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(terminal): bound concurrency and stream progress for bulk agent restarts (#849)
abhirupone8ee1571350c5
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d3c717be1..f0537a8d0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -410,9 +410,11 @@ import {clearEnvEligibility,restartEligibility,restartSessionId,+ runBoundedBulkRestart,settleRestart,summarizeBulkRestart,type BulkRestartPlan,+ type BulkRestartTask,type RestartOutcome} from '../terminal/agent-restart'import {@@ -8608,19 +8610,33 @@ export function Canvas() {onConfirm: () => {setConfirm(null)void (async () => {- const outcomes: RestartOutcome[] = []- // Sequential on purpose (spec): each restart types into its own pane and then verifies- // the echo of the resume line, and the whole canvas shares one PTY transport. The user- // gets ONE notice at the end rather than a progress UI — the run is a handful of nodes- // and each is visibly restarting in its own pane meanwhile.- for (const id of plan.runnable) {- const fn = agentRestartFn(id)- // Unmounted since the plan was made: 'not-eligible' is folded into the no-session- // skips by summarizeBulkRestart, so it is still counted. `settleRestart` turns a- // REJECTED restart into a counted failure — an escaping rejection here would abandon- // every node after it and swallow the summary the user confirmed this run for.- outcomes.push(fn ? await settleRestart(fn) : 'not-eligible')- }+ const total = plan.runnable.length+ setNotice({ kind: 'info', text: `Restarting 0/${total}…`, sticky: true })++ const activeProject = useProjects.getState().getProject(useProjects.getState().activeProjectId)+ const projectHostKey = activeProject?.ssh ? sshHostKey(activeProject.ssh.server) : undefined++ const tasks: BulkRestartTask[] = plan.runnable.map((id) => {+ const n = nodesRef.current.find((node) => node.id === id)+ const nodeHostKey = n?.data.ssh ? sshHostKey(n.data.ssh as SshServer) : projectHostKey+ return {+ id,+ hostKey: nodeHostKey,+ run: async () => {+ const fn = agentRestartFn(id)+ return fn ? await settleRestart(fn) : 'not-eligible'+ }+ }+ })++ const outcomes = await runBoundedBulkRestart(tasks, {+ onProgress: (completed, totalCount) => {+ if (completed < totalCount) {+ setNotice({ kind: 'info', text: `Restarting ${completed}/${totalCount}…`, sticky: true })+ }+ }+ })+// A line reporting failures must not fade itself out from under the user; a clean run// may. Same rule as the per-node notices above.setNotice({diff --git a/src/renderer/terminal/agent-restart.test.ts b/src/renderer/terminal/agent-restart.test.tsindex 141da6838..01199aa13 100644--- a/src/renderer/terminal/agent-restart.test.ts+++ b/src/renderer/terminal/agent-restart.test.ts@@ -17,16 +17,19 @@ import {planBulkRestart,RESTART_EXIT_TIMEOUT_MS,RESTART_LATE_EXIT_MS,+ BULK_RESTART_CONCURRENCY,registerAgentHibernate,registerAgentRestart,restartEligibility,restartSessionId,+ runBoundedBulkRestart,settleRecycledNode,settleRestart,summarizeBulkRestart,summarizeOutcomes,type AgentHibernateFns,type BulkRestartCandidate,+ type BulkRestartTask,type ExitPhaseOutcome,type RestartOutcome} from './agent-restart'@@ -1542,6 +1545,134 @@ describe('summarizeBulkRestart', () => {})})+describe('runBoundedBulkRestart (issue #849)', () => {+ it('handles an empty task list immediately', async () => {+ const progress: [number, number][] = []+ const outcomes = await runBoundedBulkRestart([], {+ onProgress: (done, total) => progress.push([done, total])+ })+ expect(outcomes).toEqual([])+ expect(progress).toEqual([])+ })++ it('preserves outcome order and streams monotonic progress updates', async () => {+ const progress: [number, number][] = []+ const tasks: BulkRestartTask[] = [+ {+ id: 'n1',+ run: async () => {+ await new Promise((r) => setTimeout(r, 20))+ return 'restarted'+ }+ },+ {+ id: 'n2',+ run: async () => {+ await new Promise((r) => setTimeout(r, 5))+ return 'exit-timeout'+ }+ },+ {+ id: 'n3',+ run: async () => {+ await new Promise((r) => setTimeout(r, 10))+ return 'not-eligible'+ }+ }+ ]++ const outcomes = await runBoundedBulkRestart(tasks, {+ concurrency: 2,+ onProgress: (done, total) => progress.push([done, total])+ })++ expect(outcomes).toEqual(['restarted', 'exit-timeout', 'not-eligible'])+ expect(progress).toEqual([+ [1, 3],+ [2, 3],+ [3, 3]+ ])+ })++ it('enforces concurrency bounds per host / ControlMaster lane', async () => {+ let currentLocalInFlight = 0+ let maxLocalInFlight = 0+ let currentSshInFlight = 0+ let maxSshInFlight = 0++ const tasks: BulkRestartTask[] = [+ ...Array.from({ length: 10 }, (_, i) => ({+ id: `local-${i}`,+ hostKey: undefined,+ run: async () => {+ currentLocalInFlight+++ maxLocalInFlight = Math.max(maxLocalInFlight, currentLocalInFlight)+ await new Promise((r) => setTimeout(r, 10))+ currentLocalInFlight--+ return 'restarted' as RestartOutcome+ }+ })),+ ...Array.from({ length: 10 }, (_, i) => ({+ id: `ssh-${i}`,+ hostKey: '[email protected]',+ run: async () => {+ currentSshInFlight+++ maxSshInFlight = Math.max(maxSshInFlight, currentSshInFlight)+ await new Promise((r) => setTimeout(r, 10))+ currentSshInFlight--+ return 'restarted' as RestartOutcome+ }+ }))+ ]++ const outcomes = await runBoundedBulkRestart(tasks, { concurrency: BULK_RESTART_CONCURRENCY })++ expect(outcomes).toHaveLength(20)+ expect(outcomes.every((o) => o === 'restarted')).toBe(true)+ expect(maxLocalInFlight).toBeLessThanOrEqual(BULK_RESTART_CONCURRENCY)+ expect(maxLocalInFlight).toBeGreaterThan(1)+ expect(maxSshInFlight).toBeLessThanOrEqual(BULK_RESTART_CONCURRENCY)+ expect(maxSshInFlight).toBeGreaterThan(1)+ })++ it('catches thrown errors and maps them to exit-timeout without failing other tasks', async () => {+ const tasks: BulkRestartTask[] = [+ {+ id: 'n1',+ run: async () => 'restarted'+ },+ {+ id: 'n2',+ run: async () => {+ throw new Error('connection dropped')+ }+ },+ {+ id: 'n3',+ run: async () => 'restarted'+ }+ ]++ const outcomes = await runBoundedBulkRestart(tasks)+ expect(outcomes).toEqual(['restarted', 'exit-timeout', 'restarted'])+ })++ it('is resilient to throwing onProgress callbacks', async () => {+ const tasks: BulkRestartTask[] = [+ { id: 'n1', run: async () => 'restarted' },+ { id: 'n2', run: async () => 'restarted' }+ ]++ const outcomes = await runBoundedBulkRestart(tasks, {+ onProgress: () => {+ throw new Error('render error in notice subscriber')+ }+ })++ expect(outcomes).toEqual(['restarted', 'restarted'])+ })+})+/*** THE `write` CONTROL VERB TAKES THIS LOCK TOO.*diff --git a/src/renderer/terminal/agent-restart.ts b/src/renderer/terminal/agent-restart.tsindex 23fc7afca..0b820b205 100644--- a/src/renderer/terminal/agent-restart.ts+++ b/src/renderer/terminal/agent-restart.ts@@ -857,3 +857,84 @@ export function summarizeOutcomes(if (skipped.noSession) parts.push(`${skipped.noSession} skipped (no session)`)return parts.join(' · ')}++/** Maximum concurrent agent restarts permitted per host / ControlMaster lane. */+export const BULK_RESTART_CONCURRENCY = 4++export interface BulkRestartTask {+ id: string+ /** Host / ControlMaster identity; defaults to 'local' when unspecified. */+ hostKey?: string+ run: () => Promise<RestartOutcome>+}++export interface BulkRestartRunnerOptions {+ /** Concurrency ceiling per hostKey lane. Defaults to BULK_RESTART_CONCURRENCY (4). */+ concurrency?: number+ /** Progress callback invoked each time a task settles. */+ onProgress?: (completed: number, total: number) => void+}++/**+ * Execute bulk restarts with bounded concurrency per host / ControlMaster lane (issue #849).+ *+ * Why: restarting a large canvas sequentially takes minutes with zero progress feedback.+ * Running every restart unbounded bursts SSH ControlMaster connections, which causes+ * socket timeouts and dropped sessions (incident #778).+ *+ * This runner:+ * - Groups runnable tasks into lanes by hostKey (local vs SSH host);+ * - Runs up to `concurrency` (default 4) tasks per lane in parallel;+ * - Invokes `onProgress(completed, total)` after each node settles;+ * - Preserves outcome ordering matching the input task array.+ */+export async function runBoundedBulkRestart(+ tasks: BulkRestartTask[],+ options?: BulkRestartRunnerOptions+): Promise<RestartOutcome[]> {+ const total = tasks.length+ if (total === 0) return []++ const concurrency = Math.max(1, options?.concurrency ?? BULK_RESTART_CONCURRENCY)+ const onProgress = options?.onProgress+ const outcomes: RestartOutcome[] = new Array(total)++ const lanes = new Map<string, { task: BulkRestartTask; index: number }[]>()+ for (let i = 0; i < total; i++) {+ const task = tasks[i]+ const laneKey = task.hostKey ?? 'local'+ let lane = lanes.get(laneKey)+ if (!lane) {+ lane = []+ lanes.set(laneKey, lane)+ }+ lane.push({ task, index: i })+ }++ let completed = 0++ const lanePromises = Array.from(lanes.values()).map(async (laneTasks) => {+ let nextIndex = 0++ async function worker(): Promise<void> {+ while (nextIndex < laneTasks.length) {+ const current = laneTasks[nextIndex++]+ const outcome = await settleRestart(current.task.run)+ outcomes[current.index] = outcome+ completed+++ try {+ onProgress?.(completed, total)+ } catch {+ // Progress reporting should never interrupt execution.+ }+ }+ }++ const workerCount = Math.min(concurrency, laneTasks.length)+ const workers = Array.from({ length: workerCount }, () => worker())+ await Promise.all(workers)+ })++ await Promise.all(lanePromises)+ return outcomes+}