diff --git a/app/lib/features/chat/workspace/chat_workspace.dart b/app/lib/features/chat/workspace/chat_workspace.dart new file mode 100644 index 00000000..4e9a341c --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace.dart @@ -0,0 +1,179 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'chat_workspace_controller.dart'; +import 'chat_workspace_divider.dart'; +import 'chat_workspace_geometry.dart'; + +export 'chat_workspace_controller.dart'; +export 'chat_workspace_geometry.dart' show ChatPaneDirection; + +typedef ChatWorkspacePaneBuilder = + Widget Function(BuildContext context, ChatWorkspacePane pane, bool active); + +/// All chat views are stable siblings, independent of the split tree. Moving a +/// divider or adding/removing a neighbouring split never reparents a chat view. +class ChatWorkspace extends StatefulWidget { + const ChatWorkspace({ + super.key, + required this.controller, + required this.paneBuilder, + this.onFocusPane, + this.shortcutsEnabled = true, + }); + final ChatWorkspaceController controller; + final ChatWorkspacePaneBuilder paneBuilder; + final bool shortcutsEnabled; + + /// Keyboard navigation only: the owner can focus the target composer. + /// Pointer activation leaves text-selection and pointer focus alone. + final ValueChanged? onFocusPane; + + @override + State createState() => _ChatWorkspaceState(); +} + +class _ChatWorkspaceState extends State { + final _focus = FocusNode(debugLabel: 'Chat workspace'); + final Map _panes = {}; + ChatWorkspaceGeometry? _geometry; + + @override + void initState() { + super.initState(); + HardwareKeyboard.instance.addHandler(_key); + } + + bool _key(KeyEvent event) { + if (!widget.shortcutsEnabled || + !_focus.hasFocus || + event is! KeyDownEvent) { + return false; + } + final keyboard = HardwareKeyboard.instance; + final modifier = + keyboard.isControlPressed && !keyboard.isMetaPressed || + defaultTargetPlatform == TargetPlatform.macOS && + keyboard.isMetaPressed && + !keyboard.isControlPressed; + if (!modifier || !keyboard.isShiftPressed || keyboard.isAltPressed) { + return false; + } + final direction = switch (event.logicalKey) { + LogicalKeyboardKey.arrowLeft => ChatPaneDirection.left, + LogicalKeyboardKey.arrowRight => ChatPaneDirection.right, + LogicalKeyboardKey.arrowUp => ChatPaneDirection.up, + LogicalKeyboardKey.arrowDown => ChatPaneDirection.down, + _ => null, + }; + if (direction == null) return false; + final id = widget.controller.activePaneId; + final target = id == null ? null : _geometry?.neighbor(id, direction); + if (target != null) { + widget.controller.activate(target); + final pane = widget.controller.activePane!; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || widget.controller.activePaneId != target) return; + if (widget.onFocusPane != null) { + widget.onFocusPane!(pane); + } else { + _panes[target]?.requestFocus(); + } + }); + } + // Consume a workspace navigation chord at an edge too: it must not select + // words in the current composer when there is no neighbouring pane. + return true; + } + + @override + void dispose() { + HardwareKeyboard.instance.removeHandler(_key); + _focus.dispose(); + for (final node in _panes.values) { + node.dispose(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) => Focus( + focusNode: _focus, + child: ListenableBuilder( + listenable: widget.controller, + builder: (context, _) => LayoutBuilder( + builder: (context, constraints) { + final root = widget.controller.root; + if (root == null) return const SizedBox.shrink(); + final geometry = ChatWorkspaceGeometry(root, constraints.biggest); + _geometry = geometry; + final panes = widget.controller.panes; + final existing = panes.map((p) => p.id).toSet(); + for (final id + in _panes.keys.where((id) => !existing.contains(id)).toList()) { + final node = _panes.remove(id)!; + WidgetsBinding.instance.addPostFrameCallback((_) => node.dispose()); + } + return Stack( + fit: StackFit.expand, + clipBehavior: Clip.hardEdge, + children: [ + for (final pane in panes) + Positioned.fromRect( + key: ValueKey('chat-workspace-${pane.id}'), + rect: geometry.collapsed + ? Offset.zero & constraints.biggest + : geometry.panes[pane.id]!, + child: Offstage( + offstage: + geometry.collapsed && + pane.id != widget.controller.activePaneId, + child: ExcludeFocus( + excluding: + geometry.collapsed && + pane.id != widget.controller.activePaneId, + child: FocusScope( + node: _panes.putIfAbsent( + pane.id, + () => FocusScopeNode(debugLabel: pane.id), + ), + onFocusChange: (focused) { + if (focused) widget.controller.activate(pane.id); + }, + child: Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (_) => + widget.controller.activate(pane.id), + child: Semantics( + identifier: 'chat-pane-${pane.id}', + container: true, + child: widget.paneBuilder( + context, + pane, + pane.id == widget.controller.activePaneId, + ), + ), + ), + ), + ), + ), + ), + if (!geometry.collapsed) + for (final divider in geometry.dividers) + Positioned.fromRect( + key: ValueKey('chat-workspace-${divider.split.id}'), + rect: divider.rect, + child: ChatWorkspaceDivider( + geometry: divider, + onChanged: (ratio) => + widget.controller.resize(divider.split.id, ratio), + ), + ), + ], + ); + }, + ), + ), + ); +} diff --git a/app/lib/features/chat/workspace/chat_workspace_controller.dart b/app/lib/features/chat/workspace/chat_workspace_controller.dart new file mode 100644 index 00000000..5ed65efc --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_controller.dart @@ -0,0 +1,177 @@ +import 'package:flutter/foundation.dart'; + +enum ChatSplitAxis { horizontal, vertical } + +sealed class ChatWorkspaceNode { + const ChatWorkspaceNode(this.id); + final String id; +} + +class ChatWorkspacePane extends ChatWorkspaceNode { + const ChatWorkspacePane(super.id, this.sessionId); + final String sessionId; +} + +class ChatWorkspaceSplit extends ChatWorkspaceNode { + const ChatWorkspaceSplit( + super.id, + this.axis, + this.first, + this.second, { + this.ratio = .5, + }); + final ChatSplitAxis axis; + final ChatWorkspaceNode first, second; + final double ratio; +} + +/// Visit-local layout. Pane identities survive nested splits and resizing. +class ChatWorkspaceController extends ChangeNotifier { + ChatWorkspaceNode? _root; + String? _active; + int _serial = 0; + ChatWorkspaceNode? get root => _root; + String? get activePaneId => _active; + int get paneCount => panes.length; + List get panes => _panes(_root).toList(); + ChatWorkspacePane? get activePane => + panes.where((p) => p.id == _active).firstOrNull; + + Iterable _panes(ChatWorkspaceNode? node) sync* { + if (node is ChatWorkspacePane) yield node; + if (node is ChatWorkspaceSplit) { + yield* _panes(node.first); + yield* _panes(node.second); + } + } + + String _id(String kind) => 'chat-$kind-${++_serial}'; + + /// Ordinary opening replaces the active pane; an already-open chat is focused. + void open(String sessionId) { + if (sessionId.isEmpty) return; + final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull; + if (existing != null) { + activate(existing.id); + return; + } + if (_root == null) { + final pane = ChatWorkspacePane(_id('pane'), sessionId); + _root = pane; + _active = pane.id; + } else { + final target = activePane ?? panes.first; + _root = _replace( + _root!, + target.id, + ChatWorkspacePane(target.id, sessionId), + ); + _active = target.id; + } + notifyListeners(); + } + + void splitActive(String sessionId, ChatSplitAxis axis) { + if (sessionId.isEmpty) return; + if (_root == null) { + open(sessionId); + return; + } + final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull; + if (existing != null) { + activate(existing.id); + return; + } + final target = activePane ?? panes.first; + final added = ChatWorkspacePane(_id('pane'), sessionId); + _root = _replace( + _root!, + target.id, + ChatWorkspaceSplit(_id('split'), axis, target, added), + ); + _active = added.id; + notifyListeners(); + } + + void activate(String paneId) { + if (_active == paneId || !panes.any((p) => p.id == paneId)) return; + _active = paneId; + notifyListeners(); + } + + void resize(String splitId, double ratio) { + if (_root == null || !ratio.isFinite) return; + _root = _resize(_root!, splitId, ratio.clamp(.01, .99)); + notifyListeners(); + } + + void close(String paneId) { + final before = panes; + final index = before.indexWhere((p) => p.id == paneId); + if (index < 0) return; + _root = _remove(_root!, paneId); + final after = panes; + if (_active == paneId) { + _active = after.isEmpty + ? null + : after[index.clamp(0, after.length - 1)].id; + } + notifyListeners(); + } + + void replaceSession(String oldId, String newId) { + if (oldId == newId || newId.isEmpty) return; + final pane = panes.where((p) => p.sessionId == oldId).firstOrNull; + if (pane == null) return; + final existing = panes.where((p) => p.sessionId == newId).firstOrNull; + if (existing != null) { + close(pane.id); + activate(existing.id); + return; + } + _root = _replace(_root!, pane.id, ChatWorkspacePane(pane.id, newId)); + notifyListeners(); + } + + ChatWorkspaceNode _replace( + ChatWorkspaceNode node, + String id, + ChatWorkspaceNode replacement, + ) { + if (node.id == id) return replacement; + if (node is! ChatWorkspaceSplit) return node; + return ChatWorkspaceSplit( + node.id, + node.axis, + _replace(node.first, id, replacement), + _replace(node.second, id, replacement), + ratio: node.ratio, + ); + } + + ChatWorkspaceNode _resize(ChatWorkspaceNode node, String id, double ratio) { + if (node is! ChatWorkspaceSplit) return node; + return ChatWorkspaceSplit( + node.id, + node.axis, + _resize(node.first, id, ratio), + _resize(node.second, id, ratio), + ratio: node.id == id ? ratio : node.ratio, + ); + } + + ChatWorkspaceNode? _remove(ChatWorkspaceNode node, String id) { + if (node.id == id) return null; + if (node is! ChatWorkspaceSplit) return node; + final first = _remove(node.first, id), second = _remove(node.second, id); + if (first == null) return second; + if (second == null) return first; + return ChatWorkspaceSplit( + node.id, + node.axis, + first, + second, + ratio: node.ratio, + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace_divider.dart b/app/lib/features/chat/workspace/chat_workspace_divider.dart new file mode 100644 index 00000000..003e031d --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_divider.dart @@ -0,0 +1,112 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'chat_workspace_controller.dart'; +import 'chat_workspace_geometry.dart'; + +/// A standard separator with a mouse/touch grab area and keyboard resizing. +class ChatWorkspaceDivider extends StatefulWidget { + const ChatWorkspaceDivider({ + super.key, + required this.geometry, + required this.onChanged, + }); + final ChatWorkspaceDividerGeometry geometry; + final ValueChanged onChanged; + + @override + State createState() => _ChatWorkspaceDividerState(); +} + +class _ChatWorkspaceDividerState extends State { + double? _drag; + bool _hovered = false, _focused = false; + bool get _horizontal => + widget.geometry.split.axis == ChatSplitAxis.horizontal; + double get _available => + (_horizontal + ? widget.geometry.container.width + : widget.geometry.container.height) - + chatPaneDividerExtent; + double get _actual => + (_horizontal + ? widget.geometry.rect.left - widget.geometry.container.left + : widget.geometry.rect.top - widget.geometry.container.top) / + _available; + void _change(double value) => widget.onChanged( + value.clamp(widget.geometry.minimum, widget.geometry.maximum), + ); + void _step(double value) => _change(_actual + value / _available); + + @override + Widget build(BuildContext context) { + final verticalLine = _horizontal; + final color = usesCupertinoHost(context) + ? CupertinoColors.separator.resolveFrom(context) + : Theme.of(context).dividerColor; + return Semantics( + identifier: 'chat-divider-${widget.geometry.split.id}', + label: 'Resize chat panes ${_horizontal ? 'horizontally' : 'vertically'}', + value: '${(_actual * 100).round()} percent', + increasedValue: + '${((_actual + 16 / _available).clamp(widget.geometry.minimum, widget.geometry.maximum) * 100).round()} percent', + decreasedValue: + '${((_actual - 16 / _available).clamp(widget.geometry.minimum, widget.geometry.maximum) * 100).round()} percent', + onIncrease: () => _step(16), + onDecrease: () => _step(-16), + child: Focus( + onFocusChange: (value) => setState(() => _focused = value), + onKeyEvent: (_, event) { + if (event is! KeyDownEvent && event is! KeyRepeatEvent) { + return KeyEventResult.ignored; + } + final negative = _horizontal + ? LogicalKeyboardKey.arrowLeft + : LogicalKeyboardKey.arrowUp; + final positive = _horizontal + ? LogicalKeyboardKey.arrowRight + : LogicalKeyboardKey.arrowDown; + if (event.logicalKey != negative && event.logicalKey != positive) { + return KeyEventResult.ignored; + } + _step(event.logicalKey == negative ? -16 : 16); + return KeyEventResult.handled; + }, + child: MouseRegion( + cursor: _horizontal + ? SystemMouseCursors.resizeColumn + : SystemMouseCursors.resizeRow, + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onDoubleTap: () => _change(.5), + onPanStart: (_) => setState(() => _drag = _actual), + onPanUpdate: (details) { + _drag = + (_drag ?? _actual) + + (_horizontal ? details.delta.dx : details.delta.dy) / + _available; + _change(_drag!); + }, + onPanEnd: (_) => setState(() => _drag = null), + onPanCancel: () => setState(() => _drag = null), + child: Center( + child: Container( + width: verticalLine + ? (_hovered || _focused || _drag != null ? 3 : 1) + : null, + height: verticalLine + ? null + : (_hovered || _focused || _drag != null ? 3 : 1), + color: color, + ), + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/workspace/chat_workspace_geometry.dart b/app/lib/features/chat/workspace/chat_workspace_geometry.dart new file mode 100644 index 00000000..c1e6ac9d --- /dev/null +++ b/app/lib/features/chat/workspace/chat_workspace_geometry.dart @@ -0,0 +1,150 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'chat_workspace_controller.dart'; + +const chatPaneMinimumWidth = 240.0; +const chatPaneMinimumHeight = 200.0; +const chatPaneDividerExtent = 12.0; + +enum ChatPaneDirection { left, right, up, down } + +class ChatWorkspaceDividerGeometry { + const ChatWorkspaceDividerGeometry( + this.split, + this.rect, + this.container, + this.minimum, + this.maximum, + ); + final ChatWorkspaceSplit split; + final Rect rect, container; + final double minimum, maximum; +} + +/// Geometry is separate from widget ancestry: leaf widgets remain siblings. +class ChatWorkspaceGeometry { + ChatWorkspaceGeometry(ChatWorkspaceNode root, Size size) { + final minimum = minimumSize(root); + collapsed = size.width < minimum.width || size.height < minimum.height; + _layout( + root, + Offset.zero & + Size( + math.max(size.width, minimum.width), + math.max(size.height, minimum.height), + ), + ); + } + final Map panes = {}; + final List dividers = []; + late final bool collapsed; + + static Size minimumSize(ChatWorkspaceNode node) { + if (node is ChatWorkspacePane) { + return const Size(chatPaneMinimumWidth, chatPaneMinimumHeight); + } + final split = node as ChatWorkspaceSplit; + final a = minimumSize(split.first), b = minimumSize(split.second); + return split.axis == ChatSplitAxis.horizontal + ? Size( + a.width + b.width + chatPaneDividerExtent, + math.max(a.height, b.height), + ) + : Size( + math.max(a.width, b.width), + a.height + b.height + chatPaneDividerExtent, + ); + } + + void _layout(ChatWorkspaceNode node, Rect bounds) { + if (node is ChatWorkspacePane) { + panes[node.id] = bounds; + return; + } + final split = node as ChatWorkspaceSplit; + final horizontal = split.axis == ChatSplitAxis.horizontal; + final a = minimumSize(split.first), b = minimumSize(split.second); + final available = + (horizontal ? bounds.width : bounds.height) - chatPaneDividerExtent; + final low = horizontal ? a.width : a.height; + final high = available - (horizontal ? b.width : b.height); + final extent = (available * split.ratio) + .clamp(low, math.max(low, high)) + .toDouble(); + final divider = horizontal + ? Rect.fromLTWH( + bounds.left + extent, + bounds.top, + chatPaneDividerExtent, + bounds.height, + ) + : Rect.fromLTWH( + bounds.left, + bounds.top + extent, + bounds.width, + chatPaneDividerExtent, + ); + dividers.add( + ChatWorkspaceDividerGeometry( + split, + divider, + bounds, + low / available, + high / available, + ), + ); + _layout( + split.first, + horizontal + ? Rect.fromLTWH(bounds.left, bounds.top, extent, bounds.height) + : Rect.fromLTWH(bounds.left, bounds.top, bounds.width, extent), + ); + _layout( + split.second, + horizontal + ? Rect.fromLTWH( + divider.right, + bounds.top, + available - extent, + bounds.height, + ) + : Rect.fromLTWH( + bounds.left, + divider.bottom, + bounds.width, + available - extent, + ), + ); + } + + String? neighbor(String active, ChatPaneDirection direction) { + final origin = panes[active]; + if (origin == null) return null; + final horizontal = + direction == ChatPaneDirection.left || + direction == ChatPaneDirection.right; + String? best; + var score = double.infinity; + for (final entry in panes.entries) { + if (entry.key == active) continue; + final candidate = entry.value; + final inDirection = switch (direction) { + ChatPaneDirection.left => candidate.right <= origin.left, + ChatPaneDirection.right => candidate.left >= origin.right, + ChatPaneDirection.up => candidate.bottom <= origin.top, + ChatPaneDirection.down => candidate.top >= origin.bottom, + }; + if (!inDirection) continue; + final delta = candidate.center - origin.center; + final primary = horizontal ? delta.dx.abs() : delta.dy.abs(); + final secondary = horizontal ? delta.dy.abs() : delta.dx.abs(); + final next = primary + secondary * 2; + if (next < score) { + score = next; + best = entry.key; + } + } + return best; + } +} diff --git a/app/notes/chat-split-workspace.md b/app/notes/chat-split-workspace.md new file mode 100644 index 00000000..0f399f10 --- /dev/null +++ b/app/notes/chat-split-workspace.md @@ -0,0 +1,11 @@ +# Split chat workspace primitives + +`chat_workspace.dart` exposes `ChatWorkspace`, `ChatWorkspaceController`, pane/split node types and `ChatSplitAxis`. The visit-local controller opens/replaces the active pane, focuses an already-open chat, splits the active pane to its right or below, replaces a session identity after `/new`, activates panes and closes/collapses splits. Pane IDs survive tree edits. + +The renderer computes tree geometry but keeps every chat view as a stable keyed sibling in one Stack. Nested splits, divider drags and closing adjacent panes never reparent the existing chat view. When the viewport cannot fit the tree's minimum sizes, only the active chat paints, with all other leaves retained offstage and excluded from focus. The root screen supplies its pane switcher and per-pane bars. + +Each divider has a 12px grab area, a native theme separator, horizontal/vertical resize cursors, pointer dragging, arrow-key adjustments, accessibility increase/decrease values and double-click reset. Geometry clamps visible panes to 240px wide and 200px high while preserving the saved ratio across viewport changes. + +Ctrl+Shift+Arrow navigates spatially between panes. Command+Shift+Arrow also works on macOS. Chords are consumed at edges so they do not alter composer selection. The handler is gated by workspace focus and `shortcutsEnabled`; pointer activation does not request composer focus. The owner supplies `onFocusPane` for keyboard-only composer focus after layout. No sockets, requests or timers are introduced by these primitives. + +Checks: bounded analysis clean; eight watchdog tests passed, peak663MB,3s (`/tmp/memwatch/out.7uae7k`). Tests assert actual horizontal/vertical dragging and clamping, nested close collapse, leaf State/draft identity, narrow fallback/restoration, keyboard divider resizing/reset, spatial geometry, Ctrl navigation and macOS Command navigation without changing drafts. Commands from app/: `tool/analyze.sh lib/features/chat/workspace test/features/chat/workspace` and `tool/memwatch/full.sh 'test/features/chat/workspace --no-pub'`. Full-app integration and rendered captures are the manager's next check; no production services or chats were touched. diff --git a/app/test/features/chat/workspace/chat_workspace_test.dart b/app/test/features/chat/workspace/chat_workspace_test.dart new file mode 100644 index 00000000..0bd6d4c9 --- /dev/null +++ b/app/test/features/chat/workspace/chat_workspace_test.dart @@ -0,0 +1,308 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_divider.dart'; +import 'package:pipelines_app/features/chat/workspace/chat_workspace_geometry.dart'; + +Widget host( + ChatWorkspaceController controller, { + double width = 1000, + double height = 800, + ValueChanged? onFocus, +}) => MaterialApp( + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: width, + height: height, + child: ChatWorkspace( + controller: controller, + onFocusPane: onFocus, + paneBuilder: (_, pane, active) => + _Draft(key: ValueKey(pane.sessionId), name: pane.sessionId), + ), + ), + ), + ), +); + +class _Draft extends StatefulWidget { + const _Draft({super.key, required this.name}); + final String name; + @override + State<_Draft> createState() => _DraftState(); +} + +class _DraftState extends State<_Draft> { + final text = TextEditingController(); + @override + void dispose() { + text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + TextField(key: ValueKey('input-${widget.name}'), controller: text); +} + +void main() { + test( + 'split tree preserves IDs and closes nested siblings without losing layout', + () { + final controller = ChatWorkspaceController()..open('one'); + addTearDown(controller.dispose); + final first = controller.activePaneId!; + controller.splitActive('two', ChatSplitAxis.horizontal); + final second = controller.activePaneId!; + controller.splitActive('three', ChatSplitAxis.vertical); + expect(controller.panes.map((p) => p.sessionId), ['one', 'two', 'three']); + expect(controller.panes.first.id, first); + controller.close(second); + expect(controller.panes.map((p) => p.sessionId), ['one', 'three']); + controller.close(first); + expect(controller.root, isA()); + controller.close(controller.activePaneId!); + expect(controller.root, isNull); + }, + ); + + test('open activates existing chats and replaces only the active pane', () { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + final second = controller.activePaneId; + controller.open('one'); + expect(controller.activePane?.sessionId, 'one'); + controller.open('three'); + expect(controller.panes.map((p) => p.sessionId), ['three', 'two']); + expect(controller.panes.last.id, second); + controller.replaceSession('two', 'new-two'); + expect(controller.panes.last.sessionId, 'new-two'); + }); + + test( + 'geometry clamps visible sizes but retains ratios and spatial neighbors', + () { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + final split = controller.root! as ChatWorkspaceSplit; + controller.resize(split.id, .9); + var geometry = ChatWorkspaceGeometry( + controller.root!, + const Size(700, 600), + ); + expect( + geometry.panes.values.every((r) => r.width >= chatPaneMinimumWidth), + isTrue, + ); + expect((controller.root! as ChatWorkspaceSplit).ratio, .9); + controller.splitActive('three', ChatSplitAxis.vertical); + geometry = ChatWorkspaceGeometry(controller.root!, const Size(1000, 700)); + final one = controller.panes[0], + two = controller.panes[1], + three = controller.panes[2]; + expect(geometry.neighbor(two.id, ChatPaneDirection.down), three.id); + expect(geometry.neighbor(three.id, ChatPaneDirection.up), two.id); + expect(geometry.neighbor(one.id, ChatPaneDirection.up), isNull); + expect( + ChatWorkspaceGeometry(controller.root!, const Size(320, 600)).collapsed, + isTrue, + ); + }, + ); + + testWidgets( + 'both dividers drag, clamp and preserve draft state through nested changes', + (tester) async { + tester.view.physicalSize = const Size(1200, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller)); + await tester.enterText( + find.byKey(const ValueKey('input-one')), + 'one draft', + ); + final state = tester.state(find.byKey(const ValueKey('one'))); + final split = controller.root! as ChatWorkspaceSplit; + final divider = find.byType(ChatWorkspaceDivider); + await tester.drag(divider, const Offset(120, 0)); + await tester.pump(); + expect((controller.root! as ChatWorkspaceSplit).ratio, greaterThan(.5)); + controller.activate(controller.panes.last.id); + controller.splitActive('three', ChatSplitAxis.vertical); + await tester.pump(); + expect(tester.state(find.byKey(const ValueKey('one'))), same(state)); + final vertical = find.byWidgetPredicate( + (w) => + w is ChatWorkspaceDivider && + w.geometry.split.axis == ChatSplitAxis.vertical, + ); + await tester.drag(vertical, const Offset(0, 80)); + await tester.pump(); + final nested = + (controller.root! as ChatWorkspaceSplit).second as ChatWorkspaceSplit; + expect(nested.ratio, greaterThan(.5)); + await tester.drag( + find.byWidgetPredicate( + (w) => w is ChatWorkspaceDivider && w.geometry.split.id == split.id, + ), + const Offset(2000, 0), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 500)); + expect(tester.takeException(), isNull); + controller.close(controller.activePaneId!); + await tester.pump(); + expect(tester.state(find.byKey(const ValueKey('one'))), same(state)); + expect( + tester + .widget(find.byKey(const ValueKey('input-one'))) + .controller! + .text, + 'one draft', + ); + }, + ); + + testWidgets( + 'divider keyboard resizing and double-click reset use the same limits', + (tester) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller, width: 700, height: 500)); + final divider = find.byType(ChatWorkspaceDivider); + final gesture = find.descendant( + of: divider, + matching: find.byType(GestureDetector), + ); + Focus.of(tester.element(gesture)).requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect((controller.root! as ChatWorkspaceSplit).ratio, greaterThan(.5)); + await tester.tap(divider); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(divider); + await tester.pump(const Duration(milliseconds: 500)); + expect((controller.root! as ChatWorkspaceSplit).ratio, .5); + }, + ); + + testWidgets( + 'narrow fallback keeps hidden drafts mounted and restores split ratios', + (tester) async { + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + await tester.pumpWidget(host(controller, width: 700, height: 500)); + await tester.enterText(find.byKey(const ValueKey('input-one')), 'draft'); + final original = tester.state(find.byKey(const ValueKey('one'))); + controller.activate(controller.panes.last.id); + await tester.pumpWidget(host(controller, width: 320, height: 500)); + expect(find.byKey(const ValueKey('input-one')), findsNothing); + expect( + find.byKey(const ValueKey('input-one'), skipOffstage: false), + findsOneWidget, + ); + await tester.pumpWidget(host(controller, width: 700, height: 500)); + expect(tester.state(find.byKey(const ValueKey('one'))), same(original)); + expect( + tester + .widget(find.byKey(const ValueKey('input-one'))) + .controller! + .text, + 'draft', + ); + }, + ); + + testWidgets( + 'Ctrl Shift arrows navigate from a composer and consume edge chords', + (tester) async { + tester.view.physicalSize = const Size(1200, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + final focused = []; + await tester.pumpWidget( + host(controller, onFocus: (pane) => focused.add(pane.sessionId)), + ); + await tester.tap(find.byKey(const ValueKey('input-one'))); + await tester.pump(); + expect(controller.activePane?.sessionId, 'one'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(controller.activePane?.sessionId, 'two'); + expect(focused, ['two']); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(focused, ['two']); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + expect( + tester + .widget(find.byKey(const ValueKey('input-one'))) + .controller! + .text, + isEmpty, + ); + }, + ); + testWidgets( + 'Command Shift arrows navigate on macOS without modifying drafts', + (tester) async { + tester.view.physicalSize = const Size(1200, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final controller = ChatWorkspaceController() + ..open('one') + ..splitActive('two', ChatSplitAxis.horizontal); + addTearDown(controller.dispose); + final focused = []; + await tester.pumpWidget( + host(controller, onFocus: (pane) => focused.add(pane.sessionId)), + ); + await tester.enterText( + find.byKey(const ValueKey('input-one')), + 'original', + ); + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + expect(controller.activePane?.sessionId, 'two'); + expect(focused, ['two']); + expect( + tester + .widget(find.byKey(const ValueKey('input-one'))) + .controller! + .text, + 'original', + ); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); +}