The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Simplify session close across global workspaces (#541)
Dee606cdf15a34d
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 8c4f94b75..4fab5e865 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -8,7 +8,8 @@ import { fileURLToPath } from 'url'import { AGENT_OPENED_THROTTLE_MS, BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow, grokHistoryPage } from './backendSocket.js'import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'-import type { TerminalStreamManager } from './lib/terminalStreamManager.js'+import { TerminalStreamManager } from './lib/terminalStreamManager.js'+import type { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'import { registry, type RegisteredSession } from './lib/registry.js'import { stoppedAgents } from './lib/stoppedAgents.js'@@ -27,9 +28,73 @@ import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'import { LocalModels } from './lib/localModels.js'import type { GridAttachResult } from './lib/gridAttach.js'import { STRICT_DOWN_TYPES, encryptDownFrame, encryptRpcResult } from './lib/e2ee/applicationFrames.js'-import type { CloseAgentService } from './lib/closeAgentService.js'+import { CloseAgentService } from './lib/closeAgentService.js'describe('safe session close RPC', () => {+ it.each(['idle', 'working'] as const)('uses %s activity even with another live viewer', async activity => {+ const socket = new BackendSocket('fixture')+ const frames: any[] = []+ for (const connId of ['local:close', 'local:other']) {+ socket.registerLocalClient(connId, {+ sendFrame: frame => { frames.push({ connId, ...frame }); return true },+ sendBinary: () => true,+ })+ }+ const row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%7302' }], cwd: '/tmp' })!+ row.sessionId = 'close-history'+ const checkpoint = vi.fn(async () => {})+ const stop = vi.fn(async (_agentId, options) => {+ await options.checkpoint(row, 'before')+ await options.beforeStop(row)+ expect(options.current()).toBe(true)+ registry.removeAgent(row.agentId)+ })+ socket.closeAgentService = new CloseAgentService({+ registry, activity: async () => activity, checkpoint, stop, changed: () => {},+ })+ const terminals = new TerminalStreamManager({+ terminals: {+ openStream: async () => ({ state: 'succeeded', value: {+ runtime: { backend: 'tmux', paneId: '%7302' },+ beginSnapshot: () => {},+ endSnapshot: () => {},+ snapshot: async () => ({ state: 'succeeded', value: { bytes: Buffer.from('fixture'), cols: 80, rows: 24 } }),+ close: async () => {},+ } }),+ } as unknown as TerminalBackendCoordinator,+ resolveAgent: id => registry.byAgent(id),+ sendTarget: (connId, type, payload) => { frames.push({ connId, type, payload }); return true },+ sendBinaryTarget: () => true,+ streamingAvailable: true,+ })+ socket.setTerminalStreamManager(terminals)+ try {+ const opening = { agentId: row.agentId, protocolVersion: 3, cols: 80, rows: 24 }+ await terminals.handleFrame('local:close', 'terminal_open', { ...opening, requestId: 'own' })+ await terminals.handleFrame('local:other', 'terminal_open', { ...opening, requestId: 'other', takeover: false })+ expect(frames.filter(frame => frame.type === 'terminal_ready')).toHaveLength(2)+ expect(frames.find(frame => frame.payload?.requestId === 'other')?.payload.readOnly).toBe(true)+ const closing = { agentId: row.agentId, sessionId: row.sessionId, createdAt: new Date(row.registeredAt).toISOString() }+ const ask = async (mode: string) => {+ socket.handleLocalFrame('local:close', { type: 'agent_close', payload: { ...closing, mode, requestId: mode } })+ await vi.waitFor(() => expect(frames.some(frame => frame.type === 'agent_close_result' && frame.payload.requestId === mode)).toBe(true))+ return frames.find(frame => frame.type === 'agent_close_result' && frame.payload.requestId === mode).payload+ }+ expect(await ask('inspect')).toMatchObject({ activity })+ expect(await ask('idle')).toMatchObject(activity === 'idle' ? { closed: true } : { error: 'SESSION_NOT_IDLE', activity })+ if (activity === 'working') {+ expect(stop).not.toHaveBeenCalled()+ expect(await ask('now')).toMatchObject({ closed: true })+ }+ expect(checkpoint).toHaveBeenCalledOnce()+ expect(stop).toHaveBeenCalledOnce()+ expect(registry.byAgent(row.agentId)).toBeUndefined()+ } finally {+ registry.removeAgent(row.agentId)+ await socket.stop()+ }+ })+it('requires encrypted remote frames and never blocks unrelated inventory while saving', async () => {const socket = new BackendSocket('fixture')const frames: any[] = []diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 1e0fdf21f..e655747dd 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -3034,8 +3034,7 @@ export class BackendSocket {reply(type, requestId, { error: 'INVALID_CLOSE_REQUEST' }); return}// Saving/exit may take seconds; terminal input and unrelated agents keep flowing.- void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode },- () => this.terminalStreams?.hasOtherViews(agentId, connId) ?? false)+ void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode }).then(result => reply(type, requestId, result), () => reply(type, requestId, { error: 'CLOSE_FAILED' }))return}diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex 6aa282ffa..5090af345 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -39,6 +39,7 @@ it('backs up an idle session before stopping, without treating a tab switch as C})it.each<CloseActivity>(['working', 'needs_input', 'draft', 'unknown'])('leaves %s work alive until explicitly approved', async activity => {vi.mocked(deps.activity).mockResolvedValue(activity)+ expect(await service.request(request('inspect'))).toEqual({ activity })expect(await service.request(request())).toEqual({ error: 'SESSION_NOT_IDLE', activity })expect(deps.stop).not.toHaveBeenCalled()expect(await service.request(request('now'))).toEqual({ closed: true })@@ -57,18 +58,6 @@ it('rechecks activity after the checkpoint so newly started work stays alive', aexpect(await service.request(request())).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'working' })expect(registry.byAgent(row.agentId)).toBe(row)})-it('requires an explicit choice when another window is using an idle session', async () => {- expect(await service.request(request('inspect'), () => true)).toEqual({ activity: 'in_use' })- expect(await service.request(request('idle'), () => true)).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'in_use' })- expect(deps.stop).not.toHaveBeenCalled()- expect(await service.request(request('now'), () => true)).toEqual({ closed: true })-})-it('does not stop if another view opens during the backup', async () => {- let opened = false- vi.mocked(deps.checkpoint).mockImplementation(async () => { opened = true })- expect(await service.request(request(), () => opened)).toEqual({ error: 'SESSION_NOT_IDLE', activity: 'in_use' })- expect(registry.byAgent(row.agentId)).toBe(row)-})it('checkpoint failure retains the session and reports the failure', async () => {vi.mocked(deps.checkpoint).mockRejectedValue(Object.assign(new Error('Disk full'), { code: 'HISTORY_NOT_SAVED' }))expect(await service.request(request())).toMatchObject({ error: 'HISTORY_NOT_SAVED', detail: 'Disk full' })diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex caf801628..e81d50762 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -8,7 +8,7 @@ import { terminalRouteKey } from './terminalRuntime.js'import type { StopAgentOptions } from './stopAgentService.js'import { resumeMode } from './resumeCapability.js'-export type CloseActivity = 'idle' | 'working' | 'needs_input' | 'draft' | 'in_use' | 'unknown'+export type CloseActivity = 'idle' | 'working' | 'needs_input' | 'draft' | 'unknown'export type CloseMode = 'inspect' | 'idle' | 'now' | 'after_task' | 'cancel'export type AgentClosePlan = {id: string@@ -82,7 +82,7 @@ export class CloseAgentService {if (!this.pending().length && this.timer) { clearTimeout(this.timer); this.timer = null }}- request(request: AgentCloseRequest, otherViews: () => boolean = () => false): Promise<AgentCloseResult> {+ request(request: AgentCloseRequest): Promise<AgentCloseResult> {const current = this.deps.registry.byAgent(request.agentId)if (!matches(current, request)) return Promise.resolve({ error: 'AGENT_CHANGED' })if (request.mode === 'cancel') { this.cancel(request.agentId); return Promise.resolve({ cancelled: true }) }@@ -90,7 +90,7 @@ export class CloseAgentService {if (pending) return pendingconst target = identity(current)const revision = this.revisions.get(request.agentId) ?? 0- const job = this.execute(request, target, revision, otherViews).finally(() => {+ const job = this.execute(request, target, revision).finally(() => {if (this.jobs.get(request.agentId) === job) this.jobs.delete(request.agentId)this.schedule()})@@ -98,7 +98,7 @@ export class CloseAgentService {return job}- private async execute(request: AgentCloseRequest, target: string, revision: number, otherViews: () => boolean): Promise<AgentCloseResult> {+ private async execute(request: AgentCloseRequest, target: string, revision: number): Promise<AgentCloseResult> {const current = () => {const s = this.deps.registry.byAgent(request.agentId)return !this.disposed && (this.revisions.get(request.agentId) ?? 0) === revision@@ -108,8 +108,9 @@ export class CloseAgentService {const s = current()if (!s) return { error: 'AGENT_CHANGED' }const observed = await this.deps.activity(s)- const activity = otherViews() ? 'in_use'- : observed === 'idle' && (!s.sessionId || resumeMode(s.engine) !== 'conversation') ? 'unknown' : observed+ // Close belongs to the global workspace. Other viewers do not change+ // whether the session has unfinished work.+ const activity = observed === 'idle' && (!s.sessionId || resumeMode(s.engine) !== 'conversation') ? 'unknown' : observedif (!current()) return { error: 'AGENT_CHANGED' }if (request.mode === 'inspect') return { activity }if (request.mode === 'after_task') {@@ -122,13 +123,12 @@ export class CloseAgentService {}if (request.mode === 'idle' && activity !== 'idle') return { error: 'SESSION_NOT_IDLE', activity }await this.deps.stop(s.agentId, {- current: () => !!current() && (request.mode === 'now' || !otherViews()),+ current: () => !!current(),checkpoint: (s, phase) => this.deps.checkpoint(s, request.mode === 'now', phase),beforeStop: async () => {const latest = current()if (!latest) throw new Error('The session changed while saving. Please try again.')if (request.mode !== 'now') {- if (otherViews()) throw new CloseRefused('in_use')const activity = await this.deps.activity(latest)if (activity !== 'idle') throw new CloseRefused(activity)if (!current()) throw new Error('The session changed while saving. Please try again.')diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.tsindex 267c5cd32..4ccd20eca 100644--- a/cli/src/lib/terminalStreamManager.spec.ts+++ b/cli/src/lib/terminalStreamManager.spec.ts@@ -113,18 +113,6 @@ describe('TerminalStreamManager', () => {vi.useRealTimers()})- it('reports other windows until their views actually close, including watchers', async () => {- const payload = { agentId: 'agent-1', viewId: 'v', requestId: 'r', protocolVersion: 3, cols: 120, rows: 40 }- await manager.handleFrame('web-1', 'terminal_open', payload)- expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(false)- expect(manager.hasOtherViews('agent-1', 'web-2')).toBe(true)- await manager.handleFrame('web-2', 'terminal_open', { ...payload, requestId: 'r2' })- expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(true)- expect(manager.hasOtherViews('unrelated', 'web-1')).toBe(false)- await manager.closeConnection('web-2')- expect(manager.hasOtherViews('agent-1', 'web-1')).toBe(false)- })-it('publishes the complete engine catalog without a client whitelist', async () => {await manager.handleFrame('web-1', 'terminal_capabilities', { requestId: 'r1' })const result = sent.at(-1)!diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.tsindex 260bb38e7..1775db305 100644--- a/cli/src/lib/terminalStreamManager.ts+++ b/cli/src/lib/terminalStreamManager.ts@@ -227,12 +227,6 @@ export class TerminalStreamManager {this.expiryTimer.unref?.()}- /** Closing a quiet pane must not silently stop a session open in another window/device. */- hasOtherViews(agentId: string, connId: string): boolean {- return [...this.streams.values()].some(stream =>- stream.agentId === agentId && stream.connId !== connId && !stream.closing)- }-private async withLeaseLock<T>(key: string, operation: () => Promise<T>): Promise<T> {const previous = this.leaseLocks.get(key) ?? Promise.resolve()let release!: () => voiddiff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex 2bbe06366..e8b1df6d7 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -251,10 +251,11 @@ Window-only preview collections are test/render fixtures, not a user setting.Per-machine runtime state is `MachineState` (connection status, transport mode, agents, `nodeOnline`from `node_status` pushes — distinct from our own socket status, pending offline agent, turn activity).-Explicit pane/tab Close uses `requestClosePane` / `requestCloseSwarm`. Closing the last local view-of an owned idle session saves its native conversation and terminal snapshot before releasing its-process. Working, unknown, draft, or other-device sessions require a reviewed decision; Cancel is-the default. Stop after finishing persists a daemon-owned plan, and reopening cancels it. Layout+Explicit pane/tab Close uses `requestClosePane` / `requestCloseSwarm` and closes the session across+the global workspace. An owned idle session saves its native conversation and terminal snapshot+before releasing its process, regardless of other viewers. Working, waiting-for-input, draft, or+unknown sessions show one short sentence with Cancel and Close; there is no title or deferred-close+button. Cancel is the default. Previously queued daemon close plans remain compatible. Layoutcleanup, moving panes, switching tabs, and sign-out retain their view-only behavior. A failed saveor unconfirmed close keeps the pane. Older daemons retain their existing behavior until updated.diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.mdindex 065ee97b4..e39f371e5 100644--- a/desktop/design/desktop-ui-migration.md+++ b/desktop/design/desktop-ui-migration.md@@ -434,3 +434,26 @@ unmerged.was replaced or launched. Native viewer interaction, physical IME and VoiceOverremain unverified. Human-readable project names, scope changes, per-sessionprivacy controls and a delivery/usefulness view remain outstanding.++### Global session close, 2026-10-01++- Explicit Close saves and ends the session across the global workspace. Other+ viewers do not require confirmation, and other tabs showing the closed session+ are removed. Confirmed idle sessions close silently; unfinished or uncertain+ work still requires a decision. Save failures retain the pane.+- The confirmation has no title: “Still working. Close anyway?” with Cancel and+ Close. Waiting for input, unsent text and uncertain activity use the same short+ pattern. Cancel retains initial keyboard focus; the session name remains in+ accessibility semantics. Previously queued deferred closes remain compatible+ in the daemon, but the dialog no longer offers that action.+- 51 desktop tests and 273 CLI tests pass, including another live viewer,+ unfinished work, failed saves, hidden-tab cleanup, desk sync and history.+ Scoped Flutter analysis, the CLI type check and CLI bundle pass. The normal+ macOS debug build and signature verification pass; no installed app was+ replaced or launched.+- Real-font synthetic renders were inspected in both appearances at normal and+ 200% text: [dark](../../docs/research/2026-10-01-session-close/dark-1.0x.png),+ [light](../../docs/research/2026-10-01-session-close/light-1.0x.png),+ [narrow dark](../../docs/research/2026-10-01-session-close/dark-2.0x.png),+ [narrow light](../../docs/research/2026-10-01-session-close/light-2.0x.png).+ Live native interaction and VoiceOver are not claimed by these widget renders.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex eecb93dbd..1161b8ca3 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1777,18 +1777,6 @@ class AppNotifier extends ChangeNotifier {for (final pane in closing) {final id = pane.agentId;if (pane.isWeb || id == null || !seen.add((pane.machineId, id))) continue;- // The same pane object may belong to several tabs. Only its last view- // closes the underlying session, even when another tab is hidden.- final remains = swarms.any(- (other) => other.panes.any(- (p) =>- !p.isWeb &&- p.machineId == pane.machineId &&- p.agentId == id &&- (!identical(other, tab) || !closing.contains(p)),- ),- );- if (remains) continue;final machine = stateOf(pane.machineId);final agent = machine?.agents.where((a) => a.id == id).firstOrNull;if (machine?.machine.isShared == true ||@@ -1818,6 +1806,26 @@ class AppNotifier extends ChangeNotifier {}if (!_authWorkCurrent(revision) || !swarms.contains(tab)) return;await finish();+ // Close is global: the acknowledged session also leaves any other+ // tab holding it. Preserve each layout through the normal close path.+ for (final (machineId, agent) in targets) {+ final current = stateOf(machineId)?.agents+ .where((candidate) => candidate.id == agent.id)+ .firstOrNull;+ if (current?.isStopped != true ||+ current?.createdAt != agent.createdAt ||+ current?.sessionId != agent.sessionId) {+ continue;+ }+ for (final other in swarms.toList()) {+ for (final pane in other.panes.toList()) {+ if (!_authWorkCurrent(revision)) return;+ if (pane.machineId == machineId && pane.agentId == agent.id) {+ await closePane(pane.id, swarmId: other.id);+ }+ }+ }+ }} catch (_) {if (_authWorkCurrent(revision)) {_lastError = 'Could not close this session safely. Check its state and try again.';diff --git a/desktop/lib/widgets/session_close_dialog.dart b/desktop/lib/widgets/session_close_dialog.dartindex cd7e678ac..055d82880 100644--- a/desktop/lib/widgets/session_close_dialog.dart+++ b/desktop/lib/widgets/session_close_dialog.dart@@ -7,7 +7,7 @@ import 'desktop_chrome.dart';import 'desktop_prompt_surface.dart';import 'terminal_prompt.dart';-/// A close decision names its consequence. Cancel is the default, never Stop.+/// Only unfinished or uncertain work needs a decision. Cancel is the default.Future<String?> showSessionCloseDialog(BuildContext context,Agent agent,@@ -59,78 +59,42 @@ class _SessionClosePromptState extends State<_SessionClosePrompt> {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);- final hasConversation =- widget.agent.sessionId?.isNotEmpty == true &&- widget.agent.resumeMode != 'fresh' &&- widget.agent.resumeMode != 'shell';final description = switch (widget.activity) {- 'working' => 'This session is still working. Stop now, or let it finish in the background and close afterward.',- 'needs_input' => 'This session is waiting for input. If you close after finishing, it stays available in Harness Monitor until you answer and its work finishes.',- 'draft' => 'There is unsent text in this session. Stop now saves a terminal snapshot without sending it. Your saved conversation is kept.',- 'in_use' => 'This session is open in another window or device. Stopping it ends the running session there too. Switching tabs keeps it running.',- _ => 'Harness could not confirm that this session is idle. You can stop it now, or keep it running until its work finishes.',+ 'working' => 'Still working. Close anyway?',+ 'needs_input' => 'Waiting for input. Close anyway?',+ 'draft' => 'Unsent text. Close anyway?',+ _ => 'May still be working. Close anyway?',};return TerminalPromptKeys(focusNode: _keys,cancel: _choose,- child: DesktopPromptSurface(- body: DesktopPromptScrollBody(- controller: _scroll,- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Text(- widget.error == null- ? 'Close session'- : 'Could not close session',- style: DesktopChrome.heading(),- ),- const SizedBox(height: DesktopChrome.groupGap),- Text(- widget.agent.displayName,- style: DesktopChrome.text(size: 14, medium: true),- ),- const SizedBox(height: DesktopChrome.groupGap),- Text(- widget.error ?? description,- style: DesktopChrome.text(size: 13),- ),- if (widget.error == null) ...[- const SizedBox(height: 8),- Text(- hasConversation- ? 'Saved history stays on disk. Reopen it from Open Harness or Harness Monitor.'- : 'This session has not saved a conversation yet. A terminal snapshot is kept; reopening starts a new conversation.',- style: DesktopChrome.text(- size: 13,- color: DesktopChrome.muted,- ),- ),- ],- ],- ),- ),- actions: [- TextButton(- focusNode: _cancel,- onPressed: _choose,- child: Text(widget.error == null ? 'Cancel' : 'OK'),+ child: Semantics(+ namesRoute: true,+ label: widget.agent.displayName,+ child: DesktopPromptSurface(+ body: DesktopPromptScrollBody(+ controller: _scroll,+ child: Text(+ widget.error ?? description,+ style: DesktopChrome.text(size: 13),+ ),),- if (widget.error == null) ...[- FilledButton(- key: const Key('session-close-now'),- style: grid.dangerButtonStyle(),- onPressed: () => _choose('now'),- child: const Text('Stop now'),+ actions: [+ TextButton(+ focusNode: _cancel,+ onPressed: _choose,+ child: Text(widget.error == null ? 'Cancel' : 'OK'),),- if (hasConversation)+ if (widget.error == null) ...[FilledButton(- key: const Key('session-close-after'),- onPressed: () => _choose('after_task'),- child: const Text('Stop after finishing'),+ key: const Key('session-close-now'),+ style: grid.dangerButtonStyle(),+ onPressed: () => _choose('now'),+ child: const Text('Close'),),+ ],],- ],+ ),),);}diff --git a/desktop/test/session_close_dialog_test.dart b/desktop/test/session_close_dialog_test.dartnew file mode 100644index 000000000..19b4656c2--- /dev/null+++ b/desktop/test/session_close_dialog_test.dart@@ -0,0 +1,108 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/widgets/desktop_prompt_surface.dart';+import 'package:harness/widgets/session_close_dialog.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;++void main() {+ final renderDir = Platform.environment['SESSION_CLOSE_RENDER_DIR'];+ setUpAll(() async {+ if (renderDir != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ for (final scale in [1.0, 2.0]) {+ testWidgets('${brightness.name} close prompt at ${scale}x', (+ tester,+ ) async {+ final previousBrightness = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = scale == 1+ ? const Size(800, 500)+ : const Size(360, 320);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final picture = GlobalKey();+ var dismissed = false;+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: RepaintBoundary(key: picture, child: child!),+ ),+ home: Builder(+ builder: (context) => Scaffold(+ body: Center(+ child: TextButton(+ onPressed: () async {+ final result = await showSessionCloseDialog(+ context,+ Agent(+ id: 'fixture',+ name: 'Example session',+ engine: 'codex',+ ),+ 'working',+ );+ expect(result, isNull);+ dismissed = true;+ },+ child: const Text('Open'),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open'));+ await tester.pumpAndSettle();+ final message = find.text('Still working. Close anyway?');+ final cancel = find.widgetWithText(TextButton, 'Cancel');+ final close = find.widgetWithText(FilledButton, 'Close');+ expect(message, findsOneWidget);+ expect(tester.widget<TextButton>(cancel).focusNode!.hasFocus, isTrue);+ // Enlarged text can scroll; the visible body must stay above actions.+ expect(+ tester.getBottomLeft(find.byType(DesktopPromptScrollBody)).dy,+ lessThan(tester.getTopLeft(cancel).dy),+ );+ expect(+ tester.getBottomRight(close).dy,+ lessThan(tester.view.physicalSize.height),+ );+ expect(tester.takeException(), isNull);++ if (renderDir != null) {+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 2);+ final data = await image.toByteData(format: ui.ImageByteFormat.png);+ Directory(renderDir).createSync(recursive: true);+ await File('$renderDir/${brightness.name}-${scale}x.png')+ .writeAsBytes(data!.buffer.asUint8List());+ image.dispose();+ });+ }+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(dismissed, isTrue);+ expect(message, findsNothing);+ });+ }+ }+}diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dartindex 290e44233..deccdb44a 100644--- a/desktop/test/session_close_test.dart+++ b/desktop/test/session_close_test.dart@@ -111,8 +111,11 @@ void main() {await mount(tester, app);unawaited(app.requestClosePane(pane.id));await tester.pumpAndSettle();- expect(find.text('Stop now'), findsOneWidget);- expect(find.text('Stop after finishing'), findsOneWidget);+ expect(find.text('Still working. Close anyway?'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, 'Close'), findsOneWidget);+ expect(find.byType(FilledButton), findsOneWidget);+ expect(find.text('Close session'), findsNothing);+ expect(find.text('Stop after finishing'), findsNothing);expect(tester.widget<TextButton>(find.widgetWithText(TextButton, 'Cancel'))@@ -128,22 +131,29 @@ void main() {},);- for (final choice in ['now', 'after']) {- testWidgets('working Close $choice sends only the reviewed action', (+ for (final entry in {+ 'working': 'Still working. Close anyway?',+ 'needs_input': 'Waiting for input. Close anyway?',+ 'draft': 'Unsent text. Close anyway?',+ 'unknown': 'May still be working. Close anyway?',+ }.entries) {+ testWidgets('${entry.key} Close sends only the reviewed action', (tester,) async {- connection.activities['a0'] = 'working';+ connection.activities['a0'] = entry.key;final pane = app.adoptSessionForTest(terminal('a0', []));await mount(tester, app);unawaited(app.requestClosePane(pane.id));await tester.pumpAndSettle();- await tester.tap(find.byKey(Key('session-close-$choice')));+ expect(find.text(entry.value), findsOneWidget);+ expect(modes(), ['inspect']);+ await tester.tap(find.widgetWithText(FilledButton, 'Close'));await tester.pumpAndSettle();- expect(modes(), ['inspect', choice == 'now' ? 'now' : 'after_task']);+ expect(modes(), ['inspect', 'now']);expect(app.allPanes, isEmpty);expect(app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,- choice == 'now',+ isTrue,);expect(app.closedHistory, hasLength(1));await tester.pumpWidget(const SizedBox());@@ -193,7 +203,7 @@ void main() {},);- testWidgets('another hidden tab showing the same session keeps it live', (+ testWidgets('Close also removes the session from another hidden tab', (tester,) async {final pane = app.adoptSessionForTest(terminal('a0', []));@@ -204,9 +214,13 @@ void main() {await mount(tester, app);await app.requestClosePane(pane.id);await tester.pumpAndSettle();- expect(connection.closes, isEmpty);- expect(original.panes, [pane]);- expect(app.stateOf('m')!.agents.first.terminalAvailable, isTrue);+ expect(modes(), ['inspect', 'idle']);+ expect(app.allPanes, isEmpty);+ expect(app.swarms, isNot(contains(original)));+ expect(+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').isStopped,+ isTrue,+ );await tester.pumpWidget(const SizedBox());});diff --git a/docs/research/2026-10-01-session-close/dark-1.0x.png b/docs/research/2026-10-01-session-close/dark-1.0x.pngnew file mode 100644index 000000000..57dee2433Binary files /dev/null and b/docs/research/2026-10-01-session-close/dark-1.0x.png differdiff --git a/docs/research/2026-10-01-session-close/dark-2.0x.png b/docs/research/2026-10-01-session-close/dark-2.0x.pngnew file mode 100644index 000000000..9e4554410Binary files /dev/null and b/docs/research/2026-10-01-session-close/dark-2.0x.png differdiff --git a/docs/research/2026-10-01-session-close/light-1.0x.png b/docs/research/2026-10-01-session-close/light-1.0x.pngnew file mode 100644index 000000000..e9a8b6a73Binary files /dev/null and b/docs/research/2026-10-01-session-close/light-1.0x.png differdiff --git a/docs/research/2026-10-01-session-close/light-2.0x.png b/docs/research/2026-10-01-session-close/light-2.0x.pngnew file mode 100644index 000000000..bc7eb2d9fBinary files /dev/null and b/docs/research/2026-10-01-session-close/light-2.0x.png differ