Skip to content

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.

feat(run): switch a running Flutter app between checkouts without rebuilding (#1174)

Senzaikene040c9c35394
diff --git a/CLAUDE.md b/CLAUDE.md
index d85310cf0..4f67186c5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2029,7 +2029,26 @@ tmux's `history-limit` keeps the raw value.
`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":
+ rows; a run that ends without our Stop says where to look; (6) **switching folders keeps the app
+ when it can** (`canHotSwitch`: a running Flutter run, same device, same flavor, Flutter on both
+ sides): the toolbar offers **Switch (keep app)** beside **Rebuild** — type `d` (flutter's own
+ detach: the tool exits, the app keeps running), `flutter attach` from the new folder (only the
+ flags attach accepts survive, `attachArgs`, MEASURED against `flutter attach --help` — attach has
+ no `--flavor`), wait until it prints its key help AFTER its own `▶ flutter attach` line
+ (`attachConnected`), then a hot RESTART — never a reload: a freshly attached tool only pushes
+ files changed after it connected (MEASURED live, Flutter 3.47 / iOS 27.1 simulator: a reload
+ after attaching from the other checkout "Reloaded 0 libraries" and the old code kept running; a
+ SIGUSR2 restart swapped it in 2.6 s, same app pid, no rebuild). **On an iOS simulator attach
+ needs `--debug-url`**: it finds an already-running app by mDNS, which the simulator barely
+ supports ("The Dart VM Service was not discovered after 30 seconds"), and the URL `flutter run`
+ printed is its DDS proxy, gone with the detached tool. `simulatorVmServiceUrl` reads the app's
+ own "The Dart VM service is listening on …" line from `simctl spawn <udid> log show` (~3 s) and
+ takes the newest one whose process is still alive (`parseVmServiceLog`); not found ⇒ the switch
+ is refused with Rebuild offered. Some Macs ship no registered `Simulator.app` (`open -a
+ Simulator` fails); booting falls back to the active Xcode's copy and otherwise runs headless. Flutter REFUSES a hand-passed `FLUTTER_APP_FLAVOR`, so after an
+ attach `appFlavor` is the pubspec default; an app whose `lib/` reads `appFlavor` is refused the
+ switch with that reason. Dart `"request": "attach"` configurations run as `flutter attach` too;
+ every other attach is still refused. 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
diff --git a/src/core/run-service.test.ts b/src/core/run-service.test.ts
index 7765ea0f6..fab9377e6 100644
--- a/src/core/run-service.test.ts
+++ b/src/core/run-service.test.ts
@@ -131,6 +131,33 @@ describe('run-service', () => {
expect(await startRun('../x', { projectDir: w, reloadOnSave: true })).toMatchObject({ ok: false })
})
+ it('switch mode writes a flutter attach launcher; refuses non-Flutter runs and apps that read appFlavor', async () => {
+ write('app/pubspec.yaml', PUBSPEC)
+ write('app/lib/main_dev.dart', 'void main() {}')
+ write('app/.vscode/launch.json', `{ "configurations": [
+ { "name": "Dev", "type": "dart", "request": "launch", "program": "lib/main_dev.dart", "args": ["--flavor", "dev", "--web-port=8080"] },
+ { "name": "Tool", "type": "node", "request": "launch", "program": "a.js" }
+ ] }`)
+ const app = path.join(root, 'app')
+ const r = await startRun('n8', { projectDir: app, launchConfig: 'Dev', deviceId: 'SIM-1', reloadOnSave: true }, { attach: true })
+ expect(r).toMatchObject({ ok: true, kind: 'process', hotReload: true })
+ const script = readFileSync(launcherPath('n8'), 'utf8')
+ expect(script).toContain(`'flutter' 'attach' '-t' 'lib/main_dev.dart' '-d' 'SIM-1' '--pid-file' '${flutterPidFile('n8')}'`)
+ expect(script).not.toContain('--flavor')
+ expect(script).not.toContain('--web-port')
+
+ expect(await startRun('n8', { projectDir: app, launchConfig: 'Tool', reloadOnSave: true }, { attach: true })).toMatchObject({
+ ok: false,
+ error: expect.stringMatching(/not a Flutter run/)
+ })
+
+ write('app/lib/flavor.dart', "import 'package:flutter/services.dart'; final f = appFlavor;")
+ expect(await startRun('n8', { projectDir: app, launchConfig: 'Dev', deviceId: 'SIM-1', reloadOnSave: true }, { attach: true })).toEqual({
+ ok: false,
+ error: 'This app reads appFlavor, which flutter attach cannot set — rebuild to switch.'
+ })
+ })
+
describe('on a Windows core', () => {
const real = Object.getOwnPropertyDescriptor(process, 'platform') as PropertyDescriptor
beforeEach(() => Object.defineProperty(process, 'platform', { value: 'win32' }))
diff --git a/src/core/run-service.ts b/src/core/run-service.ts
index 20f5246c3..d9372559d 100644
--- a/src/core/run-service.ts
+++ b/src/core/run-service.ts
@@ -19,6 +19,7 @@ import {
parseEnvFile,
parseLaunchFile,
parseTasksFile,
+ parseVmServiceLog,
planLaunch,
resolveEntry,
RUN_WINDOWS_REASON,
@@ -218,12 +219,63 @@ export async function bootSimulator(udid: unknown): Promise<boolean> {
if (!/current state: Booted/i.test(String((e as { stderr?: string }).stderr ?? (e as Error).message))) return false
}
devicesCache = null
+ await openSimulatorApp()
+ return true
+}
+
+/**
+ * Show Simulator.app, best effort. `open -a Simulator` needs LaunchServices to know the app, and on
+ * a machine where it does not (MEASURED: a Mac whose Xcode ships no registered Simulator.app —
+ * "Unable to find application named 'Simulator'") the bundle inside the active Xcode is tried. A
+ * machine with neither runs its simulators headless, which is fine: the app runs either way.
+ */
+async function openSimulatorApp(): Promise<void> {
try {
await run('/usr/bin/open', ['-a', 'Simulator'], { timeout: 15_000 })
+ return
} catch {
- /* booted either way; the window is a convenience */
+ /* try the active Xcode's own copy */
}
- return true
+ try {
+ const { stdout } = await run('/usr/bin/xcode-select', ['-p'], { timeout: 5_000 })
+ await run('/usr/bin/open', [path.join(stdout.trim(), 'Applications', 'Simulator.app')], { timeout: 15_000 })
+ } catch {
+ /* headless simulators — nothing to show */
+ }
+}
+
+/**
+ * The running Flutter app's own VM service URL on an iOS simulator — read from the simulator's
+ * log (see `parseVmServiceLog` for why attach needs it). The newest announcement whose process is
+ * still alive wins; an app that started long ago is found by widening the window once.
+ */
+export async function simulatorVmServiceUrl(udid: string): Promise<string | null> {
+ if (process.platform !== 'darwin' || !SIMULATOR_UDID.test(udid)) return null
+ let alive: Set<string> | null = null
+ try {
+ const { stdout } = await run('/usr/bin/xcrun', ['simctl', 'spawn', udid, 'launchctl', 'list'], { timeout: 15_000, maxBuffer: 8 * 1024 * 1024 })
+ alive = new Set(stdout.split('\n').map((l) => l.split('\t')[0]).filter((p) => /^\d+$/.test(p)))
+ } catch {
+ return null
+ }
+ for (const window of ['1h', '24h']) {
+ let text = ''
+ try {
+ text = (
+ await run(
+ '/usr/bin/xcrun',
+ ['simctl', 'spawn', udid, 'log', 'show', '--style', 'compact', '--last', window, '--predicate', 'eventMessage CONTAINS "Dart VM service is listening on"'],
+ { timeout: 90_000, maxBuffer: 16 * 1024 * 1024 }
+ )
+ ).stdout
+ } catch {
+ continue
+ }
+ const hits = parseVmServiceLog(text).reverse()
+ const live = hits.find((h) => alive?.has(h.pid))
+ if (live) return live.url
+ }
+ return null
}
// ─── Project discovery ───────────────────────────────────────────────────────────────────────
@@ -305,7 +357,43 @@ function referencedEnv(...values: unknown[]): string[] {
return names
}
-export async function startRun(nodeId: unknown, rawConfig: unknown): Promise<RunStartResult> {
+/**
+ * Does the app's own Dart code read `appFlavor`? `flutter attach` has no `--flavor`, and Flutter
+ * REFUSES a hand-passed `FLUTTER_APP_FLAVOR` define (flutter_command.dart,
+ * `_ensureReservedDartDefineIsUnset`), so after an attach + hot restart `appFlavor` falls back to
+ * the pubspec's default flavor — the wrong answer for an app that branches on it. Bounded scan of
+ * `lib/` (the app's code; packages are not the app's choice). A read failure answers "no".
+ */
+async function readsAppFlavor(dir: string): Promise<boolean> {
+ const stack = [path.join(dir, 'lib')]
+ let files = 0
+ while (stack.length && files < 4000) {
+ const d = stack.pop() as string
+ let entries: import('node:fs').Dirent[]
+ try {
+ entries = await readdir(d, { withFileTypes: true })
+ } catch {
+ continue
+ }
+ for (const e of entries) {
+ const p = path.join(d, e.name)
+ if (e.isDirectory()) stack.push(p)
+ else if (e.name.endsWith('.dart')) {
+ files++
+ try {
+ if ((await readFile(p, 'utf8')).includes('appFlavor')) return true
+ } catch {
+ /* unreadable — not evidence */
+ }
+ }
+ }
+ }
+ return false
+}
+
+export async function startRun(nodeId: unknown, rawConfig: unknown, rawOpts?: unknown): Promise<RunStartResult> {
+ // `attach`: switch a running Flutter app to this folder without rebuilding it (see canHotSwitch).
+ const attach = !!rawOpts && typeof rawOpts === 'object' && (rawOpts as { attach?: unknown }).attach === true
if (!validNode(nodeId)) return { ok: false, error: 'Invalid node.' }
const config = normalizeRunConfig(rawConfig)
if (!config) return { ok: false, error: 'Choose a folder first.' }
@@ -331,7 +419,32 @@ export async function startRun(nodeId: unknown, rawConfig: unknown): Promise<Run
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 ?? [] }
+ if (entry.kind === 'compound') {
+ if (attach) return { ok: false, error: 'A compound cannot be switched to — rebuild instead.' }
+ return { ok: true, kind: 'compound', members: entry.members ?? [] }
+ }
+ let debugUrl: string | undefined
+ if (attach) {
+ if (!entry.hotReload || entry.typeLabel !== 'Flutter') {
+ return { ok: false, error: `“${entry.name}” is not a Flutter run — it cannot be switched to without a rebuild.` }
+ }
+ if (entry.flavor && (await readsAppFlavor(dir))) {
+ return {
+ ok: false,
+ error: 'This app reads appFlavor, which flutter attach cannot set — rebuild to switch.'
+ }
+ }
+ // On an iOS simulator attach cannot discover the running app by itself; hand it the URL.
+ if (config.deviceId && SIMULATOR_UDID.test(config.deviceId)) {
+ debugUrl = (await simulatorVmServiceUrl(config.deviceId)) ?? undefined
+ if (!debugUrl) {
+ return {
+ ok: false,
+ error: 'Could not find the running app on the simulator (no VM service URL in its log) — Rebuild to switch.'
+ }
+ }
+ }
+ }
const cfg = file.configs.find((c) => c.name === entry.name) as LaunchConfig
const tasks = await readTasks(dir)
@@ -349,7 +462,7 @@ export async function startRun(nodeId: unknown, rawConfig: unknown): Promise<Run
extraArgs: config.extraArgs,
flutterPidFile: flutterPidFile(nodeId),
tasks
- })
+ }, { attach, debugUrl })
if (!planned.ok) return planned
const plan = planned.plan
if (plan.kind === 'browser') return { ok: true, kind: 'browser', url: plan.url }
@@ -535,7 +648,7 @@ export function registerRunConfigIpc(): void {
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.runStart, (nodeId: unknown, config: unknown, opts: unknown) => startRun(nodeId, config, opts))
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))
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 9cc7047cc..df707d48c 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -585,7 +585,7 @@ const api: NodeTerminalApi = {
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),
+ start: (nodeId, config, opts) => ipcRenderer.invoke(IPC.runStart, nodeId, config, opts),
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),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 61d027b31..58981073f 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -1122,7 +1122,7 @@ export function buildRunConfigApi(client: RpcClient): Pick<NodeTerminalApi, 'run
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>,
+ start: (nodeId, config, opts) => client.request(IPC.runStart, nodeId, config, opts) 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>,
diff --git a/src/renderer/nodes/RunBar.tsx b/src/renderer/nodes/RunBar.tsx
index 98cc2b2ab..dee18b6b6 100644
--- a/src/renderer/nodes/RunBar.tsx
+++ b/src/renderer/nodes/RunBar.tsx
@@ -1,6 +1,8 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useReactFlow, useStore } from '@xyflow/react'
import {
+ attachConnected,
+ canHotSwitch,
deviceClaims,
resolveEntry,
runDirLabel,
@@ -9,6 +11,7 @@ import {
type RunDevice,
type RunEntriesResult,
type RunNodeConfig,
+ type RunSnapshot,
type RunStatus
} from '@shared/run-config'
import { isShellCommand } from '@shared/agents/pane'
@@ -38,7 +41,7 @@ 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
+type Busy = 'booting' | 'starting' | 'stopping' | 'reloading' | 'restarting' | 'switching' | null
const CHOOSE_FOLDER = '\u0000choose'
const NO_ENTRY = '\u0000none'
@@ -100,6 +103,8 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
const cfgRef = useRef(config)
cfgRef.current = config
+ /** The entry the node resolves to now (kept current below), for callbacks and the status poll. */
+ const entryRef = useRef<LaunchEntry | undefined>(undefined)
const running = !!status?.running
const say = useCallback((kind: 'error' | 'info', text: string) => setNote({ kind, text }), [])
@@ -155,6 +160,7 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
[entries, config.launchConfig]
)
const wantsDevices = entries.some((e) => e.usesDevice)
+ entryRef.current = entry
const loadDevices = useCallback(
(refresh: boolean) => {
@@ -173,9 +179,18 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
// 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)
+ /** What the live run was started from — what a folder switch must match to keep the app.
+ * Set at Run; recovered from the node's config when the run was already going at mount (the
+ * config cannot have changed before this view existed to change it). Cleared when it ends. */
+ const runningRef = useRef<RunSnapshot | null>(null)
const pollStatus = useCallback(async () => {
const s = await api.runConfig.status(nodeId)
if (!mounted.current) return s.running
+ if (!s.running && !stoppingRef.current) runningRef.current = null
+ if (s.running && !runningRef.current && entryRef.current) {
+ const c = cfgRef.current
+ runningRef.current = { projectDir: c.projectDir, deviceId: c.deviceId, flavor: entryRef.current.flavor, hotReload: entryRef.current.hotReload }
+ }
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.` })
@@ -284,6 +299,7 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
await start({ launchConfig: first })
return
}
+ runningRef.current = { projectDir: cfg.projectDir, deviceId: cfg.deviceId, flavor: target?.flavor, hotReload: r.hotReload }
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.')
@@ -334,6 +350,73 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
await start()
}, [running, stop, start])
+ /**
+ * Switch the running Flutter app to the node's (new) folder WITHOUT rebuilding it:
+ * 1. `d` — flutter run/attach's own "detach": the tool exits, the app keeps running;
+ * 2. `flutter attach` from the new folder, to the same device;
+ * 3. once it has connected, a hot RESTART (SIGUSR2). Not a reload: a freshly attached tool only
+ * pushes files that change after it connected, so the new checkout's code would mostly not
+ * reach the app. A restart pushes the whole program — the app's state resets, nothing native
+ * is rebuilt.
+ * Every failure leaves the app running and says so; Rebuild stays one click away.
+ */
+ const switchKeepApp = useCallback(async () => {
+ const cfg = cfgRef.current
+ setBusy('switching')
+ stoppingRef.current = true
+ await api.pty.sendText(nodeId, 'd', { enter: false })
+ const detached = await waitStopped(10_000)
+ stoppingRef.current = false
+ if (!detached) {
+ setBusy(null)
+ say('error', 'The running tool did not detach — open ⋯ to check the terminal.')
+ return
+ }
+ const r = await api.runConfig.start(nodeId, cfg, { attach: true })
+ if (!r.ok || r.kind !== 'process') {
+ setBusy(null)
+ say('error', `${r.ok ? 'Could not attach.' : r.error} The app is still running on the device; Rebuild restarts it from this folder.`)
+ return
+ }
+ const sent = await api.pty.sendText(nodeId, r.command)
+ if (sent !== true) {
+ setBusy(null)
+ say('error', sent === 'pasted-not-submitted' ? 'The attach command is in the terminal — press Enter.' : 'Could not type into this terminal.')
+ return
+ }
+ // Wait for the attach to connect (it prints its key help once it has). Discovering the app
+ // can take a while on a busy simulator; an attach that exits early has failed.
+ let connected = false
+ let sawRunning = false
+ const deadline = Date.now() + 120_000
+ while (mounted.current && Date.now() < deadline) {
+ if (attachConnected(await api.pty.capture(nodeId))) {
+ connected = true
+ break
+ }
+ const alive = await pollStatus()
+ if (alive) sawRunning = true
+ else if (sawRunning) break
+ await sleep(700)
+ }
+ if (!mounted.current) return
+ if (!connected) {
+ setBusy(null)
+ say('error', 'flutter attach did not connect — open ⋯ to see why. Rebuild starts the app from this folder.')
+ return
+ }
+ const restarted = await api.runConfig.signal(nodeId, 'restart')
+ runningRef.current = { projectDir: cfg.projectDir, deviceId: cfg.deviceId, flavor: entryRef.current?.flavor, hotReload: true }
+ setNeedsRerun(false)
+ setBusy(null)
+ say(
+ restarted ? 'info' : 'error',
+ restarted
+ ? `Switched to ${runDirLabel(cfg.projectDir)} without rebuilding — hot restarted (the app's state was reset).`
+ : 'Attached, but the hot restart failed — press R in the terminal.'
+ )
+ }, [api, nodeId, waitStopped, pollStatus, say])
+
const signal = useCallback(
async (kind: 'reload' | 'restart') => {
setBusy(kind === 'reload' ? 'reloading' : 'restarting')
@@ -460,6 +543,9 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
)
const browser = !!entry?.browser
+ // Folder/configuration changed under a running Flutter app that the new choice would build the
+ // same way: offer to switch without rebuilding (canHotSwitch states the rule).
+ const hotSwitch = canHotSwitch(runningRef.current, { config, entry })
const canRun = !!entry?.supported && !busy
const statusText =
busy === 'booting'
@@ -472,6 +558,8 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
? 'Hot reload'
: busy === 'restarting'
? 'Hot restart'
+ : busy === 'switching'
+ ? 'Switching…'
: running
? 'Running'
: status?.exitCode
@@ -612,7 +700,29 @@ export function RunBar({ nodeId, config, autoStart }: Props) {
</button>
)
)}
- {needsRerun && running && (
+ {needsRerun && running && hotSwitch && (
+ <>
+ <button
+ type="button"
+ className="run-bar__btn run-bar__btn--accent"
+ title="Keep the app on the device: detach, attach from the new folder, hot restart. Its state resets; nothing native is rebuilt."
+ disabled={!!busy}
+ onClick={() => void switchKeepApp()}
+ >
+ ⇄ Switch (keep app)
+ </button>
+ <button
+ type="button"
+ className="run-bar__btn"
+ title="Stop and run again from scratch — needed when the folders differ in native code (plugins, ios/, Info.plist)"
+ disabled={!!busy}
+ onClick={() => void restart()}
+ >
+ Rebuild
+ </button>
+ </>
+ )}
+ {needsRerun && running && !hotSwitch && (
<button
type="button"
className="run-bar__btn run-bar__btn--accent"
diff --git a/src/shared/run-config.test.ts b/src/shared/run-config.test.ts
index c6363a375..dcf6ef70b 100644
--- a/src/shared/run-config.test.ts
+++ b/src/shared/run-config.test.ts
@@ -1,17 +1,23 @@
import { describe, expect, it } from 'vitest'
import {
DEFAULT_FLUTTER_ENTRY,
+ attachArgs,
+ attachConnected,
buildLauncher,
+ canHotSwitch,
defaultFlutterConfig,
describeConfig,
describeLaunchFile,
deviceClaims,
+ flavorOf,
+ isVmServiceUrl,
gateEntriesForPlatform,
normalizeRunConfig,
parseEnvFile,
parseJsonc,
parseLaunchFile,
parseTasksFile,
+ parseVmServiceLog,
planLaunch,
planTask,
resolveEntry,
@@ -19,7 +25,8 @@ import {
runNodeTitle,
type LaunchConfig,
type PlanContext,
- type ProcessPlan
+ type ProcessPlan,
+ type RunNodeConfig
} from './run-config'
const WS = '/Users/me/dev/app'
@@ -395,3 +402,110 @@ describe('presentation', () => {
expect(deviceClaims(nodes, 'a', 'sim1')).toEqual(['B'])
})
})
+
+describe('switching a running Flutter app without a rebuild', () => {
+ it('reads the flavor in either form', () => {
+ expect(flavorOf(['--flavor', 'dev'])).toBe('dev')
+ expect(flavorOf(['--flavor=staging'])).toBe('staging')
+ expect(flavorOf(['-d', 'x'])).toBeUndefined()
+ })
+
+ it('keeps only what flutter attach understands, dropping run-only flags with their values', () => {
+ expect(
+ attachArgs([
+ '--flavor', 'dev', '--dart-define=API=1', '-D', 'B=2', '--web-port=8080',
+ '--web-browser-flag', '--disable-web-security', '-t', 'lib/main_dev.dart', '--no-dds', '--route', '/home'
+ ])
+ ).toEqual({
+ kept: ['--dart-define=API=1', '-D', 'B=2', '-t', 'lib/main_dev.dart', '--no-dds'],
+ dropped: ['--flavor', 'dev', '--web-port=8080', '--web-browser-flag', '--disable-web-security', '--route', '/home']
+ })
+ })
+
+ it('plans flutter attach to the node device: target and dart-defines kept, flavor dropped, no preLaunchTask', () => {
+ const tasks = parseTasksFile('{ "tasks": [ { "label": "gen", "type": "shell", "command": "make" } ] }')
+ const r = planLaunch(
+ cfg({ type: 'dart', program: 'lib/main_dev.dart', args: ['--flavor', 'dev', '--dart-define=A=1'], preLaunchTask: 'gen' }),
+ ctx({ isFlutterProject: true, deviceId: 'SIM-1', tasks }),
+ { attach: true }
+ )
+ if (!r.ok || r.plan.kind !== 'process') throw new Error('expected a process plan')
+ expect(r.plan.argv).toEqual([
+ 'flutter', 'attach', '-t', 'lib/main_dev.dart', '--dart-define=A=1', '-d', 'SIM-1', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ expect(r.plan.preTasks).toEqual([])
+ expect(r.plan.hotReload).toBe(true)
+ })
+
+ it('runs a Dart "request": "attach" configuration as flutter attach, and still refuses other attaches', () => {
+ const e = describeConfig(cfg({ type: 'dart', request: 'attach', vmServiceUri: 'http://127.0.0.1:1234/x=/' }), true)
+ expect(e).toMatchObject({ supported: true, attach: true, hotReload: true })
+ const r = planLaunch(cfg({ type: 'dart', request: 'attach', vmServiceUri: 'http://127.0.0.1:1234/x=/' }), ctx({ isFlutterProject: true, deviceId: 'SIM-1' }))
+ expect(r.ok && r.plan.kind === 'process' && r.plan.argv).toEqual([
+ 'flutter', 'attach', '--debug-url', 'http://127.0.0.1:1234/x=/', '-d', 'SIM-1', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ expect(describeConfig(cfg({ type: 'dart', request: 'attach' }), false).supported).toBe(false)
+ expect(describeConfig(cfg({ type: 'node', request: 'attach' }), false).supported).toBe(false)
+ })
+
+ const entryFor = (raw: Record<string, unknown>) => describeConfig(cfg({ type: 'dart', program: 'lib/main.dart', ...raw }), true)
+ const running = { projectDir: '/a', deviceId: 'SIM-1', flavor: 'dev', hotReload: true }
+ const to = (over: Partial<RunNodeConfig> = {}, raw: Record<string, unknown> = { args: ['--flavor', 'dev'] }) => ({
+ config: { projectDir: '/b', deviceId: 'SIM-1', reloadOnSave: true, ...over },
+ entry: entryFor(raw)
+ })
+
+ it('allows the switch only for the same device and flavor, Flutter on both sides', () => {
+ expect(canHotSwitch(running, to())).toBe(true)
+ expect(canHotSwitch(running, to({ deviceId: 'SIM-2' }))).toBe(false)
+ expect(canHotSwitch(running, to({}, { args: ['--flavor', 'staging'] }))).toBe(false)
+ expect(canHotSwitch(running, to({}, { args: ['--flavor', 'dev', '-d', 'chrome'] }))).toBe(false)
+ expect(canHotSwitch(running, to({}, { program: 'test/a_test.dart', args: ['--flavor', 'dev'] }))).toBe(false)
+ expect(canHotSwitch(null, to())).toBe(false)
+ expect(canHotSwitch({ ...running, hotReload: false }, to())).toBe(false)
+ })
+
+ it('knows attach has connected only from help printed after its own launch line', () => {
+ const oldRun = 'Flutter run key commands.\nr Hot reload.\n'
+ expect(attachConnected(`${oldRun}▶ flutter attach -d SIM-1\nWaiting for a connection…\n`)).toBe(false)
+ expect(attachConnected(`${oldRun}▶ flutter attach -d SIM-1\nSyncing files…\nFlutter run key commands.\n`)).toBe(true)
+ // The launch line scrolled off: everything on screen is newer than it.
+ expect(attachConnected('…lots of output…\nFlutter run key commands.\n')).toBe(true)
+ expect(attachConnected('▶ flutter attach\n')).toBe(false)
+ })
+})
+
+describe('finding a running app on an iOS simulator', () => {
+ // Shape copied from a real `xcrun simctl spawn <udid> log show --style compact` (Flutter 3.47).
+ const LOG = [
+ 'Timestamp Ty Process[PID:TID]',
+ '2026-10-09 11:02:10.100 Df Runner[61000:7a01] (Flutter) flutter: The Dart VM service is listening on http://127.0.0.1:49999/AAAA=/',
+ '2026-10-09 12:24:00.531 Df Runner[64771:740c89a] (Flutter) flutter: The Dart VM service is listening on http://127.0.0.1:50056/OtE7vTN5nVs=/',
+ "2026-10-09 12:32:09.463 Df log[75814:0] [com.apple.log:] log run noninteractively, args: 'log' 'show' '--predicate' 'eventMessage CONTAINS \"Dart VM service is listening\"'"
+ ].join('\n')
+
+ it('reads each announcement with the pid that made it, oldest first, ignoring log show echoing its own predicate', () => {
+ expect(parseVmServiceLog(LOG)).toEqual([
+ { url: 'http://127.0.0.1:49999/AAAA=/', pid: '61000' },
+ { url: 'http://127.0.0.1:50056/OtE7vTN5nVs=/', pid: '64771' }
+ ])
+ })
+
+ it('accepts only loopback VM service URLs', () => {
+ expect(isVmServiceUrl('http://127.0.0.1:50056/OtE7vTN5nVs=/')).toBe(true)
+ expect(isVmServiceUrl('http://evil.example:80/x/')).toBe(false)
+ expect(isVmServiceUrl("http://127.0.0.1:1/'; rm -rf ~")).toBe(false)
+ })
+
+ it('passes the discovered URL to flutter attach, ahead of the config’s own', () => {
+ const r = planLaunch(
+ cfg({ type: 'dart', program: 'lib/main_dev.dart', vmServiceUri: 'http://127.0.0.1:1/old=/' }),
+ ctx({ isFlutterProject: true, deviceId: 'SIM-1' }),
+ { attach: true, debugUrl: 'http://127.0.0.1:50056/OtE7vTN5nVs=/' }
+ )
+ expect(r.ok && r.plan.kind === 'process' && r.plan.argv).toEqual([
+ 'flutter', 'attach', '-t', 'lib/main_dev.dart', '--debug-url', 'http://127.0.0.1:50056/OtE7vTN5nVs=/',
+ '-d', 'SIM-1', '--pid-file', '/data/run/n.flutter.pid'
+ ])
+ })
+})
diff --git a/src/shared/run-config.ts b/src/shared/run-config.ts
index 79a743dac..6912001fb 100644
--- a/src/shared/run-config.ts
+++ b/src/shared/run-config.ts
@@ -271,6 +271,10 @@ export interface LaunchEntry {
members?: string[]
/** The configuration's `preLaunchTask`, if any. */
preLaunchTask?: string
+ /** Flutter: the `--flavor` the configuration builds with. */
+ flavor?: string
+ /** A `"request": "attach"` configuration (Flutter: `flutter attach` to a running debug app). */
+ attach?: boolean
}
const TYPE_LABEL: Record<string, string> = {
@@ -321,6 +325,121 @@ export function pinnedDevice(raw: Record<string, unknown>): string | undefined {
return isSafeDeviceId(raw.deviceId) ? raw.deviceId : undefined
}
+/** A Dart VM service URL as the engine prints it: loopback http, a port, the auth-code path. */
+export function isVmServiceUrl(s: string): boolean {
+ return /^http:\/\/127\.0\.0\.1:\d{1,5}\/[A-Za-z0-9_=+-]*\/?$/.test(s)
+}
+
+/**
+ * The VM service URLs a Flutter app announced in an iOS simulator's log, newest last, with the pid
+ * of the process that announced each. The engine logs `The Dart VM service is listening on <url>`
+ * at startup; `log show --style compact` prefixes `<process>[<pid>:<tid>]`.
+ *
+ * Needed because `flutter attach` cannot find an ALREADY-running app on the iOS simulator — it
+ * relies on mDNS, which the simulator barely supports. MEASURED (Flutter 3.47, iOS 27.1 sim): attach
+ * printed "The Dart VM Service was not discovered after 30 seconds … use the Dart VM service URL
+ * … with flutter attach --debug-url" and never connected; with the URL from this log line it
+ * connected in 26 s. The URL `flutter run` itself printed is useless here: it is the tool's DDS
+ * proxy, which closes when that tool detaches.
+ */
+export function parseVmServiceLog(text: string): Array<{ url: string; pid: string }> {
+ const out: Array<{ url: string; pid: string }> = []
+ for (const line of text.split('\n')) {
+ if (!line.includes('Dart VM service is listening on')) continue
+ const url = /listening on (http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_=+-]*\/?)/.exec(line)?.[1]
+ const pid = /\[(\d+):/.exec(line)?.[1]
+ if (url && pid && isVmServiceUrl(url)) out.push({ url: url.endsWith('/') ? url : `${url}/`, pid })
+ }
+ return out
+}
+
+/** The `--flavor` in a Flutter argv (`--flavor x` or `--flavor=x`). */
+export function flavorOf(args: readonly string[]): string | undefined {
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--flavor' && args[i + 1]) return args[i + 1]
+ if (args[i].startsWith('--flavor=')) return args[i].slice('--flavor='.length)
+ }
+ return undefined
+}
+
+/**
+ * The `flutter run` arguments `flutter attach` also understands, and the ones it would reject.
+ * MEASURED against `flutter attach --help` (Flutter 3.47): attach takes the target, dart-defines,
+ * the app id / VM service URL and device options — and NOT `--flavor`, `--web-port`, build modes or
+ * anything else that shapes a build, because attach builds nothing. An unknown option is a hard
+ * error ("Could not find an option named …"), so passing a run argv through would kill the attach.
+ * `-d` is left out on purpose: the device is always the node's own.
+ */
+const ATTACH_VALUE_FLAGS = new Set([
+ '-t', '--target', '-D', '--dart-define', '--dart-define-from-file', '--app-id', '--debug-url',
+ '--device-timeout', '--device-user', '--dds-port', '--device-vmservice-port', '--host-vmservice-port'
+])
+const ATTACH_BOOL_FLAGS = new Set(['--track-widget-creation', '--no-track-widget-creation', '--dds', '--no-dds'])
+
+export function attachArgs(args: readonly string[]): { kept: string[]; dropped: string[] } {
+ const kept: string[] = []
+ const dropped: string[] = []
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]
+ const eq = a.indexOf('=')
+ const flag = a.startsWith('-') && eq > 0 ? a.slice(0, eq) : a
+ if (ATTACH_VALUE_FLAGS.has(flag)) {
+ if (eq > 0) kept.push(a)
+ else if (i + 1 < args.length) kept.push(a, args[++i])
+ } else if (ATTACH_BOOL_FLAGS.has(a)) {
+ kept.push(a)
+ } else if (a.startsWith('-')) {
+ // A flag attach does not know; drop its value too when it has one (`--flavor dev`).
+ dropped.push(a)
+ if (eq < 0 && i + 1 < args.length && !args[i + 1].startsWith('-') && RUN_VALUE_FLAGS.has(a)) dropped.push(args[++i])
+ } else {
+ dropped.push(a)
+ }
+ }
+ return { kept, dropped }
+}
+
+/** `flutter run` flags that take a value, so `attachArgs` drops the value with the flag. */
+const RUN_VALUE_FLAGS = new Set([
+ '--flavor', '-d', '--device-id', '--web-port', '--web-hostname', '--web-browser-flag', '--web-renderer',
+ '--route', '--dart-entrypoint-args', '-a', '--target-platform', '--build-name', '--build-number',
+ '--split-debug-info', '--obfuscation-map', '--web-launch-url', '--web-header', '--web-tls-cert-path',
+ '--web-tls-cert-key-path', '--device-connection'
+])
+
+/** What a running Flutter run was started from — enough to tell whether a switch can keep it. */
+export interface RunSnapshot {
+ projectDir: string
+ deviceId?: string
+ flavor?: string
+ hotReload: boolean
+}
+
+/**
+ * Can the node switch a running Flutter app to `to` WITHOUT rebuilding it — detach the tool, attach
+ * a new one from the new checkout, hot restart? Only when the running app is the one `to` would
+ * build: same device, same flavor, a Flutter run (not a test) on both sides. Anything native that
+ * differs between the checkouts (plugins, ios/, Info.plist) is not something this can know, which
+ * is why Rebuild stays offered beside it.
+ */
+export function canHotSwitch(from: RunSnapshot | null, to: { config: RunNodeConfig; entry: LaunchEntry | undefined }): boolean {
+ const e = to.entry
+ if (!from || !from.hotReload || !e || !e.supported || e.kind !== 'config' || !e.hotReload) return false
+ if (e.pinnedDevice) return false // a pinned device is web/desktop/explicit — attach is for the node's device
+ if (!from.deviceId || from.deviceId !== to.config.deviceId) return false
+ if ((from.flavor ?? '') !== (e.flavor ?? '')) return false
+ return true
+}
+
+/** Has `flutter attach` connected? It prints its key-command help once it has. `attachLine` is the
+ * launcher's own `▶ flutter attach …` line: the help must come AFTER it (an earlier run's help may
+ * still be on screen). When that line has scrolled away, everything on screen is newer than it. */
+export function attachConnected(screen: string): boolean {
+ const ready = Math.max(screen.lastIndexOf('Flutter run key commands'), screen.lastIndexOf('To hot restart changes'))
+ if (ready < 0) return false
+ return ready > screen.lastIndexOf('▶ flutter attach')
+}
+
/** 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
@@ -355,7 +474,10 @@ export function describeConfig(cfg: LaunchConfig, isFlutterProject: boolean): La
...(str(cfg.raw.preLaunchTask) ? { preLaunchTask: str(cfg.raw.preLaunchTask) } : {})
}
const refuse = (reason: string): LaunchEntry => ({ ...base, supported: false, reason })
- if (cfg.request !== 'launch') {
+ const flutter = cfg.type === 'dart' && (isFlutterProject || cfg.raw.flutterMode !== undefined)
+ // A Flutter attach is `flutter attach`: it connects to an app already running in debug mode.
+ // Every other attach (a debugger to a process, Xdebug, …) has nothing for us to start.
+ if (cfg.request !== 'launch' && !(cfg.request === 'attach' && flutter)) {
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.`)
@@ -364,9 +486,11 @@ export function describeConfig(cfg: LaunchConfig, isFlutterProject: boolean): La
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)
+ const flavor = flavorOf([...strArray(cfg.raw.toolArgs), ...strArray(cfg.raw.args)])
+ const attach = cfg.request === 'attach'
+ if (attach && isTest) return refuse(`“${cfg.name}” attaches to a test — tests cannot be attached to.`)
// 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 {
@@ -374,7 +498,9 @@ export function describeConfig(cfg: LaunchConfig, isFlutterProject: boolean): La
typeLabel: 'Flutter',
usesDevice: onDevice,
hotReload: !isTest,
- ...(pinned ? { pinnedDevice: pinned } : {})
+ ...(pinned ? { pinnedDevice: pinned } : {}),
+ ...(flavor ? { flavor } : {}),
+ ...(attach ? { attach: true } : {})
}
}
if (!program) return refuse(`“${cfg.name}” has no program to run.`)
@@ -601,7 +727,11 @@ export function planTask(label: string, ctx: PlanContext, depth = 0, seen = new
}
/** Turn one launch configuration into what the host runs. Pure; every refusal is a sentence. */
-export function planLaunch(cfg: LaunchConfig, ctx: PlanContext): PlanResult {
+export function planLaunch(
+ cfg: LaunchConfig,
+ ctx: PlanContext,
+ opts: { attach?: boolean; debugUrl?: string } = {}
+): PlanResult {
const entry = describeConfig(cfg, ctx.isFlutterProject)
if (!entry.supported) return { ok: false, error: entry.reason ?? 'Not supported.' }
try {
@@ -614,7 +744,8 @@ export function planLaunch(cfg: LaunchConfig, ctx: PlanContext): PlanResult {
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) : []
+ // A switch-attach runs nothing first: the app is already built and running.
+ const preTasks = str(raw.preLaunchTask) && !opts.attach ? planTask(x(raw.preLaunchTask as string), ctx) : []
const proc = (argv: string[], hotReload = false): PlanResult => ({
ok: true,
plan: {
@@ -640,6 +771,24 @@ export function planLaunch(cfg: LaunchConfig, ctx: PlanContext): PlanResult {
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])
+ if (opts.attach || entry.attach) {
+ // `flutter attach` to the app already running on the node's device. Only the arguments
+ // attach understands survive (attachArgs); dart-defines do, so constants match.
+ // The host's discovered URL wins (an iOS simulator's app cannot be found by mDNS).
+ const vm = (opts.debugUrl && isVmServiceUrl(opts.debugUrl) ? opts.debugUrl : undefined) ?? str(raw.vmServiceUri) ?? str(raw.observatoryUri)
+ const attachDevice = entry.pinnedDevice ? ['-d', entry.pinnedDevice] : ctx.deviceId ? ['-d', ctx.deviceId] : []
+ return proc(
+ [
+ 'flutter', 'attach',
+ ...(program ? ['-t', program] : []),
+ ...attachArgs([...toolArgs, ...args, ...extra]).kept,
+ ...(vm ? ['--debug-url', x(vm)] : []),
+ ...attachDevice,
+ '--pid-file', ctx.flutterPidFile
+ ],
+ true
+ )
+ }
return proc(
[
'flutter', 'run',
@@ -871,8 +1020,10 @@ export interface RunConfigApi {
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>
+ /** Prepare a run: write the launcher and return the line to type (or a URL / compound members).
+ * `attach`: `flutter attach` to the app already running on the node's device instead (the
+ * no-rebuild folder switch). */
+ start(nodeId: string, config: RunNodeConfig, opts?: { attach?: boolean }): 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>