Merge branch 'chat-runtime': chats on the shell window system

This commit is contained in:
2026-11-10 21:43:37 +00:00
55 changed files with 2151 additions and 2120 deletions
-14
View File
@@ -1,14 +0,0 @@
import '../shell/windows/window_kind.dart';
import '../shell/windows/window_manager.dart';
import '../shell/windows/window_store.dart';
/// The app's floating windows, for the app's lifetime: the kinds features
/// register at start and the one manager the shell's window host draws.
abstract final class AppWindows {
static final WindowKinds kinds = WindowKinds();
static final WindowManager manager = WindowManager(
kinds: kinds,
store: const SharedPreferencesWindowStore(),
);
}
+10
View File
@@ -1,7 +1,9 @@
import '../core/servers/chat/chat_server_pool.dart'; import '../core/servers/chat/chat_server_pool.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../features/chat/chat_runtime.dart';
import '../features/chat/screen.dart'; import '../features/chat/screen.dart';
import '../features/chat/windows/chat_windows.dart';
import '../ui/adaptive/host.dart'; import '../ui/adaptive/host.dart';
import '../ui/adaptive/top_bar_notices.dart'; import '../ui/adaptive/top_bar_notices.dart';
import 'app_session.dart'; import 'app_session.dart';
@@ -25,6 +27,8 @@ class ChatDestination extends StatelessWidget {
this.onBack, this.onBack,
this.onWorkspaceEmpty, this.onWorkspaceEmpty,
this.onAvailableSessionsChanged, this.onAvailableSessionsChanged,
this.runtime,
this.windows,
}); });
final AppSession session; final AppSession session;
@@ -36,6 +40,10 @@ class ChatDestination extends StatelessWidget {
final VoidCallback? onWorkspaceEmpty; final VoidCallback? onWorkspaceEmpty;
final ValueChanged<Set<String>>? onAvailableSessionsChanged; final ValueChanged<Set<String>>? onAvailableSessionsChanged;
/// The chats' app-lifetime state and floating windows (see [ChatScreen]).
final ChatRuntime? runtime;
final ChatWindows? windows;
@override @override
Widget build(BuildContext context) => AnimatedBuilder( Widget build(BuildContext context) => AnimatedBuilder(
animation: Listenable.merge([session, ?pool]), animation: Listenable.merge([session, ?pool]),
@@ -86,5 +94,7 @@ class ChatDestination extends StatelessWidget {
onBack: onBack, onBack: onBack,
onWorkspaceEmpty: onWorkspaceEmpty, onWorkspaceEmpty: onWorkspaceEmpty,
onAvailableSessionsChanged: onAvailableSessionsChanged, onAvailableSessionsChanged: onAvailableSessionsChanged,
runtime: runtime,
windows: windows,
); );
} }
+60 -5
View File
@@ -35,9 +35,13 @@ import '../features/updates/web_release.dart';
import '../features/settings/server_connections.dart'; import '../features/settings/server_connections.dart';
import 'app.dart'; import 'app.dart';
import '../shell/windows/window_host.dart'; import '../shell/windows/window_host.dart';
import '../shell/windows/window_kind.dart';
import '../shell/windows/window_manager.dart'; import '../shell/windows/window_manager.dart';
import '../shell/windows/window_store.dart';
import 'app_terminals.dart'; import 'app_terminals.dart';
import 'app_windows.dart'; import '../features/chat/chat_runtime.dart';
import '../features/chat/windows/chat_windows.dart';
import '../features/chat/workspace/chat_float_store.dart';
import '../features/terminal/terminal_layout.dart'; import '../features/terminal/terminal_layout.dart';
import 'app_route.dart'; import 'app_route.dart';
import 'app_router.dart'; import 'app_router.dart';
@@ -99,7 +103,8 @@ class PipelinesApp extends StatefulWidget {
/// The terminal surface's saved layout; null is the device's own. /// The terminal surface's saved layout; null is the device's own.
final TerminalLayout? terminalLayout; final TerminalLayout? terminalLayout;
/// The floating windows; the app's own ([AppWindows.manager]) when null. /// The floating windows; the app keeps its own (saved on this device)
/// when null.
final WindowManager? windows; final WindowManager? windows;
final ServerEndpoint server; final ServerEndpoint server;
final PipelinesClient? client; final PipelinesClient? client;
@@ -216,6 +221,8 @@ class _PipelinesAppState extends State<PipelinesApp>
NotificationServiceHandoff? _deliveryHandoff; NotificationServiceHandoff? _deliveryHandoff;
late final AppTerminals _terminals; late final AppTerminals _terminals;
late final WindowManager _windows; late final WindowManager _windows;
late final ChatRuntime _chatRuntime;
late final ChatWindows _chatWindows;
@override @override
void initState() { void initState() {
@@ -236,9 +243,38 @@ class _PipelinesAppState extends State<PipelinesApp>
bindServerIdentity(_session.gateway, widget.serverId); bindServerIdentity(_session.gateway, widget.serverId);
bindServerIdentity(_session.client, widget.serverId); bindServerIdentity(_session.client, widget.serverId);
// One server for now: windows are kept per server, and this one's show. // One server for now: windows are kept per server, and this one's show.
_windows = (widget.windows ?? AppWindows.manager) _windows =
..server = widget.serverId ?? 'server'; (widget.windows ??
unawaited(_windows.restore()); WindowManager(
kinds: WindowKinds(),
store: const SharedPreferencesWindowStore(),
))
..server = widget.serverId ?? 'server';
final chatGateway = widget.chatPool?.gateway ?? _session.gateway;
final chatScope = widget.chatPool != null
? 'all-saved-servers'
: serverStorageScope(serverIdentity(chatGateway));
_chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope);
_chatWindows = ChatWindows(
manager: _windows,
runtime: _chatRuntime,
openInChat: (id) => _delegate.goTo(AppRoute.chatSession(id)),
ready: _chatReady,
readiness: Listenable.merge([_session, ?widget.chatPool]),
)..start();
_session.addListener(_chatSyncChanged);
widget.chatPool?.addListener(_chatSyncChanged);
_chatSyncChanged();
// Every kind is registered: saved windows can be restored, then the
// floating chats an older build saved are brought over once.
unawaited(
_windows.restore().then((_) {
if (!mounted) return null;
return _chatWindows.migrate(
SharedPreferencesChatFloatStore(serverScope: chatScope),
);
}),
);
_terminals = AppTerminals( _terminals = AppTerminals(
pool: widget.chatPool, pool: widget.chatPool,
connection: _session, connection: _session,
@@ -464,6 +500,11 @@ class _PipelinesAppState extends State<PipelinesApp>
(_provider as PlatformRouteInformationProvider).dispose(); (_provider as PlatformRouteInformationProvider).dispose();
} }
_terminals.dispose(); _terminals.dispose();
_session.removeListener(_chatSyncChanged);
widget.chatPool?.removeListener(_chatSyncChanged);
_chatWindows.dispose();
_chatRuntime.dispose();
if (widget.windows == null) _windows.dispose();
_session.dispose(); _session.dispose();
super.dispose(); super.dispose();
} }
@@ -732,6 +773,18 @@ class _PipelinesAppState extends State<PipelinesApp>
_delegate.goTo(AppRoute.run(id)); _delegate.goTo(AppRoute.run(id));
} }
/// Whether a chat can be read: the server has been reached (or saved
/// machines connect on their own).
bool _chatReady() {
final pool = widget.chatPool;
if (pool != null && pool.servers.catalog.servers.isNotEmpty) return true;
return _session.everConnected || _session.connected;
}
/// A replaced socket makes open chats re-subscribe, also in windows.
void _chatSyncChanged() => _chatRuntime.syncToken.value =
widget.chatPool?.revision ?? _session.connectionEpoch;
/// The shell rebuilds its Runs tab badge from the attention count alone; the /// The shell rebuilds its Runs tab badge from the attention count alone; the
/// destination bodies keep their state through it. /// destination bodies keep their state through it.
Widget _buildShell(BuildContext context, AppRoute route) => Widget _buildShell(BuildContext context, AppRoute route) =>
@@ -835,6 +888,8 @@ class _PipelinesAppState extends State<PipelinesApp>
initialSessionId: chatRoute.chatSessionId, initialSessionId: chatRoute.chatSessionId,
onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)), onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)),
onBack: () => _delegate.goTo(AppRoute.chat), onBack: () => _delegate.goTo(AppRoute.chat),
runtime: _chatRuntime,
windows: _chatWindows,
onWorkspaceEmpty: () => _chatWorkspaceRoute = null, onWorkspaceEmpty: () => _chatWorkspaceRoute = null,
onAvailableSessionsChanged: (ids) { onAvailableSessionsChanged: (ids) {
_availableChatSessionIds = ids; _availableChatSessionIds = ids;
+2 -4
View File
@@ -6,10 +6,8 @@ import 'browser_peer_stub.dart'
/// Registers [server] with the same-origin relay. [needsPassword] is the /// Registers [server] with the same-origin relay. [needsPassword] is the
/// relay's own verdict, distinct from an unreachable machine. /// relay's own verdict, distinct from an unreachable machine.
Future<({bool connected, bool needsPassword, String? error})> Future<({bool connected, bool needsPassword, String? error})>
registerBrowserPeer( registerBrowserPeer(SavedServer server, {String? password}) =>
SavedServer server, { impl.register(server, password: password);
String? password,
}) => impl.register(server, password: password);
Future<void> removeBrowserPeer(String id) => impl.remove(id); Future<void> removeBrowserPeer(String id) => impl.remove(id);
Uri browserPeerEndpoint(String id, Uri endpoint, {Uri? page}) { Uri browserPeerEndpoint(String id, Uri endpoint, {Uri? page}) {
final origin = page ?? Uri.base; final origin = page ?? Uri.base;
-1
View File
@@ -297,4 +297,3 @@ class ServerSession {
static ServerProbeResult interpret(Uri login, LoginProbe probe) => static ServerProbeResult interpret(Uri login, LoginProbe probe) =>
interpretLoginProbe(login, probe); interpretLoginProbe(login, probe);
} }
@@ -0,0 +1,111 @@
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import '../../core/servers/server_context.dart';
import '../../shell/destination.dart';
import '../../shell/detail_page.dart';
import 'chat_runtime.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/composer_focus_request.dart';
/// Where an open chat is shown and what that place alone decides: its Back,
/// its pane menu, whether it takes pastes, and what follows `/new` and
/// `/close`. Everything else about the chat comes from its [ChatRuntime].
class ChatPanePlacement {
const ChatPanePlacement({
required this.onBack,
required this.onNewSession,
required this.onSessionClosed,
this.syncToken = 0,
this.useNativeBack = false,
this.showBackButton,
this.pasteTarget = false,
this.ownsPasteWhenFocused = false,
this.paneControls,
this.onNextChat,
});
final VoidCallback onBack;
/// `/new` moved the chat to a fresh session (previous id, the new row and
/// the line the new conversation opens on).
final void Function(String previousId, JsonMap session, String notice)
onNewSession;
/// `/close` was accepted.
final VoidCallback onSessionClosed;
/// Advances when the socket is replaced; the conversation re-subscribes.
final int syncToken;
final bool useNativeBack;
final bool? showBackButton;
/// Whether a paste with no field focused goes to this chat.
final bool pasteTarget;
/// Whether this chat takes a paste while it has the keyboard, though it is
/// not the active pane (a chat in a window).
final bool ownsPasteWhenFocused;
/// The pane menu's choices, built in the pane's own context.
final List<Widget> Function(BuildContext paneContext)? paneControls;
final VoidCallback? onNextChat;
}
/// One open chat with the scopes its conversation needs, the same in the
/// Chat destination's tiling and in a floating window. It is keyed by the
/// runtime ([ChatRuntime.viewKey]), so a chat that moves between the two in
/// one frame keeps its live view: transcript, scroll, draft and running turn.
Widget buildChatPaneContent({
required ChatRuntime runtime,
required String sessionId,
required ChatPanePlacement placement,
}) => KeyedSubtree(
key: runtime.viewKey(sessionId),
child: DetailPane(
destination: AppDestination.chat,
implyBack: false,
builder: (context) {
final row = runtime.rowFor(sessionId);
final start = runtime.startNotice;
return ChatComposerFocusScope(
sessionId: sessionId,
requests: runtime.composerFocus,
child: ServerContext.forServer(
context,
runtime.serverIdFor(sessionId),
ChatThreadView(
key: ValueKey<String>('chat-session-$sessionId'),
gateway: runtime.gatewayFor(sessionId),
sessionId: sessionId,
title: '${row?['title'] ?? ''}'.trim(),
session: row,
syncToken: placement.syncToken,
scrollPositions: runtime.scrollPositions,
transcripts: runtime.transcripts,
initialNotice: start != null && start.id == sessionId
? start.notice
: null,
onBack: placement.onBack,
onModelChanged: (applied) =>
runtime.modelChanged(sessionId, applied),
onModeChanged: (mode, name) =>
runtime.acceptMode(sessionId, mode, name),
onEffortChanged: (state) => runtime.acceptEffort(sessionId, state),
onNewSession: placement.onNewSession,
onSessionRenamed: (title) => runtime.acceptRename(sessionId, title),
onSessionClosed: placement.onSessionClosed,
onColorSelected: (color) =>
runtime.sessions.setColor(sessionId, color),
onNextChat: placement.onNextChat,
useNativeBack: placement.useNativeBack,
pasteTarget: placement.pasteTarget,
ownsPasteWhenFocused: placement.ownsPasteWhenFocused,
showBackButton: placement.showBackButton,
paneControls: placement.paneControls?.call(context) ?? const [],
),
),
);
},
),
);
+246
View File
@@ -0,0 +1,246 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import '../../core/servers/chat/chat_identity.dart';
import '../../core/servers/chat/federated_chat_gateway.dart';
import 'conversation/chat_efforts.dart';
import 'conversation/chat_models.dart';
import 'conversation/chat_row_widgets.dart';
import 'conversation/chat_scroll.dart';
import 'conversation/chat_transcript_cache.dart';
import 'conversation/composer_focus_request.dart';
import 'data/chat_repository.dart';
import 'ui/sessions/chat_sessions_body.dart';
import 'ui/sessions/chat_sessions_controller.dart';
/// What open chats share for one server, wherever they are shown (the Chat
/// destination's tiling or a floating window): the session list, the rows
/// opened so far, model switches the server accepted, transcript positions
/// and caches, and composer focus requests.
///
/// It notifies when a row a conversation is drawn from changes.
class ChatRuntime extends ChangeNotifier {
ChatRuntime({required ApiGateway gateway, this.serverKey = ''})
: _gateway = gateway,
sessions = ChatSessionsController(ChatRepository(gateway)) {
sessions.onSessionReplaced = (previousId, session) {
for (final listener in _replaced.toList()) {
listener(previousId, session);
}
};
}
/// The server (or set of servers) these chats belong to; windows carry it.
final String serverKey;
/// Advances when the socket is replaced, for chats shown outside the Chat
/// destination.
final ValueNotifier<int> syncToken = ValueNotifier(0);
final List<void Function(String previousId, JsonMap session)> _replaced = [];
/// Calls [listener] when another device moved a chat to a new session.
void addSessionReplacedListener(
void Function(String previousId, JsonMap session) listener,
) => _replaced.add(listener);
void removeSessionReplacedListener(
void Function(String previousId, JsonMap session) listener,
) => _replaced.remove(listener);
final Map<String, GlobalKey> _viewKeys = {};
/// The key of [sessionId]'s live view, so it can move between the tiling
/// and a window without being rebuilt.
GlobalKey viewKey(String sessionId) => _viewKeys.putIfAbsent(
sessionId,
() => GlobalKey(debugLabel: 'chat view $sessionId'),
);
ApiGateway _gateway;
/// The gateway chats are read through. Transcripts read through another
/// gateway belong to that server, so replacing it drops them.
ApiGateway get gateway => _gateway;
set gateway(ApiGateway value) {
if (identical(_gateway, value)) return;
_gateway = value;
transcripts.clear();
}
/// The gateway for one chat: its own server's on a federated gateway.
ApiGateway gatewayFor(String sessionId) {
final gateway = _gateway;
return gateway is FederatedChatGateway
? gateway.forChat(sessionId)
: gateway;
}
/// The id of the server [sessionId] lives on, or empty.
String serverIdFor(String sessionId) =>
'${rowFor(sessionId)?['_server_id'] ?? parseFederatedChatId(sessionId)?.server ?? ''}';
/// The list's controller, shared with the mounted list screen. The list
/// screen refreshes it on mount and swaps its repository when the socket
/// is replaced.
final ChatSessionsController sessions;
/// The list's folded sections, so Next chat counts the rows the list
/// draws.
final ChatSectionFolds folds = ChatSectionFolds();
/// Rows opened so far, used for the title and the recorded model facts.
/// The mounted list also reports its loaded rows, so a routed id (a deep
/// link) resolves the same row without a second list request.
final Map<String, JsonMap> opened = {};
/// Each row as the list last reported it (without its live `running`), so
/// [adoptRows] adopts only what a re-read changed.
final Map<String, JsonMap> _listed = {};
/// Model switches the server accepted after a row was opened. The row that
/// opened the conversation may still carry the pre-switch model, so these
/// win, including when the same chat is reopened.
final Map<String, ChatModelSelection> _acceptedModels = {};
/// Transcript positions, so Back and a reopened chat return to the same
/// place.
final ChatScrollStore scrollPositions = MemoryChatScrollStore();
/// Transcripts of recently left chats, so a reopened chat shows its last
/// transcript at once while it re-subscribes and re-reads. Bounded and in
/// memory only; see [ChatTranscriptCache].
final ChatTranscriptCache transcripts = ChatTranscriptCache();
/// Puts the keyboard in an opened chat's composer once it is built.
final ChatComposerFocusRequests composerFocus = ChatComposerFocusRequests();
/// The line a just-created conversation opens on, tied to the selection
/// `/new` made. Leaving that conversation drops it, so a later reopen is
/// an ordinary visit.
({String id, String notice})? startNotice;
/// The row to open for [id], with an accepted model folded in.
JsonMap? rowFor(String id) {
final row = opened[id] ?? _listed[id];
final accepted = _acceptedModels[id];
if (row == null || accepted == null) return row;
return {
...row,
'model': accepted.model,
'model_provider': accepted.provider,
'model_selection': accepted.selection,
};
}
/// [id]'s title as shown on a pane or window, else the id.
String titleFor(String id) => '${rowFor(id)?['title'] ?? id}';
void modelChanged(String id, ChatModelSelection applied) {
_acceptedModels[id] = applied;
notifyListeners();
}
/// An accepted mode switch updates the opened row, so reopening the chat
/// shows it before the list re-reads. Returns false when [id] has no
/// opened row.
bool modeChanged(String id, String mode, String name) {
final row = opened[id];
if (row == null) return false;
opened[id] = {...row, 'mode': mode, 'mode_name': name};
notifyListeners();
return true;
}
/// An accepted thinking level updates the opened row like a mode switch.
bool effortChanged(String id, ChatEffortState state) {
final row = opened[id];
if (row == null) return false;
opened[id] = state.applyTo(row);
notifyListeners();
return true;
}
/// An accepted mode switch also re-reads the list, so a listing already
/// in flight from before the switch is superseded rather than adopted over
/// the accepted mode.
void acceptMode(String id, String mode, String name) {
if (modeChanged(id, mode, name)) unawaited(sessions.refresh());
}
void acceptEffort(String id, ChatEffortState state) {
if (effortChanged(id, state)) unawaited(sessions.refresh());
}
/// `/rename` was accepted: the opened row follows the shared title and the
/// list re-reads it.
void acceptRename(String id, String title) {
renamed(id, title);
unawaited(sessions.refresh());
}
/// `/rename` was accepted for [id]: the opened row follows the title.
void renamed(String id, String title) {
final row = opened[id];
if (row == null) return;
opened[id] = {...row, 'title': title};
notifyListeners();
}
/// The chat [previousId] moved to the new session [session] (`/new`): it
/// opens under its new id on the server's row, which carries every shared
/// field (an omitted one is unset, so the old row is not merged in), on
/// [notice]. A model switch accepted for the old id moves with the chat.
void movedToSession(String previousId, JsonMap session, String notice) {
final id = '${session['id'] ?? ''}';
final accepted = _acceptedModels[previousId];
if (accepted != null) _acceptedModels[id] = accepted;
startNotice = (id: id, notice: notice);
opened[id] = <String, dynamic>{...session}..remove('running');
}
/// Adopts the list's loaded [rows] for [selected], for every chat in
/// [retained] and for every opened row. Only a listed row that changed
/// since the list last reported it is adopted, so an unchanged (or still
/// loading) listing never reverts a mode or model just accepted. Fields
/// only the opened row carries (a create's instruction status) are kept.
/// The list's live `running` flag is ignored: the conversation tracks its
/// own turn, and following it would rebuild the open thread at every turn.
void adoptRows(
List<JsonMap> rows, {
required String? selected,
required Set<String> retained,
}) {
final next = <String, JsonMap>{};
for (final row in rows) {
final id = '${row['id'] ?? ''}';
if (id.isEmpty) continue;
final listed = <String, dynamic>{...row}..remove('running');
final previous = _listed[id];
_listed[id] = listed;
final was = opened[id];
if (was == null && id != selected && !retained.contains(id)) continue;
if (was != null && chatJsonEquals(previous, listed)) continue;
final adopted = <String, dynamic>{...?was, ...listed};
if (was != null && was.containsKey('running')) {
adopted['running'] = was['running'];
}
if (!chatJsonEquals(was, adopted)) next[id] = adopted;
}
if (next.isEmpty) return;
opened.addAll(next);
notifyListeners();
}
@override
void dispose() {
_replaced.clear();
syncToken.dispose();
sessions.dispose();
folds.dispose();
composerFocus.dispose();
super.dispose();
}
}
+47 -61
View File
@@ -1,81 +1,67 @@
part of 'screen.dart'; part of 'screen.dart';
/// The floating chats for one Chat destination visit: their menu choices, /// Floating a tiled pane into a window and docking it back (see
/// window frames and persistence (see `notes/chat-floating-pane.md`). /// [ChatWindows] and `notes/chat-floating-pane.md`).
mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace { mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
@override ChatTiling? _tiling;
final ChatFloatFrames _floatFrames = ChatFloatFrames();
ChatFloatBinding? _floatBinding;
/// Restores and saves the floating chat in [store] once [restored] (the void _bindWindows() {
/// workspace layout's own restore) completes. final windows = widget.windows;
@override if (windows == null) return;
void _bindFloat(ChatFloatStore store, Future<void> restored) { _workspace.showOutside = windows.show;
_floatBinding?.dispose(); windows.tiling = _tiling = ChatTiling(
final binding = _floatBinding = ChatFloatBinding( holds: _workspace.holdsSession,
controller: _workspace, dock: _dockSession,
frames: _floatFrames, canFloatActive: () {
store: store, final pane = _workspace.activePane;
); return mounted &&
unawaited( pane != null &&
restored.then((_) { _floatsHere &&
if (mounted && identical(_floatBinding, binding)) { _workspaceVisible &&
return binding.start(); _workspace.canFloat(pane.id) &&
} _chatOwnsKeyboard();
}), },
floatActive: () {
final pane = _workspace.activePane;
if (pane != null) _floatPane(pane.id);
},
); );
} }
@override void _unbindWindows() {
void _unbindFloat() { final windows = widget.windows;
_floatBinding?.dispose(); if (windows != null && identical(windows.tiling, _tiling)) {
_floatBinding = null; windows.tiling = null;
} }
_workspace.showOutside = null;
void _disposeFloat() {
_unbindFloat();
_floatFrames.dispose();
} }
/// Panes float only on a wide layout, beside the chat list. /// Panes float only on a wide layout, beside the chat list.
bool get _floatsHere => !_pageOpen && showsListBesideDetail(context); bool get _floatsHere =>
widget.windows != null && !_pageOpen && showsListBesideDetail(context);
void _dockFloat(ChatWorkspacePane pane) { /// The pane leaves the tiling and its live view moves into a window in
_workspace.dock(pane.id); /// the same frame.
_composerFocus.request(pane.sessionId); void _floatPane(String paneId) {
final pane = _workspace.detach(paneId);
if (pane != null) widget.windows?.float(pane.sessionId);
} }
/// The pane menu's floating choices: Float on a tiled pane that can, and void _dockSession(String sessionId) {
/// Dock, Hide and Close on a floating chat. if (!mounted) return;
_workspaceVisible = true;
if (!_pageOpen && showsListBesideDetail(context)) _usedWorkspace = true;
_workspace.dock(sessionId);
_composerFocus.request(sessionId);
}
/// The pane menu's Float choice, on a tiled pane that can.
List<Widget> _floatControls(ChatWorkspacePane pane) { List<Widget> _floatControls(ChatWorkspacePane pane) {
final shortcut = chatFloatShortcutLabel();
if (_workspace.isFloating(pane.id)) {
return [
ChatBarAction(
label: 'Dock',
onPressed: () => _dockFloat(pane),
materialIcon: Icons.vertical_split_outlined,
cupertinoIcon: CupertinoIcons.rectangle_split_3x1,
),
ChatBarAction(
label: 'Hide floating chats ($shortcut)',
onPressed: () => _workspace.setFloatShown(false),
materialIcon: Icons.visibility_off_outlined,
cupertinoIcon: CupertinoIcons.eye_slash,
),
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
];
}
if (!_floatsHere || !_workspace.canFloat(pane.id)) return const []; if (!_floatsHere || !_workspace.canFloat(pane.id)) return const [];
return [ return [
ChatBarAction( ChatBarAction(
label: 'Float ($shortcut)', label: 'Float (${chatFloatShortcutLabel()})',
onPressed: () => _workspace.float(pane.id), onPressed: () => _floatPane(pane.id),
materialIcon: Icons.picture_in_picture_alt_outlined, materialIcon: Icons.picture_in_picture_alt_outlined,
cupertinoIcon: CupertinoIcons.rectangle_on_rectangle, cupertinoIcon: CupertinoIcons.rectangle_on_rectangle,
), ),
@@ -11,15 +11,7 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
JsonMap? _rowFor(String id); JsonMap? _rowFor(String id);
void _back(); void _back();
bool get _pageOpen; bool get _pageOpen;
ChatFloatFrames get _floatFrames; Widget _thread(ChatWorkspacePane pane);
void _bindFloat(ChatFloatStore store, Future<void> restored);
void _unbindFloat();
Widget _thread(
String selected,
VoidCallback onBack, {
ChatWorkspacePane? pane,
BuildContext? paneContext,
});
ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded; ChatSidebarMode _sidebarMode = ChatSidebarMode.expanded;
void _setSidebarMode(ChatSidebarMode mode) { void _setSidebarMode(ChatSidebarMode mode) {
@@ -117,17 +109,8 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
_publishWorkspaceRoute(); _publishWorkspaceRoute();
}, },
); );
final restored = _workspaceBinding!.start( unawaited(
initialSessionId: widget.initialSessionId, _workspaceBinding!.start(initialSessionId: widget.initialSessionId),
);
unawaited(restored);
_bindFloat(
SharedPreferencesChatFloatStore(
serverScope: widget.gateway is FederatedChatGateway
? 'all-saved-servers'
: scope,
),
restored,
); );
} }
@@ -139,7 +122,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
} }
_workspaceBinding?.dispose(); _workspaceBinding?.dispose();
_workspaceBinding = null; _workspaceBinding = null;
_unbindFloat();
if (_workspaceScope != null && scope != _workspaceScope) { if (_workspaceScope != null && scope != _workspaceScope) {
_workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!); _workspace.restoreLayout(ChatWorkspaceSnapshot.fromLayout(null, null)!);
_forgetRecentSessions(); _forgetRecentSessions();
@@ -328,7 +310,6 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
controller: _workspace, controller: _workspace,
onVisibleSessionIdsChanged: _workspaceVisibilityChanged, onVisibleSessionIdsChanged: _workspaceVisibilityChanged,
shortcutsEnabled: _workspaceVisible, shortcutsEnabled: _workspaceVisible,
floatFrames: _floatFrames,
singlePane: !showsListBesideDetail(context), singlePane: !showsListBesideDetail(context),
mobilePeeks: true, mobilePeeks: true,
paneTitle: (pane) => paneTitle: (pane) =>
@@ -390,16 +371,9 @@ mixin _ChatScreenWorkspace on State<ChatScreen> {
// active pane the others fade theirs. // active pane the others fade theirs.
child: ChatPaneActivity( child: ChatPaneActivity(
inactive: _workspace.paneCount > 1 && !active, inactive: _workspace.paneCount > 1 && !active,
child: DetailPane( child: KeyedSubtree(
key: ValueKey('chat-pane-detail-${pane.id}'), key: ValueKey('chat-pane-detail-${pane.id}'),
destination: AppDestination.chat, child: _thread(pane),
implyBack: false,
builder: (context) => _thread(
pane.sessionId,
_back,
pane: pane,
paneContext: context,
),
), ),
), ),
), ),
@@ -202,7 +202,7 @@ class _ChatBackgroundTasksState extends State<ChatBackgroundTasks> {
// Level with the field's single line, beside Send. // Level with the field's single line, beside Send.
padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4), padding: const EdgeInsetsDirectional.only(end: 4, bottom: 4),
child: Semantics( child: Semantics(
identifier: 'chat-background-tasks-button', identifier: 'chat-background-tasks-button',
button: true, button: true,
excludeSemantics: true, excludeSemantics: true,
onTap: _open, onTap: _open,
@@ -1,3 +1,4 @@
import '../../../ui/adaptive/app_menu_anchor.dart';
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
@@ -158,7 +159,7 @@ class _ChatEffortControlState extends State<ChatEffortControl> {
), ),
); );
} }
return MenuAnchor( return AppMenuAnchor(
menuChildren: [ menuChildren: [
Padding( Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
@@ -1,3 +1,4 @@
import '../../../shell/windows/window_scope.dart';
import '../../terminal/terminal_open_action.dart'; import '../../terminal/terminal_open_action.dart';
import 'dart:async'; import 'dart:async';
@@ -300,7 +301,18 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_filesSheetOpen = true; _filesSheetOpen = true;
final cupertino = final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino; chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final sheet = cupertino // In a floating window the explorer is a page of that window, so a file
// it opens stays in the window too.
final sheet = WindowScope.maybeOf(context) != null
? Navigator.of(context).push<void>(
MaterialPageRoute<void>(
builder: (_) => Scaffold(
appBar: AppBar(title: const Text('Files')),
body: FilesPanel(controller: _files),
),
),
)
: cupertino
? showCupertinoModalPopup<void>( ? showCupertinoModalPopup<void>(
context: context, context: context,
builder: (_) => Align( builder: (_) => Align(
@@ -1429,6 +1441,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
], ],
moreActions: [ moreActions: [
?widget.sidebarControl, ?widget.sidebarControl,
// A window's own title bar names the chat, and its narrow action
// bar has no room for the title that opens the details.
if (WindowScope.maybeOf(context) != null)
ChatBarAction(
label: 'Chat details',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
...widget.paneControls, ...widget.paneControls,
chatShellRunMenuAction(onPressed: _runShellFromMenu), chatShellRunMenuAction(onPressed: _runShellFromMenu),
if (_shellRuns.finishedIds.isNotEmpty) if (_shellRuns.finishedIds.isNotEmpty)
+90 -218
View File
@@ -1,7 +1,8 @@
import 'chat_pane_content.dart';
import 'chat_runtime.dart';
import 'windows/chat_windows.dart';
import 'workspace/federated_workspace_store.dart'; import 'workspace/federated_workspace_store.dart';
import '../../core/servers/chat/chat_identity.dart';
import '../../core/servers/chat/federated_chat_gateway.dart'; import '../../core/servers/chat/federated_chat_gateway.dart';
import '../../core/servers/server_context.dart';
import '../../shell/destination.dart'; import '../../shell/destination.dart';
import '../../shell/shell_bar.dart'; import '../../shell/shell_bar.dart';
import '../../shell/shell_destination_menu.dart'; import '../../shell/shell_destination_menu.dart';
@@ -20,15 +21,11 @@ import 'package:flutter/services.dart';
import '../../core/api_gateway.dart'; import '../../core/api_gateway.dart';
import '../../core/servers/server_scope.dart'; import '../../core/servers/server_scope.dart';
import 'workspace/chat_float_binding.dart';
import 'workspace/chat_float_shortcut.dart'; import 'workspace/chat_float_shortcut.dart';
import 'workspace/chat_float_store.dart';
import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_binding.dart';
import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_snapshot.dart';
import 'workspace/chat_workspace_store.dart'; import 'workspace/chat_workspace_store.dart';
import 'conversation/chat_bar_tint.dart'; import 'conversation/chat_bar_tint.dart';
import 'conversation/chat_efforts.dart';
import 'conversation/chat_models.dart';
import 'conversation/chat_pane_picker.dart'; import 'conversation/chat_pane_picker.dart';
import 'conversation/chat_add_pane_picker.dart'; import 'conversation/chat_add_pane_picker.dart';
import 'conversation/chat_sidebar_controls.dart'; import 'conversation/chat_sidebar_controls.dart';
@@ -40,13 +37,8 @@ import 'workspace/chat_center_stage_keys.dart';
import 'workspace/chat_pane_move_actions.dart'; import 'workspace/chat_pane_move_actions.dart';
import 'workspace/chat_workspace_entrance.dart'; import 'workspace/chat_workspace_entrance.dart';
import 'ui/sessions/chat_adaptive.dart'; import 'ui/sessions/chat_adaptive.dart';
import 'conversation/chat_row_widgets.dart';
import 'conversation/chat_scroll.dart';
import 'conversation/chat_thread_view.dart';
import 'conversation/chat_transcript_cache.dart';
import 'conversation/composer_focus_request.dart'; import 'conversation/composer_focus_request.dart';
import 'conversation/composer_selection_focus.dart'; import 'conversation/composer_selection_focus.dart';
import 'data/chat_repository.dart';
import 'domain/chat_commands.dart'; import 'domain/chat_commands.dart';
import 'domain/chat_cycle.dart'; import 'domain/chat_cycle.dart';
import '../terminal/terminal_scope.dart'; import '../terminal/terminal_scope.dart';
@@ -80,11 +72,21 @@ class ChatScreen extends StatefulWidget {
this.onWorkspaceEmpty, this.onWorkspaceEmpty,
this.onAvailableSessionsChanged, this.onAvailableSessionsChanged,
this.persistWorkspace = false, this.persistWorkspace = false,
this.runtime,
this.windows,
}); });
final ApiGateway gateway; final ApiGateway gateway;
final bool persistWorkspace; final bool persistWorkspace;
/// The chats' shared state, kept by the app beyond this screen; the screen
/// keeps its own for the visit when null.
final ChatRuntime? runtime;
/// The app's floating chat windows; null offers none (a pane cannot
/// float).
final ChatWindows? windows;
/// The chat session the current route names, or null for the list. /// The chat session the current route names, or null for the list.
final String? initialSessionId; final String? initialSessionId;
@@ -103,53 +105,23 @@ class ChatScreen extends StatefulWidget {
class _ChatScreenState extends State<ChatScreen> class _ChatScreenState extends State<ChatScreen>
with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat { with _ChatScreenWorkspace, _ChatScreenKeys, _ChatScreenFloat {
/// The list's controller, shared with the mounted list screen. The list /// The chats' shared state: the list, opened rows, accepted models,
/// screen refreshes it on mount and swaps its repository when the socket is /// transcript positions and caches (see [ChatRuntime]).
/// replaced; this destination lists created rows and re-reads after a late final ChatRuntime _runtime =
/// conversation's command changes a session. widget.runtime ?? ChatRuntime(gateway: widget.gateway);
late final ChatSessionsController _sessions = ChatSessionsController(
ChatRepository(widget.gateway),
)..onSessionReplaced = _replacedElsewhere;
/// Rows this visit has opened, used for the native title and the recorded ChatSessionsController get _sessions => _runtime.sessions;
/// model facts. The mounted list also reports its loaded rows, so a routed id
/// (a deep link) resolves the same row without a second list request.
@override @override
final Map<String, JsonMap> _openedSessions = {}; Map<String, JsonMap> get _openedSessions => _runtime.opened;
/// Each row as the list last reported it (without its live `running`), so
/// [_adoptRows] adopts only what a re-read changed.
final Map<String, JsonMap> _listedRows = {};
/// Model switches the server accepted after a row was opened. The row that
/// opened the conversation may still carry the pre-switch model, so these win
/// for the rest of this visit, including when the same chat is reopened.
final Map<String, ChatModelSelection> _acceptedModels = {};
/// Transcript positions for this visit. It lives with the destination, not a
/// conversation view, so Back and a reopened chat return to the same place.
final ChatScrollStore _scrollPositions = MemoryChatScrollStore();
/// Transcripts of recently left chats for this visit, so a reopened chat
/// shows its last transcript at once while it re-subscribes and re-reads.
/// Bounded and in memory only; see [ChatTranscriptCache].
final ChatTranscriptCache _transcripts = ChatTranscriptCache();
/// The line a just-created conversation opens on, tied to the selection
/// `/new` made. Leaving that conversation drops it, so a later reopen is an
/// ordinary visit.
({String id, String notice})? _startNotice;
String? _standaloneSelection; String? _standaloneSelection;
/// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a /// Ctrl+1…Ctrl+9 put the keyboard in the opened chat's composer; choosing a
/// chat does too where [chatSelectionFocusesComposer] allows. /// chat does too where [chatSelectionFocusesComposer] allows.
@override @override
final ChatComposerFocusRequests _composerFocus = ChatComposerFocusRequests(); ChatComposerFocusRequests get _composerFocus => _runtime.composerFocus;
/// The list's folded sections, kept here so Next chat counts the rows the ChatSectionFolds get _folds => _runtime.folds;
/// list draws.
final ChatSectionFolds _folds = ChatSectionFolds();
/// Whether the last build offered Next chat, so a list change rebuilds only /// Whether the last build offered Next chat, so a list change rebuilds only
/// when that changes. /// when that changes.
@@ -165,6 +137,11 @@ class _ChatScreenState extends State<ChatScreen>
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_runtime
..gateway = widget.gateway
..addListener(_runtimeChanged);
_runtime.addSessionReplacedListener(_replacedElsewhere);
_bindWindows();
final initial = widget.initialSessionId; final initial = widget.initialSessionId;
if (initial != null && initial.isNotEmpty) { if (initial != null && initial.isNotEmpty) {
_workspace.open(initial); _workspace.open(initial);
@@ -184,6 +161,11 @@ class _ChatScreenState extends State<ChatScreen>
_folds.addListener(_nextChanged); _folds.addListener(_nextChanged);
} }
/// A row an open conversation is drawn from changed.
void _runtimeChanged() {
if (mounted) setState(() {});
}
/// The chat after [id] as the list draws it (Starred, then Chats by /// The chat after [id] as the list draws it (Starred, then Chats by
/// directory, then Closed, skipping folded sections), wrapping around. The /// directory, then Closed, skipping folded sections), wrapping around. The
/// embedded list has no search field, so no query narrows it. /// embedded list has no search field, so no query narrows it.
@@ -255,7 +237,7 @@ class _ChatScreenState extends State<ChatScreen>
_openedSessions[id] = session; _openedSessions[id] = session;
_workspaceVisible = true; _workspaceVisible = true;
_workspace.open(id); _workspace.open(id);
if (_startNotice?.id != id) _startNotice = null; if (_runtime.startNotice?.id != id) _runtime.startNotice = null;
final select = widget.onSessionSelected; final select = widget.onSessionSelected;
if (select != null) { if (select != null) {
if (_publishedWorkspaceSession != id) { if (_publishedWorkspaceSession != id) {
@@ -289,26 +271,12 @@ class _ChatScreenState extends State<ChatScreen>
/// shared field (an omitted one is unset, so the old row is not merged in). /// shared field (an omitted one is unset, so the old row is not merged in).
/// A model switch accepted here in this visit moved with the chat. /// A model switch accepted here in this visit moved with the chat.
void _followNewSession(String previousId, JsonMap session, String notice) { void _followNewSession(String previousId, JsonMap session, String notice) {
final id = '${session['id'] ?? ''}'; _runtime.movedToSession(previousId, session, notice);
final accepted = _acceptedModels[previousId];
if (accepted != null) _acceptedModels[id] = accepted;
_startNotice = (id: id, notice: notice);
_openedSessions[id] = <String, dynamic>{...session}..remove('running');
_forgetRecentSession(previousId); _forgetRecentSession(previousId);
_workspace.replaceSession(previousId, id); _workspace.replaceSession(previousId, '${session['id'] ?? ''}');
if (_workspace.paneCount == 0) _open(session); if (_workspace.paneCount == 0) _open(session);
} }
/// `/rename` was accepted for [id]: the opened row follows the shared title
/// and the list re-reads it.
void _renamed(String id, String title) {
final row = _openedSessions[id];
if (row != null) {
setState(() => _openedSessions[id] = {...row, 'title': title});
}
unawaited(_sessions.refresh());
}
/// `/close` was accepted: the conversation leaves, back to the list, which /// `/close` was accepted: the conversation leaves, back to the list, which
/// re-reads the closed row. /// re-reads the closed row.
void _closed(String sessionId) { void _closed(String sessionId) {
@@ -319,12 +287,6 @@ class _ChatScreenState extends State<ChatScreen>
.toList()) { .toList()) {
_closePane(pane.id); _closePane(pane.id);
} }
for (final pane
in _workspace.floatingPanes
.where((pane) => pane.sessionId == sessionId)
.toList()) {
_closePane(pane.id);
}
unawaited(_sessions.refresh()); unawaited(_sessions.refresh());
} }
@@ -348,73 +310,21 @@ class _ChatScreenState extends State<ChatScreen>
if (row['closed_at'] == null && row['closed'] != true) if (row['closed_at'] == null && row['closed'] != true)
'${row['id'] ?? ''}', '${row['id'] ?? ''}',
}); });
final selected = _selected; _runtime.adoptRows(
final retained = _workspace.panes.map((pane) => pane.sessionId).toSet(); rows,
final next = <String, JsonMap>{}; selected: _selected,
for (final row in rows) { retained: _workspace.panes.map((pane) => pane.sessionId).toSet(),
final id = '${row['id'] ?? ''}';
if (id.isEmpty) continue;
final listed = <String, dynamic>{...row}..remove('running');
final previous = _listedRows[id];
_listedRows[id] = listed;
final opened = _openedSessions[id];
if (opened == null && id != selected && !retained.contains(id)) continue;
if (opened != null && chatJsonEquals(previous, listed)) continue;
final adopted = <String, dynamic>{...?opened, ...listed};
if (opened != null && opened.containsKey('running')) {
adopted['running'] = opened['running'];
}
if (!chatJsonEquals(opened, adopted)) next[id] = adopted;
}
if (next.isEmpty) return;
setState(() => _openedSessions.addAll(next));
}
void _modelChanged(String id, ChatModelSelection applied) {
if (!mounted) return;
setState(() => _acceptedModels[id] = applied);
}
/// An accepted mode switch updates the opened row, so reopening the chat in
/// this visit shows it before the list re-reads. The list then re-reads, so
/// a listing already in flight from before the switch is superseded rather
/// than adopted over the accepted mode.
void _modeChanged(String id, String mode, String name) {
final row = _openedSessions[id];
if (!mounted || row == null) return;
setState(
() => _openedSessions[id] = {...row, 'mode': mode, 'mode_name': name},
); );
unawaited(_sessions.refresh());
} }
/// An accepted thinking level updates the opened row like a mode switch.
void _effortChanged(String id, ChatEffortState state) {
final row = _openedSessions[id];
if (!mounted || row == null) return;
setState(() => _openedSessions[id] = state.applyTo(row));
unawaited(_sessions.refresh());
}
/// The row to open for [id], with an accepted model folded in.
@override @override
JsonMap? _rowFor(String id) { JsonMap? _rowFor(String id) => _runtime.rowFor(id);
final row = _openedSessions[id] ?? _listedRows[id];
final accepted = _acceptedModels[id];
if (row == null || accepted == null) return row;
return {
...row,
'model': accepted.model,
'model_provider': accepted.provider,
'model_selection': accepted.selection,
};
}
@override @override
void _back() { void _back() {
_workspaceVisible = false; _workspaceVisible = false;
_publishedWorkspaceSession = null; _publishedWorkspaceSession = null;
_startNotice = null; _runtime.startNotice = null;
_composerFocus.cancel(); _composerFocus.cancel();
if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call(); if (_workspace.paneCount == 0) widget.onWorkspaceEmpty?.call();
final back = widget.onBack; final back = widget.onBack;
@@ -454,7 +364,7 @@ class _ChatScreenState extends State<ChatScreen>
} }
} }
// Transcripts read through another gateway belong to that server. // Transcripts read through another gateway belong to that server.
if (oldWidget.gateway != widget.gateway) _transcripts.clear(); _runtime.gateway = widget.gateway;
} }
@override @override
@@ -463,102 +373,64 @@ class _ChatScreenState extends State<ChatScreen>
HardwareKeyboard.instance.removeHandler(_slashFocusKey); HardwareKeyboard.instance.removeHandler(_slashFocusKey);
_page.dispose(); _page.dispose();
_workspaceBinding?.dispose(); _workspaceBinding?.dispose();
_disposeFloat(); _unbindWindows();
_workspace.removeListener(_workspaceChanged); _workspace.removeListener(_workspaceChanged);
_workspace.dispose(); _workspace.dispose();
_sessions.removeListener(_nextChanged); _sessions.removeListener(_nextChanged);
_sessions.removeListener(_availableSessionsChanged); _sessions.removeListener(_availableSessionsChanged);
_sessions.dispose(); _folds.removeListener(_nextChanged);
_folds.dispose(); _runtime.removeListener(_runtimeChanged);
_composerFocus.dispose(); _runtime.removeSessionReplacedListener(_replacedElsewhere);
if (widget.runtime == null) _runtime.dispose();
super.dispose(); super.dispose();
} }
@override @override
Widget _thread( Widget _thread(ChatWorkspacePane pane) {
String selected, final selected = pane.sessionId;
VoidCallback onBack, { return buildChatPaneContent(
ChatWorkspacePane? pane, runtime: _runtime,
BuildContext? paneContext,
}) {
final row = _rowFor(selected);
final start = _startNotice;
final thread = ChatThreadView(
key: ValueKey<String>('chat-session-$selected'),
gateway: widget.gateway is FederatedChatGateway
? (widget.gateway as FederatedChatGateway).forChat(selected)
: widget.gateway,
sessionId: selected, sessionId: selected,
title: '${row?['title'] ?? ''}'.trim(), placement: ChatPanePlacement(
session: row, syncToken: widget.syncToken,
syncToken: widget.syncToken, onBack: _back,
scrollPositions: _scrollPositions, onNewSession: _startedNewSession,
transcripts: _transcripts, onSessionClosed: () => _closed(selected),
initialNotice: start != null && start.id == selected onNextChat: _nextAfter(selected) != null
? start.notice ? () => _openNext(selected)
: null, : null,
onBack: onBack, useNativeBack: _page.open,
onModelChanged: (applied) => _modelChanged(selected, applied), pasteTarget: _workspaceVisible && pane.id == _workspace.activePaneId,
onModeChanged: (mode, name) => _modeChanged(selected, mode, name), showBackButton: _page.open || !showsListBesideDetail(context),
onEffortChanged: (state) => _effortChanged(selected, state), paneControls: (paneContext) => [
onNewSession: _startedNewSession, ChatBarAction(
onSessionRenamed: (title) => _renamed(selected, title), label: 'Add chat pane',
onSessionClosed: () => _closed(selected), onPressed: () => _addPane(paneContext),
onColorSelected: (color) => _sessions.setColor(selected, color), materialIcon: Icons.add_box_outlined,
onNextChat: _nextAfter(selected) != null cupertinoIcon: CupertinoIcons.plus_square,
? () => _openNext(selected) ),
: null, if (_workspace.paneCount > 1)
useNativeBack: _page.open, ChatBarAction(
pasteTarget: label: 'Open chats (${_workspace.paneCount})',
_workspaceVisible && onPressed: () => _pickPane(paneContext),
(pane == null || pane.id == _workspace.activePaneId), materialIcon: Icons.view_quilt_outlined,
// A floating chat is never the active pane, so its composer takes a cupertinoIcon: CupertinoIcons.square_split_2x2,
// paste while it has the keyboard. ),
ownsPasteWhenFocused: pane != null && _workspace.isFloating(pane.id), if (_workspace.paneCount > 1 && showsListBesideDetail(context))
showBackButton: pane == null chatCenterStageAction(ChatCenterStageController.instance),
? null ...chatPaneMoveActions(
: _page.open || !showsListBesideDetail(context), ChatWorkspacePaneScope.maybeOf(paneContext),
paneControls: pane == null onMove: (target) => _movePane(pane.id, target),
? const [] ),
: _workspace.isFloating(pane.id) ..._floatControls(pane),
? _floatControls(pane) if (_workspace.paneCount > 1)
: [ ChatBarAction(
ChatBarAction( label: 'Close pane',
label: 'Add chat pane', onPressed: () => _closePane(pane.id),
onPressed: () => _addPane(paneContext ?? context), materialIcon: Icons.close,
materialIcon: Icons.add_box_outlined, cupertinoIcon: CupertinoIcons.xmark,
cupertinoIcon: CupertinoIcons.plus_square, ),
), ],
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Open chats (${_workspace.paneCount})',
onPressed: () => _pickPane(paneContext ?? context),
materialIcon: Icons.view_quilt_outlined,
cupertinoIcon: CupertinoIcons.square_split_2x2,
),
if (_workspace.paneCount > 1 && showsListBesideDetail(context))
chatCenterStageAction(ChatCenterStageController.instance),
...chatPaneMoveActions(
ChatWorkspacePaneScope.maybeOf(paneContext ?? context),
onMove: (target) => _movePane(pane.id, target),
),
..._floatControls(pane),
if (_workspace.paneCount > 1)
ChatBarAction(
label: 'Close pane',
onPressed: () => _closePane(pane.id),
materialIcon: Icons.close,
cupertinoIcon: CupertinoIcons.xmark,
),
],
);
return ChatComposerFocusScope(
sessionId: selected,
requests: _composerFocus,
child: ServerContext.forServer(
context,
'${row?['_server_id'] ?? parseFederatedChatId(selected)?.server ?? ''}',
thread,
), ),
); );
} }
@@ -0,0 +1,68 @@
import 'package:flutter/material.dart';
import '../../../shell/windows/window_entry.dart';
import '../../../ui/adaptive/window_margins.dart';
import '../chat_pane_content.dart';
import 'chat_windows.dart';
/// A floating window's chat: the same live view as a tiled pane (see
/// [buildChatPaneContent]), with what a window decides. Before the server
/// has been reached it says so instead of reading a chat.
class ChatWindowContent extends StatelessWidget {
const ChatWindowContent({
super.key,
required this.windows,
required this.entry,
});
final ChatWindows windows;
final WindowEntry entry;
@override
Widget build(BuildContext context) {
final runtime = windows.runtime;
final sessionId = entry.contentId;
return ListenableBuilder(
listenable: Listenable.merge([
runtime,
runtime.syncToken,
windows.readiness,
]),
builder: (context, _) {
// A chat is drawn once: the tiling wins, and this window closes.
if (windows.tiling?.holds(sessionId) ?? false) {
WidgetsBinding.instance.addPostFrameCallback(
(_) => windows.manager.close(entry.id),
);
return const SizedBox.shrink();
}
if (!windows.ready) {
return Center(
child: Text(
'Connecting…',
style: Theme.of(context).textTheme.bodyMedium,
),
);
}
// A small window keeps the compact bar insets.
return WindowMargins.compact(
child: buildChatPaneContent(
runtime: runtime,
sessionId: sessionId,
placement: ChatPanePlacement(
syncToken: runtime.syncToken.value,
onBack: () {},
showBackButton: false,
// Never the active pane: its composer takes a paste while it
// has the keyboard.
ownsPasteWhenFocused: true,
onNewSession: (previousId, session, notice) => windows
.startedNewSession(entry.id, previousId, session, notice),
onSessionClosed: () => windows.sessionClosed(entry.id),
),
),
);
},
);
}
}
@@ -0,0 +1,280 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../shell/list_detail_policy.dart';
import '../../../shell/windows/window_entry.dart';
import '../../../shell/windows/window_kind.dart';
import '../../../shell/windows/window_manager.dart';
import '../chat_runtime.dart';
import '../domain/chat_commands.dart';
import '../workspace/chat_float_shortcut.dart';
import '../workspace/chat_float_store.dart';
import 'chat_window_content.dart';
const chatWindowKind = 'chat';
/// What the mounted Chat destination offers the chat windows: its tiling.
class ChatTiling {
const ChatTiling({
required this.holds,
required this.dock,
required this.canFloatActive,
required this.floatActive,
});
/// Whether the tiling shows [sessionId].
final bool Function(String sessionId) holds;
/// Puts a chat back into the tiling.
final void Function(String sessionId) dock;
/// Whether the chord can float the active pane now.
final bool Function() canFloatActive;
final VoidCallback floatActive;
}
/// The floating chat windows, for the app's lifetime: the `chat` window kind
/// over the app's [WindowManager], its chord (see [chatFloatShortcut]), and
/// what `/new` and `/close` do to a chat in a window. The windows are built
/// from [runtime], so they show whatever destination is open, also when the
/// Chat destination has never been built.
class ChatWindows {
ChatWindows({
required this.manager,
required this.runtime,
required this.openInChat,
this._ready,
Listenable? readiness,
}) : readiness = readiness ?? const _Never();
final WindowManager manager;
final ChatRuntime runtime;
/// Opens a chat in the Chat destination (when no tiling is mounted to
/// dock into).
final void Function(String sessionId) openInChat;
final bool Function()? _ready;
/// Notifies when [ready] may have changed.
final Listenable readiness;
/// The mounted Chat destination's tiling, if it is built.
ChatTiling? tiling;
late final ChatWindowKind kind = ChatWindowKind(this);
bool _started = false;
/// Whether the server has been reached, so a chat can be read.
bool get ready => _ready?.call() ?? true;
Iterable<WindowEntry> get windows =>
manager.windows.where((w) => w.kind == chatWindowKind);
/// Registers the kind and starts answering the chord. Call before the
/// manager restores, so saved chat windows are kept.
void start() {
if (_started) return;
_started = true;
manager.kinds.register(kind);
FocusManager.instance.addEarlyKeyEventHandler(_key);
runtime.addSessionReplacedListener(_replacedElsewhere);
runtime.sessions.addListener(_rowsChanged);
manager.addListener(_rowsChanged);
readiness.addListener(_rowsChanged);
}
void dispose() {
if (!_started) return;
_started = false;
FocusManager.instance.removeEarlyKeyEventHandler(_key);
runtime.removeSessionReplacedListener(_replacedElsewhere);
runtime.sessions.removeListener(_rowsChanged);
manager.removeListener(_rowsChanged);
readiness.removeListener(_rowsChanged);
manager.kinds.unregister(chatWindowKind);
}
/// Opens the windows an older build saved (`pipelines.next.chatFloat.v1`,
/// both formats) once, after the manager restored and found none.
Future<void> migrate(ChatFloatStore legacy) async {
final record = await legacy.read();
if (record == null || record.panes.isEmpty || !_started) return;
if (windows.isEmpty) {
for (final pane in record.panes) {
manager.open(
chatWindowKind,
pane.sessionId,
frame: record.frames[pane.id],
);
}
if (!record.shown) manager.setGroupShown(chatWindowKind, false);
}
await legacy.write(const ChatFloatRecord());
}
/// Shows the window [sessionId] is in; false when it is in none.
bool show(String sessionId) {
final entry = manager.find(chatWindowKind, sessionId);
if (entry == null) return false;
manager.show(entry.id);
return true;
}
/// Opens [sessionId] in a window (the caller took it out of the tiling).
void float(String sessionId) => manager.open(chatWindowKind, sessionId);
/// Puts the window's chat back into the tiling, or opens it in the Chat
/// destination when that is not built.
void dock(WindowEntry entry) {
final tiling = this.tiling;
manager.close(entry.id);
if (tiling != null) {
tiling.dock(entry.contentId);
} else {
openInChat(entry.contentId);
}
}
/// `/new` in a window's chat: the window follows the new session, unless
/// that session is already open elsewhere.
void startedNewSession(
String windowId,
String previousId,
JsonMap session,
String notice,
) {
runtime.sessions.replaceSession(previousId, session);
_follow(windowId, previousId, session, notice);
unawaited(runtime.sessions.refresh());
}
void _replacedElsewhere(String previousId, JsonMap session) {
final entry = manager.find(chatWindowKind, previousId);
if (entry == null) return;
_follow(entry.id, previousId, session, chatNewSessionElsewhereNotice);
}
void _follow(
String windowId,
String previousId,
JsonMap session,
String notice,
) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
final elsewhere =
manager.find(chatWindowKind, id) != null ||
(tiling?.holds(id) ?? false);
if (elsewhere) {
manager.close(windowId);
return;
}
runtime.movedToSession(previousId, session, notice);
manager.setContent(windowId, id);
}
/// `/close` was accepted for a window's chat.
void sessionClosed(String windowId) {
manager.close(windowId);
unawaited(runtime.sessions.refresh());
}
bool _reading = false;
/// The windows' chats take their rows (title, model, mode) from the
/// session list, which nothing else reads while the Chat destination is
/// not built.
void _rowsChanged() {
final ids = {for (final w in windows) w.contentId};
if (ids.isEmpty || !ready) return;
final sessions = runtime.sessions;
if (ids.any((id) => runtime.rowFor(id) == null) && !_reading) {
_reading = true;
unawaited(sessions.refresh().whenComplete(() => _reading = false));
}
final rows = sessions.sessions;
scheduleMicrotask(() {
if (_started) runtime.adoptRows(rows, selected: null, retained: ids);
});
}
bool get _wide {
final view = WidgetsBinding.instance.platformDispatcher.views.firstOrNull;
return view == null ||
view.physicalSize.width / view.devicePixelRatio >= kListDetailMinWidth;
}
/// Handled before any focused widget sees the key, so it works from a
/// composer or the terminal; ignored (left to them) when it does nothing.
KeyEventResult _key(KeyEvent event) {
if (!_wide || !chatFloatShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
if (windows.isEmpty) {
final tiling = this.tiling;
if (tiling == null || !tiling.canFloatActive()) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) tiling.floatActive();
return KeyEventResult.handled;
}
if (event is KeyDownEvent) manager.toggleGroup(chatWindowKind);
return KeyEventResult.handled;
}
}
class _Never implements Listenable {
const _Never();
@override
void addListener(VoidCallback listener) {}
@override
void removeListener(VoidCallback listener) {}
}
/// A chat in a floating window.
class ChatWindowKind extends WindowKind {
ChatWindowKind(this.windows);
final ChatWindows windows;
@override
String get key => chatWindowKind;
@override
bool get serverScoped => true;
@override
IconData get icon => Icons.chat_bubble_outline;
@override
Size get minSize => chatFloatMinSize;
@override
Rect get defaultFrame => chatFloatDefaultRect;
/// Chats float beside the chat list, on a wide layout only.
@override
double get minHostWidth => kListDetailMinWidth;
@override
Listenable get changes => windows.runtime;
@override
String title(BuildContext context, WindowEntry entry) =>
windows.runtime.titleFor(entry.contentId);
@override
Widget build(BuildContext context, WindowEntry entry) =>
ChatWindowContent(windows: windows, entry: entry);
@override
List<WindowAction> actions(BuildContext context, WindowEntry entry) => [
WindowAction(
label: 'Dock',
icon: Icons.vertical_split_outlined,
onPressed: () => windows.dock(entry),
),
];
@override
void focusContent(WindowEntry entry) =>
windows.runtime.composerFocus.request(entry.contentId);
}
@@ -1,156 +0,0 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'chat_float_store.dart';
import 'chat_workspace_controller.dart';
/// The floating chat windows' frames, by pane id. A drag moves a window every
/// pointer event without saving; [commit] marks the end of the drag. A pane
/// keeps its frame while it is docked, so floating it again puts the window
/// back where it was.
class ChatFloatFrames extends ChangeNotifier {
ChatFloatFrames([Map<String, Rect> frames = const {}])
: _frames = {...frames};
final Map<String, Rect> _frames;
int _commits = 0;
Map<String, Rect> get frames => Map.unmodifiable(_frames);
/// Advances when a move or resize ends (the binding saves then).
int get commits => _commits;
/// [paneId]'s frame; a window without one opens at the default frame,
/// stepped down and right by [index] so stacked windows stay visible.
Rect rectFor(String paneId, {int index = 0}) =>
_frames[paneId] ??
chatFloatDefaultRect.shift(Offset(32, 32) * index.toDouble());
/// Gives [paneId] its opening frame ([rectFor] at [index]) unless it has
/// one, so the window stays put when other windows come and go.
void place(String paneId, {required int index}) {
if (_frames.containsKey(paneId)) return;
move(paneId, rectFor(paneId, index: index));
}
void move(String paneId, Rect rect) {
if (_frames[paneId] == rect) return;
_frames[paneId] = rect;
notifyListeners();
}
/// Replaces every frame (a restore).
void restore(Map<String, Rect> frames) {
if (mapEquals(frames, _frames)) return;
_frames
..clear()
..addAll(frames);
notifyListeners();
}
void commit() {
_commits++;
notifyListeners();
}
}
/// Saves which chats float, whether they show and their windows' frames, and
/// restores them once the workspace layout itself has been restored.
class ChatFloatBinding {
ChatFloatBinding({
required this.controller,
required this.frames,
required this.store,
this.debounce = const Duration(milliseconds: 250),
}) {
controller.addListener(_changed);
frames.addListener(_framesChanged);
}
final ChatWorkspaceController controller;
final ChatFloatFrames frames;
final ChatFloatStore store;
final Duration debounce;
ChatFloatRecord? _saved;
bool _loading = true;
bool _disposed = false;
int _commits = 0;
Timer? _timer;
Future<void> _writes = Future.value();
/// Frames of panes still open somewhere (tiled or floating); a closed
/// pane's frame is dropped.
ChatFloatRecord get _current {
final open = {
for (final pane in controller.panes) pane.id,
for (final pane in controller.floatingPanes) pane.id,
};
return ChatFloatRecord(
panes: controller.floatingPanes,
shown: controller.floatShown,
frames: {
for (final MapEntry(:key, :value) in frames.frames.entries)
if (open.contains(key)) key: value,
},
);
}
/// Call after the workspace layout restored, so a saved float can tell
/// whether its chat is already open in the tiling.
Future<void> start() async {
ChatFloatRecord? record;
try {
record = await store.read();
} on Object {
// Unavailable preferences leave the default frames and no float.
}
if (_disposed) return;
if (record != null) {
_saved = record;
_commits = frames.commits;
frames.restore(record.frames);
if (record.panes.isNotEmpty && controller.floatingPanes.isEmpty) {
controller.restoreFloats(record.panes, shown: record.shown);
}
}
_loading = false;
_changed();
}
void _framesChanged() {
if (frames.commits == _commits) return;
_commits = frames.commits;
_changed();
}
void _changed() {
if (_disposed || _loading || _current == _saved) return;
_timer?.cancel();
_timer = Timer(debounce, flush);
}
Future<void> flush() {
_timer?.cancel();
_timer = null;
final record = _current;
if (_loading || record == _saved) return _writes;
_saved = record;
_writes = _writes.then((_) async {
try {
await store.write(record);
} on Object {
// A storage failure must not interrupt the chat.
}
});
return _writes;
}
void dispose() {
if (_disposed) return;
controller.removeListener(_changed);
frames.removeListener(_framesChanged);
unawaited(flush());
_disposed = true;
}
}
@@ -1,337 +0,0 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '../../../ui/floating/floating_layer.dart';
import '../../../ui/motion/motion.dart';
import '../../../ui/motion/surface_visibility.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_float_binding.dart';
import 'chat_float_shortcut.dart';
import 'chat_float_window.dart';
import 'chat_workspace_controller.dart';
/// The split workspace ([child]) with its floating chats over the app: their
/// windows, show and hide motion, focus and shortcut (see
/// [chatFloatShortcut]). [content] is a floating pane's live view, moved here
/// from the tiling rather than rebuilt.
///
/// The windows show while [enabled] (a wide layout), over every destination,
/// like the floating terminal. They show and hide together.
class ChatFloatHost extends StatefulWidget {
const ChatFloatHost({
super.key,
required this.controller,
required this.frames,
required this.enabled,
required this.title,
required this.content,
required this.scope,
required this.focusedPane,
required this.onFocusPane,
required this.child,
});
final ChatWorkspaceController controller;
final ChatFloatFrames frames;
final bool enabled;
final String Function(ChatWorkspacePane pane) title;
final Widget Function(ChatWorkspacePane pane) content;
/// A floating pane's focus scope.
final FocusScopeNode? Function(ChatWorkspacePane pane) scope;
/// The tiled pane with the keyboard, which the shortcut floats when no
/// chat floats yet.
final ChatWorkspacePane? Function() focusedPane;
final ValueChanged<ChatWorkspacePane>? onFocusPane;
final Widget child;
@override
State<ChatFloatHost> createState() => _ChatFloatHostState();
}
class _ChatFloatHostState extends State<ChatFloatHost> {
bool _visible = false;
Set<String> _paneIds = const {};
FocusNode? _previous;
@override
void initState() {
super.initState();
FocusManager.instance.addEarlyKeyEventHandler(_key);
widget.controller.addListener(_sync);
WidgetsBinding.instance.addPostFrameCallback((_) => _sync());
}
@override
void didUpdateWidget(covariant ChatFloatHost oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_sync);
widget.controller.addListener(_sync);
}
if (oldWidget.enabled != widget.enabled) {
WidgetsBinding.instance.addPostFrameCallback((_) => _sync());
}
}
@override
void dispose() {
FocusManager.instance.removeEarlyKeyEventHandler(_key);
widget.controller.removeListener(_sync);
super.dispose();
}
void _sync() {
if (!mounted) return;
final panes = widget.controller.floatingPanes;
final ids = {for (final pane in panes) pane.id};
final visible = widget.enabled && widget.controller.floatShown;
for (final (index, pane) in panes.indexed) {
widget.frames.place(pane.id, index: index);
}
if (panes.isEmpty) {
// Docked or closed: the views went back to the tiling.
_previous = null;
} else if (visible != _visible) {
if (visible) {
_remember();
_focusSoon(panes.last);
} else {
_release();
}
} else if (visible) {
// A newly floated chat takes the keyboard.
final added = panes.where((p) => !_paneIds.contains(p.id)).lastOrNull;
if (added != null) _focusSoon(added);
}
_paneIds = ids;
if (visible != _visible) setState(() => _visible = visible);
}
bool _inside(FocusNode node) => widget.controller.floatingPanes.any((pane) {
final scope = widget.scope(pane);
return scope != null &&
(identical(node, scope) || node.ancestors.contains(scope));
});
void _remember() {
final current = FocusManager.instance.primaryFocus;
if (current == null || _inside(current)) return;
_previous = identical(current, FocusManager.instance.rootScope)
? null
: current;
}
void _focusSoon(ChatWorkspacePane pane) {
WidgetsBinding.instance
..addPostFrameCallback((_) {
if (!mounted || !widget.controller.isFloating(pane.id)) return;
final focus = widget.onFocusPane;
if (focus != null) {
focus(pane);
} else {
widget.scope(pane)?.requestFocus();
}
})
..ensureVisualUpdate();
}
/// Gives the keyboard back to what had it before the chats showed, if a
/// floating chat has it now.
void _release() {
final previous = _previous;
_previous = null;
final current = FocusManager.instance.primaryFocus;
if (current == null || !_inside(current)) return;
if (previous != null &&
previous.context != null &&
previous.canRequestFocus) {
previous.requestFocus();
} else {
current.unfocus();
}
}
/// Handled before any focused widget sees the key, so it works from a
/// composer or the terminal; ignored (left to them) when it does nothing.
KeyEventResult _key(KeyEvent event) {
if (!mounted ||
!widget.enabled ||
!chatFloatShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
final controller = widget.controller;
if (controller.floatingPanes.isEmpty) {
final pane = widget.focusedPane();
if (pane == null || !controller.canFloat(pane.id)) {
return KeyEventResult.ignored;
}
if (event is KeyDownEvent) controller.float(pane.id);
return KeyEventResult.handled;
}
if (event is KeyDownEvent) controller.toggleFloatShown();
return KeyEventResult.handled;
}
@override
Widget build(BuildContext context) {
final panes = widget.controller.floatingPanes;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return Stack(
fit: StackFit.expand,
children: [
widget.child,
for (final (index, pane) in panes.indexed)
Positioned.fill(
key: ValueKey(pane.id),
// Shown over every destination; the window's motion keeps
// running there (see [_ChatFloatSlot]).
child: FloatingLayer(
open: _visible,
coverOverlay: true,
builder: (context, bounds) => [
ListenableBuilder(
listenable: widget.frames,
builder: (context, _) => _ChatFloatSlot(
visible: _visible,
rect: widget.frames.rectFor(pane.id, index: index),
currentRect: () =>
widget.frames.rectFor(pane.id, index: index),
onMove: (rect) => widget.frames.move(pane.id, rect),
onCommit: widget.frames.commit,
bounds: bounds,
title: widget.title(pane),
cupertino: cupertino,
onDock: () => widget.controller.dock(pane.id),
onHide: () => widget.controller.setFloatShown(false),
child: widget.content(pane),
),
),
],
),
),
],
);
}
}
/// One floating chat's window and its own grow-and-fade motion, so a chat
/// floated while the others show animates in alone.
class _ChatFloatSlot extends StatefulWidget {
const _ChatFloatSlot({
required this.visible,
required this.rect,
required this.currentRect,
required this.onMove,
required this.onCommit,
required this.bounds,
required this.title,
required this.cupertino,
required this.onDock,
required this.onHide,
required this.child,
});
final bool visible;
final Rect rect;
final Rect Function() currentRect;
final ValueChanged<Rect> onMove;
final VoidCallback onCommit;
final Size bounds;
final String title;
final bool cupertino;
final VoidCallback onDock;
final VoidCallback onHide;
final Widget child;
@override
State<_ChatFloatSlot> createState() => _ChatFloatSlotState();
}
class _ChatFloatSlotState extends State<_ChatFloatSlot>
implements TickerProvider {
Ticker? _ticker;
/// A ticker the hidden destination's [TickerMode] does not mute: the
/// window must still show and hide over another destination, and a
/// TickerMode cannot re-enable what an ancestor turned off.
@override
Ticker createTicker(TickerCallback onTick) {
assert(_ticker == null, 'one reveal ticker per window');
return _ticker = Ticker(onTick, debugLabel: 'chat float reveal');
}
late final AnimationController _reveal = AnimationController(
vsync: this,
duration: Motion.standard,
);
late final CurvedAnimation _curve = CurvedAnimation(
parent: _reveal,
curve: Motion.curve,
reverseCurve: Curves.easeInCubic,
);
@override
void initState() {
super.initState();
if (widget.visible) {
WidgetsBinding.instance.addPostFrameCallback((_) => _run());
}
}
@override
void didUpdateWidget(covariant _ChatFloatSlot oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.visible != widget.visible) _run();
}
void _run() {
if (!mounted) return;
_reveal.duration = Motion.of(context, Motion.standard);
unawaited(widget.visible ? _reveal.forward() : _reveal.reverse());
}
@override
void dispose() {
_curve.dispose();
_reveal.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: _reveal,
builder: (context, _) {
final offstage = !widget.visible && _reveal.isDismissed;
return ChatFloatWindow(
rect: widget.rect,
currentRect: widget.currentRect,
onMove: widget.onMove,
onCommit: widget.onCommit,
bounds: widget.bounds,
title: widget.title,
cupertino: widget.cupertino,
reveal: _curve,
hiding: !widget.visible,
offstage: offstage,
shortcut: chatFloatShortcutLabel(),
onDock: widget.onDock,
onHide: widget.onHide,
// A hidden window's chat pauses its tickers like a hidden tab.
child: TickerMode(
enabled: !offstage,
child: SurfaceVisibility(
shown: !offstage,
current: !offstage,
child: widget.child,
),
),
);
},
);
}
@@ -37,7 +37,7 @@ bool chatFloatShortcut(
bool _apple(TargetPlatform platform) => bool _apple(TargetPlatform platform) =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The floating chat's shortcut as it reads on this platform, for menus and /// The floating chats' shortcut as it reads on this platform, for menus and
/// tooltips. /// tooltips: the Alt chord, which every platform and browser delivers.
String chatFloatShortcutLabel([TargetPlatform? platform]) => String chatFloatShortcutLabel([TargetPlatform? platform]) =>
_apple(platform ?? defaultTargetPlatform) ? 'Cmd+Y' : 'Ctrl+Y'; _apple(platform ?? defaultTargetPlatform) ? 'Option+Y' : 'Alt+Y';
@@ -1,229 +0,0 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/window_margins.dart';
import '../../terminal/terminal_float_frame.dart' show terminalFloatChrome;
import 'chat_float_store.dart';
/// [rect] moved and shrunk to fit inside [bounds], at least the smallest
/// window where the bounds allow it.
Rect fitChatFloat(Rect rect, Size bounds) {
final width = rect.width
.clamp(chatFloatMinSize.width, double.infinity)
.clamp(0.0, bounds.width);
final height = rect.height
.clamp(chatFloatMinSize.height, double.infinity)
.clamp(0.0, bounds.height);
return Rect.fromLTWH(
rect.left.clamp(0.0, bounds.width - width),
rect.top.clamp(0.0, bounds.height - height),
width,
height,
);
}
/// A floating chat's window: moved by its title bar, resized from its
/// lower right corner, kept inside [bounds]. It grows and fades in from its
/// place as [reveal] runs forward and leaves the same way in reverse.
class ChatFloatWindow extends StatelessWidget {
const ChatFloatWindow({
super.key,
required this.rect,
required this.currentRect,
required this.onMove,
required this.onCommit,
required this.bounds,
required this.title,
required this.cupertino,
required this.reveal,
required this.hiding,
this.offstage = false,
required this.shortcut,
required this.onDock,
required this.onHide,
required this.child,
});
/// The saved frame; it is drawn fitted inside [bounds].
final Rect rect;
/// The frame now: several drag events can arrive before a rebuild.
final Rect Function() currentRect;
final ValueChanged<Rect> onMove;
/// A move or resize ended.
final VoidCallback onCommit;
final Size bounds;
final String title;
final bool cupertino;
final Animation<double> reveal;
/// While the window hides it takes no input.
final bool hiding;
/// Hidden and settled: kept built (the chat keeps its state) but unpainted.
final bool offstage;
final String shortcut;
final VoidCallback onDock;
final VoidCallback onHide;
final Widget child;
static const double revealScale = 0.92;
void _resize(Offset delta) {
final rect = fitChatFloat(currentRect(), bounds);
onMove(
fitChatFloat(
Rect.fromLTWH(
rect.left,
rect.top,
rect.width + delta.dx,
rect.height + delta.dy,
),
bounds,
),
);
}
@override
Widget build(BuildContext context) {
final rect = fitChatFloat(this.rect, bounds);
final window = SizedBox.fromSize(
size: rect.size,
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_titleBar(context, rect),
Expanded(
child: MediaQuery.removePadding(
context: context,
removeTop: true,
removeBottom: true,
removeLeft: true,
removeRight: true,
// A small window keeps the compact bar insets.
child: WindowMargins.compact(child: child),
),
),
],
),
PositionedDirectional(end: 0, bottom: 0, child: _corner()),
],
),
);
return Positioned(
left: rect.left,
top: rect.top,
child: Offstage(
offstage: offstage,
child: IgnorePointer(
ignoring: hiding,
child: ExcludeFocus(
excluding: hiding,
child: FadeTransition(
opacity: reveal,
child: ScaleTransition(
scale: Tween<double>(
begin: revealScale,
end: 1,
).animate(reveal),
child: Semantics(
container: true,
label: 'Floating chat: $title',
identifier: 'chat-float-window',
child: terminalFloatChrome(context, cupertino, window),
),
),
),
),
),
),
);
}
Widget _titleBar(BuildContext context, Rect rect) {
final label = Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleSmall,
);
final drag = MouseRegion(
cursor: SystemMouseCursors.move,
child: GestureDetector(
key: const ValueKey('chat-float-title'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onPanUpdate: (details) => onMove(
fitChatFloat(
fitChatFloat(currentRect(), bounds).shift(details.delta),
bounds,
),
),
onPanEnd: (_) => onCommit(),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: label,
),
),
),
);
return Row(
children: [
Expanded(child: drag),
_button(
'Dock',
Icons.vertical_split_outlined,
CupertinoIcons.rectangle_split_3x1,
onDock,
),
_button(
'Hide floating chats ($shortcut)',
Icons.close,
CupertinoIcons.xmark,
onHide,
),
],
);
}
Widget _button(
String label,
IconData material,
IconData cupertinoIcon,
VoidCallback onPressed,
) => cupertino
? CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 8),
onPressed: onPressed,
child: Icon(cupertinoIcon, semanticLabel: label),
)
: IconButton(tooltip: label, onPressed: onPressed, icon: Icon(material));
Widget _corner() => Semantics(
label: 'Resize floating chat',
child: MouseRegion(
cursor: SystemMouseCursors.resizeDownRight,
child: GestureDetector(
key: const ValueKey('chat-float-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onPanUpdate: (details) => _resize(details.delta),
onPanEnd: (_) => onCommit(),
child: Padding(
padding: const EdgeInsets.all(4),
child: Icon(
cupertino ? CupertinoIcons.arrow_down_right : Icons.south_east,
),
),
),
),
);
}
@@ -3,14 +3,11 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import '../../../ui/floating/floating_layer.dart';
import '../../../ui/motion/motion.dart'; import '../../../ui/motion/motion.dart';
import '../../../ui/motion/quick_switch_animation.dart'; import '../../../ui/motion/quick_switch_animation.dart';
import 'chat_center_stage_layout.dart'; import 'chat_center_stage_layout.dart';
import 'chat_center_stage_motion.dart'; import 'chat_center_stage_motion.dart';
import 'chat_center_stage_strip.dart'; import 'chat_center_stage_strip.dart';
import 'chat_float_binding.dart';
import 'chat_float_host.dart';
import 'chat_workspace_controller.dart'; import 'chat_workspace_controller.dart';
import 'chat_workspace_geometry.dart'; import 'chat_workspace_geometry.dart';
import 'chat_mobile_panes.dart'; import 'chat_mobile_panes.dart';
@@ -45,7 +42,6 @@ class ChatWorkspace extends StatefulWidget {
this.onVisibleSessionIdsChanged, this.onVisibleSessionIdsChanged,
this.centerStage, this.centerStage,
this.paneColor, this.paneColor,
this.floatFrames,
}); });
final ChatWorkspaceController controller; final ChatWorkspaceController controller;
final ChatWorkspacePaneBuilder paneBuilder; final ChatWorkspacePaneBuilder paneBuilder;
@@ -65,11 +61,6 @@ class ChatWorkspace extends StatefulWidget {
/// A pane's chat colour, for its strip beside the stage. /// A pane's chat colour, for its strip beside the stage.
final Color? Function(ChatWorkspacePane)? paneColor; final Color? Function(ChatWorkspacePane)? paneColor;
/// Offers floating chats (see [ChatFloatHost]) in these frames; null for a
/// workspace without them. They show only while the panes are not
/// collapsed.
final ChatFloatFrames? floatFrames;
/// Keyboard navigation only: the owner can focus the target composer. /// Keyboard navigation only: the owner can focus the target composer.
/// Pointer activation leaves text-selection and pointer focus alone. /// Pointer activation leaves text-selection and pointer focus alone.
final ValueChanged<ChatWorkspacePane>? onFocusPane; final ValueChanged<ChatWorkspacePane>? onFocusPane;
@@ -83,8 +74,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
final _focus = FocusNode(debugLabel: 'Chat workspace'); final _focus = FocusNode(debugLabel: 'Chat workspace');
final Map<String, FocusScopeNode> _panes = {}; final Map<String, FocusScopeNode> _panes = {};
/// Each pane's view keeps its State when it moves into or out of the /// Each pane's view keeps its State as the tiling rearranges.
/// floating window.
final Map<String, GlobalKey> _views = {}; final Map<String, GlobalKey> _views = {};
late final ChatPaneSwitchMotion _motion; late final ChatPaneSwitchMotion _motion;
late final ChatCenterStageMotion _stage = ChatCenterStageMotion(vsync: this); late final ChatCenterStageMotion _stage = ChatCenterStageMotion(vsync: this);
@@ -295,13 +285,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
: !collapsed || pane.id == activeId) : !collapsed || pane.id == activeId)
pane.sessionId, pane.sessionId,
}); });
final floating = widget.floatFrames == null final existing = {...panes.map((p) => p.id)};
? const <ChatWorkspacePane>[]
: widget.controller.floatingPanes;
final existing = {
...panes.map((p) => p.id),
...floating.map((p) => p.id),
};
_views.removeWhere((id, _) => !existing.contains(id)); _views.removeWhere((id, _) => !existing.contains(id));
for (final id for (final id
in _panes.keys.where((id) => !existing.contains(id)).toList()) { in _panes.keys.where((id) => !existing.contains(id)).toList()) {
@@ -342,7 +326,7 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
edge, edge,
}, },
}; };
final surface = chatWorkspaceSurface( return chatWorkspaceSurface(
context: context, context: context,
backdrop: _backdrop, backdrop: _backdrop,
motion: _motion, motion: _motion,
@@ -364,21 +348,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
moveTargets[pane.id], moveTargets[pane.id],
), ),
); );
final frames = widget.floatFrames;
if (frames == null) return surface;
return ChatFloatHost(
controller: widget.controller,
frames: frames,
enabled: !widget.singlePane,
title: (pane) => widget.paneTitle?.call(pane) ?? pane.sessionId,
content: _floatView,
scope: (pane) => _panes[pane.id],
focusedPane: () => widget.controller.panes
.where((pane) => _panes[pane.id]?.hasFocus ?? false)
.firstOrNull,
onFocusPane: widget.onFocusPane,
child: surface,
);
}, },
), ),
), ),
@@ -441,19 +410,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
); );
} }
/// A floating chat's view: the same keyed content as in the tiling, so
/// floating and docking move it without rebuilding the chat. Its focus
/// hangs from the shell's [FloatingFocusRoot], so it keeps the keyboard
/// while another destination (which excludes this one) shows.
Widget _floatView(ChatWorkspacePane pane) => _paneContent(
pane,
active: true,
peek: false,
mobile: false,
edges: {},
focusParent: FloatingFocusRoot.maybeOf(context),
);
Widget _paneContent( Widget _paneContent(
ChatWorkspacePane pane, { ChatWorkspacePane pane, {
required bool active, required bool active,
@@ -461,7 +417,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
required bool mobile, required bool mobile,
required Set<String> edges, required Set<String> edges,
Map<ChatPaneDirection, String>? moveTargets, Map<ChatPaneDirection, String>? moveTargets,
FocusNode? focusParent,
}) { }) {
var actionBarPointerDown = false; var actionBarPointerDown = false;
bool preservesStageForActionBar() => bool preservesStageForActionBar() =>
@@ -469,7 +424,6 @@ class _ChatWorkspaceState extends State<ChatWorkspace>
return KeyedSubtree( return KeyedSubtree(
key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)), key: _views.putIfAbsent(pane.id, () => GlobalKey(debugLabel: pane.id)),
child: FocusScope( child: FocusScope(
parentNode: focusParent,
node: _panes.putIfAbsent( node: _panes.putIfAbsent(
pane.id, pane.id,
() => FocusScopeNode(debugLabel: pane.id), () => FocusScopeNode(debugLabel: pane.id),
@@ -12,10 +12,9 @@ class ChatWorkspaceController extends ChangeNotifier {
ChatWorkspaceNode? _root; ChatWorkspaceNode? _root;
String? _active; String? _active;
/// The chats taken out of the tiling into floating windows, oldest first. /// Shows the window [sessionId] is out in and returns true, or returns
/// They show and hide together. /// false when it is in none. Set by whoever hosts floating chats.
final List<ChatWorkspacePane> _floating = []; bool Function(String sessionId)? showOutside;
bool _floatShown = false;
double _mobilePeekFraction = .2; double _mobilePeekFraction = .2;
double get mobilePeekFraction => _mobilePeekFraction; double get mobilePeekFraction => _mobilePeekFraction;
void resizeMobilePeek(double fraction) { void resizeMobilePeek(double fraction) {
@@ -56,7 +55,6 @@ class ChatWorkspaceController extends ChangeNotifier {
} }
collect(_root); collect(_root);
_floating.forEach(collect);
String id; String id;
do { do {
id = 'chat-$kind-${++_serial}'; id = 'chat-$kind-${++_serial}';
@@ -70,7 +68,6 @@ class ChatWorkspaceController extends ChangeNotifier {
_root = snapshot.root; _root = snapshot.root;
_active = snapshot.activePaneId; _active = snapshot.activePaneId;
_mobilePeekFraction = snapshot.mobilePeekFraction; _mobilePeekFraction = snapshot.mobilePeekFraction;
_floating.clear();
_serial = 0; _serial = 0;
_changed(); _changed();
return true; return true;
@@ -193,12 +190,10 @@ class ChatWorkspaceController extends ChangeNotifier {
} }
void close(String paneId) { void close(String paneId) {
if (_closeFloating(paneId)) return;
final before = panes; final before = panes;
final index = before.indexWhere((p) => p.id == paneId); final index = before.indexWhere((p) => p.id == paneId);
if (index < 0) return; if (index < 0) return;
_root = _remove(_root!, paneId); _root = _remove(_root!, paneId);
_adoptFloatingIfEmpty();
final after = panes; final after = panes;
if (_active == paneId) { if (_active == paneId) {
_active = after.isEmpty _active = after.isEmpty
@@ -1,30 +1,21 @@
part of 'chat_workspace_controller.dart'; part of 'chat_workspace_controller.dart';
/// Chats can leave the split tiling for floating windows over the app. They /// Chats can leave the split tiling for floating windows over the app (see
/// show and hide together. A floating pane keeps its id (and so its live view) /// `ChatWindows`). The tiling keeps none of them: it only asks whether a
/// while it floats, hides or docks. /// chat is out in a window before opening it.
extension ChatWorkspaceFloat on ChatWorkspaceController { extension ChatWorkspaceFloat on ChatWorkspaceController {
/// The floating chats, shown or hidden, oldest first. /// Whether [sessionId] is open in the tiling.
List<ChatWorkspacePane> get floatingPanes => List.unmodifiable(_floating);
/// Whether [paneId] floats.
bool isFloating(String paneId) => _floating.any((pane) => pane.id == paneId);
/// Whether the floating chats are shown (rather than hidden by Ctrl+Y).
bool get floatShown => _floating.isNotEmpty && _floatShown;
/// Whether [sessionId] is open in the tiling or a floating window.
bool holdsSession(String sessionId) => bool holdsSession(String sessionId) =>
_floating.any((pane) => pane.sessionId == sessionId) ||
panes.any((pane) => pane.sessionId == sessionId); panes.any((pane) => pane.sessionId == sessionId);
/// A tiled pane can float while another chat stays in the tiling. /// A tiled pane can float while another chat stays in the tiling.
bool canFloat(String paneId) => bool canFloat(String paneId) =>
paneCount > 1 && panes.any((pane) => pane.id == paneId); paneCount > 1 && panes.any((pane) => pane.id == paneId);
/// Floats the tiled pane [paneId] and shows every floating chat. /// Takes the tiled pane [paneId] out of the tiling for a window; the pane
void float(String paneId) { /// beside it becomes active. Null when it cannot float.
if (!canFloat(paneId)) return; ChatWorkspacePane? detach(String paneId) {
if (!canFloat(paneId)) return null;
final pane = panes.firstWhere((pane) => pane.id == paneId); final pane = panes.firstWhere((pane) => pane.id == paneId);
final index = panes.indexWhere((p) => p.id == paneId); final index = panes.indexWhere((p) => p.id == paneId);
_root = _remove(_root!, paneId); _root = _remove(_root!, paneId);
@@ -32,18 +23,20 @@ extension ChatWorkspaceFloat on ChatWorkspaceController {
final after = panes; final after = panes;
_active = after[index.clamp(0, after.length - 1)].id; _active = after[index.clamp(0, after.length - 1)].id;
} }
_floating.add(pane);
_floatShown = true;
_changed(); _changed();
return pane;
} }
/// Puts the floating chat [paneId] back into the tiling, to the right of /// Puts the chat [sessionId] back from its window into the tiling, to the
/// the active pane, and makes it the active pane. /// right of the active pane, and makes it the active pane.
void dock(String paneId) { void dock(String sessionId) {
final at = _floating.indexWhere((pane) => pane.id == paneId); if (sessionId.isEmpty) return;
if (at < 0) return; final existing = panes.where((p) => p.sessionId == sessionId).firstOrNull;
final pane = _floating.removeAt(at); if (existing != null) {
final split = _id('split'); activate(existing.id);
return;
}
final pane = ChatWorkspacePane(_id('pane'), sessionId);
if (_root == null) { if (_root == null) {
_root = pane; _root = pane;
} else { } else {
@@ -51,93 +44,27 @@ extension ChatWorkspaceFloat on ChatWorkspaceController {
_root = _replace( _root = _replace(
_root!, _root!,
target.id, target.id,
ChatWorkspaceSplit(split, ChatSplitAxis.horizontal, target, pane), ChatWorkspaceSplit(
_id('split'),
ChatSplitAxis.horizontal,
target,
pane,
),
); );
} }
_active = pane.id; _active = pane.id;
_changed(); _changed();
} }
void setFloatShown(bool shown) { /// Opening a chat that is out in a window shows that window instead.
if (_floating.isEmpty || _floatShown == shown) return; bool _showFloating(String sessionId) => showOutside?.call(sessionId) ?? false;
_floatShown = shown;
_changed();
}
void toggleFloatShown() => setFloatShown(!_floatShown); /// A tiled chat moved to a session that is out in a window: the window
/// stays and the tiled pane closes.
/// Restores saved floating chats, skipping any whose session is already
/// open or whose pane id is taken. With no tiled pane the first becomes
/// the tiling instead. Returns how many were restored.
int restoreFloats(List<ChatWorkspacePane> saved, {required bool shown}) {
var restored = 0;
for (final pane in saved) {
if (holdsSession(pane.sessionId) || _taken(pane.id)) continue;
if (_root == null) {
_root = pane;
_active = pane.id;
} else {
_floating.add(pane);
}
restored++;
}
if (restored == 0) return 0;
_floatShown = shown;
_changed();
return restored;
}
bool _taken(String id) {
bool inTree(ChatWorkspaceNode? node) =>
node != null &&
(node.id == id ||
node is ChatWorkspaceSplit &&
(inTree(node.first) || inTree(node.second)));
return inTree(_root) || isFloating(id);
}
/// Opening a floating chat (from the list, a link) shows the floats.
bool _showFloating(String sessionId) {
if (!_floating.any((pane) => pane.sessionId == sessionId)) return false;
setFloatShown(true);
return true;
}
bool _closeFloating(String paneId) {
final at = _floating.indexWhere((pane) => pane.id == paneId);
if (at < 0) return false;
_floating.removeAt(at);
_changed();
return true;
}
/// The tiling never empties while a chat floats: the oldest one docks.
void _adoptFloatingIfEmpty() {
if (_root != null || _floating.isEmpty) return;
_root = _floating.removeAt(0);
}
/// `/new` in a floating chat keeps it floating under the new session.
bool _replaceFloating(String oldId, String newId) { bool _replaceFloating(String oldId, String newId) {
final at = _floating.indexWhere((pane) => pane.sessionId == oldId); if (!(showOutside?.call(newId) ?? false)) return false;
if (at >= 0) {
final pane = _floating[at];
final elsewhere =
panes.any((p) => p.sessionId == newId) ||
_floating.any((p) => p.sessionId == newId);
if (elsewhere) {
_closeFloating(pane.id);
} else {
_floating[at] = ChatWorkspacePane(pane.id, newId);
_changed();
}
return true;
}
if (!_floating.any((pane) => pane.sessionId == newId)) return false;
// A tiled chat moved to a session that floats: the float stays.
final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull; final tiled = panes.where((p) => p.sessionId == oldId).firstOrNull;
if (tiled != null) close(tiled.id); if (tiled != null) close(tiled.id);
setFloatShown(true);
return true; return true;
} }
} }
@@ -142,8 +142,10 @@ class ChatWorkspaceGeometry {
}; };
if (gap < -slack || gap > chatPaneDividerExtent + slack) continue; if (gap < -slack || gap > chatPaneDividerExtent + slack) continue;
final overlap = horizontal final overlap = horizontal
? math.min(origin.bottom, rect.bottom) - math.max(origin.top, rect.top) ? math.min(origin.bottom, rect.bottom) -
: math.min(origin.right, rect.right) - math.max(origin.left, rect.left); math.max(origin.top, rect.top)
: math.min(origin.right, rect.right) -
math.max(origin.left, rect.left);
if (overlap <= slack) continue; if (overlap <= slack) continue;
final centred = horizontal final centred = horizontal
? rect.top <= centre && centre < rect.bottom ? rect.top <= centre && centre < rect.bottom
@@ -113,10 +113,7 @@ class _DiscoveredServerRowState extends State<DiscoveredServerRow> {
_choice(context, cupertino, address), _choice(context, cupertino, address),
Padding( Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Align( child: Align(alignment: AlignmentDirectional.centerStart, child: use),
alignment: AlignmentDirectional.centerStart,
child: use,
),
), ),
], ],
); );
@@ -1,3 +1,4 @@
import '../../../ui/adaptive/app_menu_anchor.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -108,7 +109,7 @@ class PipelineSortButton extends StatelessWidget {
), ),
); );
} }
return MenuAnchor( return AppMenuAnchor(
menuChildren: [ menuChildren: [
for (final option in PipelineSort.values) for (final option in PipelineSort.values)
MenuItemButton( MenuItemButton(
@@ -108,7 +108,9 @@ class _SavedServerSignInStepState extends State<SavedServerSignInStep> {
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(strokeWidth: 2),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Expanded(child: Text('Saved. Checking whether $name needs a sign-in…')), Expanded(
child: Text('Saved. Checking whether $name needs a sign-in…'),
),
], ],
); );
} }
@@ -57,11 +57,12 @@ class TerminalShortcutLabels {
bool get _apple => bool get _apple =>
platform == TargetPlatform.macOS || platform == TargetPlatform.iOS; platform == TargetPlatform.macOS || platform == TargetPlatform.iOS;
/// The keys that show or hide the terminal, most convenient first. /// The keys that show or hide the terminal. The Alt chord leads (the
/// button's tooltip names it): every platform and browser delivers it.
List<String> get toggle => [ List<String> get toggle => [
_apple ? 'Option+T' : 'Alt+T',
if (!web && _apple) 'Cmd+T', if (!web && _apple) 'Cmd+T',
if (!web || _apple) 'Ctrl+T', if (!web || _apple) 'Ctrl+T',
_apple ? 'Option+T' : 'Alt+T',
'Ctrl+`', 'Ctrl+`',
]; ];
+4 -8
View File
@@ -1,4 +1,3 @@
import '../ui/floating/floating_layer.dart';
import '../ui/motion/fade_through_stack.dart'; import '../ui/motion/fade_through_stack.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -423,15 +422,12 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
); );
} }
// Floating windows (chats) keep the keyboard over every destination.
Widget _destinationStack(List<Widget> contents) => ListPaneWidthsScope( Widget _destinationStack(List<Widget> contents) => ListPaneWidthsScope(
widths: _paneWidths, widths: _paneWidths,
child: FloatingFocusRoot( child: FadeThroughStack(
child: FadeThroughStack( key: _destinationStackKey,
key: _destinationStackKey, index: AppDestination.values.indexOf(_selected),
index: AppDestination.values.indexOf(_selected), children: contents,
children: contents,
),
), ),
); );
} }
+16 -5
View File
@@ -40,18 +40,29 @@ class WindowFocus {
: current; : current;
} }
/// Focuses [id]'s window once this frame has built it. /// Whether something covers the windows and owns the keyboard (a sheet,
/// dialog or page over the app); set by the host.
bool Function()? covered;
/// Focuses [id]'s window once this frame has built it, unless a popup the
/// same press opened has covered the windows meanwhile.
void focusSoon(String id) { void focusSoon(String id) {
WidgetsBinding.instance WidgetsBinding.instance
..addPostFrameCallback((_) { ..addPostFrameCallback((_) {
final scope = _scopes[id]; if (covered?.call() ?? false) return;
if (scope != null && scope.context != null && scope.canRequestFocus) { focusNow(id);
scope.requestFocus();
}
}) })
..ensureVisualUpdate(); ..ensureVisualUpdate();
} }
/// Focuses [id]'s window if it is built.
void focusNow(String id) {
final scope = _scopes[id];
if (scope != null && scope.context != null && scope.canRequestFocus) {
scope.requestFocus();
}
}
/// Gives the keyboard back to what had it before the windows showed, if /// Gives the keyboard back to what had it before the windows showed, if
/// a window has it now. /// a window has it now.
void release() { void release() {
+41 -24
View File
@@ -33,6 +33,9 @@ class _WindowHostState extends State<WindowHost> {
void initState() { void initState() {
super.initState(); super.initState();
widget.manager.addListener(_changed); widget.manager.addListener(_changed);
// The shell page is not the top route while a popup or page covers it.
_focus.covered = () =>
mounted && !(ModalRoute.of(context)?.isCurrent ?? true);
WidgetsBinding.instance.addPostFrameCallback((_) => _changed()); WidgetsBinding.instance.addPostFrameCallback((_) => _changed());
} }
@@ -68,41 +71,55 @@ class _WindowHostState extends State<WindowHost> {
if (_visible.isEmpty && visible.isNotEmpty) _focus.remember(); if (_visible.isEmpty && visible.isNotEmpty) _focus.remember();
if (active == null) { if (active == null) {
if (_visible.isNotEmpty) _focus.release(); if (_visible.isNotEmpty) _focus.release();
} else if (active != _active || !_visible.contains(active)) { } else if (active != _active ||
_focus.focusSoon(active); !_visible.contains(active) ||
} else if (focused != null && !visible.contains(focused)) { (focused != null && !visible.contains(focused))) {
_focus.focusSoon(active); _focusWindow(active);
} }
_visible = visible; _visible = visible;
_active = active; _active = active;
setState(() {}); setState(() {});
} }
/// The window takes the keyboard, then its content places it.
void _focusWindow(String id) {
_focus.focusSoon(id);
final entry = widget.manager.byId(id);
if (entry != null) widget.manager.kinds[entry.kind]?.focusContent(entry);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final manager = widget.manager; final manager = widget.manager;
final windows = manager.windows; final windows = manager.windows;
_focus.retain({for (final w in windows) w.id}); _focus.retain({for (final w in windows) w.id});
return LayoutBuilder( return ListenableBuilder(
builder: (context, constraints) { listenable: Listenable.merge([
final bounds = constraints.biggest; for (final kind in manager.kinds.all) ?kind.changes,
return Stack( ]),
fit: StackFit.expand, builder: (context, _) => LayoutBuilder(
children: [ builder: (context, constraints) {
for (final entry in windows) final bounds = constraints.biggest;
if (manager.kinds[entry.kind] case final kind?) return Stack(
WindowLayer( fit: StackFit.expand,
key: ValueKey(entry.id), children: [
manager: manager, for (final entry in windows)
kind: kind, if (manager.kinds[entry.kind] case final kind?)
entry: entry, WindowLayer(
visible: manager.isVisible(entry), key: ValueKey(entry.id),
bounds: bounds, manager: manager,
focus: _focus, kind: kind,
), entry: entry,
], visible:
); manager.isVisible(entry) &&
}, bounds.width >= kind.minHostWidth,
bounds: bounds,
focus: _focus,
),
],
);
},
),
); );
} }
} }
+11
View File
@@ -46,6 +46,17 @@ abstract class WindowKind {
List<WindowAction> actions(BuildContext context, WindowEntry entry) => List<WindowAction> actions(BuildContext context, WindowEntry entry) =>
const []; const [];
/// Notifies when a title or the actions of this kind's windows change.
Listenable? get changes => null;
/// The narrowest app this kind's windows show in; below it they hide (and
/// come back when the app widens).
double get minHostWidth => 0;
/// Puts the keyboard where [entry]'s content wants it (a chat's composer)
/// as its window takes focus. The default leaves it on the window.
void focusContent(WindowEntry entry) {}
/// Called after the user closes the window (the X). /// Called after the user closes the window (the X).
void closed(WindowEntry entry) {} void closed(WindowEntry entry) {}
+8 -2
View File
@@ -117,9 +117,12 @@ class _WindowLayerState extends State<WindowLayer>
); );
} }
/// A press brings the window to the top and gives it the keyboard at
/// once, before the press does anything else (focus a field, open a
/// popup that takes the keyboard itself).
void _pressed() { void _pressed() {
if (!widget.focus.has(_id)) widget.focus.focusNow(_id);
widget.manager.raise(_id); widget.manager.raise(_id);
if (!widget.focus.has(_id)) widget.focus.focusSoon(_id);
} }
@override @override
@@ -203,6 +206,7 @@ class _WindowLayerState extends State<WindowLayer>
], ],
); );
final center = widget.bounds.center(Offset.zero); final center = widget.bounds.center(Offset.zero);
final current = ModalRoute.of(context)?.isCurrent ?? true;
return AnimatedBuilder( return AnimatedBuilder(
animation: _reveal, animation: _reveal,
builder: (context, child) { builder: (context, child) {
@@ -213,7 +217,9 @@ class _WindowLayerState extends State<WindowLayer>
enabled: !offstage, enabled: !offstage,
child: SurfaceVisibility( child: SurfaceVisibility(
shown: !offstage, shown: !offstage,
current: !hiding, // Not while a page, sheet or dialog covers the app: the
// window's own route is always its navigator's current one.
current: !hiding && current,
child: IgnorePointer( child: IgnorePointer(
ignoring: hiding, ignoring: hiding,
child: ExcludeFocus(excluding: hiding, child: child!), child: ExcludeFocus(excluding: hiding, child: child!),
+82
View File
@@ -0,0 +1,82 @@
import 'package:flutter/material.dart';
/// The app's anchored menu: a [MenuAnchor] whose panel is in the root
/// overlay, so it opens above every floating window and is never clipped to
/// one, and which takes the keyboard while open, so Escape closes it and the
/// arrow keys move through it wherever the keyboard was. Closing gives the
/// keyboard back to what had it.
///
/// Use it instead of [MenuAnchor] everywhere: any content can end up in a
/// window, where only the root overlay reaches past the window's edges.
class AppMenuAnchor extends StatefulWidget {
const AppMenuAnchor({
super.key,
required this.menuChildren,
required this.builder,
this.controller,
this.style,
this.alignmentOffset,
this.child,
});
final List<Widget> menuChildren;
final MenuAnchorChildBuilder builder;
final MenuController? controller;
final MenuStyle? style;
final Offset? alignmentOffset;
final Widget? child;
@override
State<AppMenuAnchor> createState() => _AppMenuAnchorState();
}
class _AppMenuAnchorState extends State<AppMenuAnchor> {
final FocusNode _focus = FocusNode(
debugLabel: 'menu anchor',
skipTraversal: true,
);
FocusNode? _previous;
@override
void dispose() {
_focus.dispose();
super.dispose();
}
void _opened() {
final current = FocusManager.instance.primaryFocus;
_previous = identical(current, _focus) ? null : current;
_focus.requestFocus();
}
void _closed() {
final previous = _previous;
_previous = null;
if (!_focus.hasPrimaryFocus) return;
if (previous != null &&
previous.context != null &&
previous.canRequestFocus) {
previous.requestFocus();
} else {
_focus.unfocus();
}
}
@override
Widget build(BuildContext context) => MenuAnchor(
useRootOverlay: true,
controller: widget.controller,
style: widget.style,
alignmentOffset: widget.alignmentOffset,
childFocusNode: _focus,
onOpen: _opened,
onClose: _closed,
menuChildren: widget.menuChildren,
builder: (context, menu, child) => Focus(
focusNode: _focus,
includeSemantics: false,
child: widget.builder(context, menu, child),
),
child: widget.child,
);
}
@@ -1,3 +1,4 @@
import 'app_menu_anchor.dart';
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -98,7 +99,7 @@ class SegmentedMoreButton extends StatelessWidget {
), ),
); );
} }
return MenuAnchor( return AppMenuAnchor(
menuChildren: [ menuChildren: [
for (final entry in entries) for (final entry in entries)
if (entry.choices.isEmpty) if (entry.choices.isEmpty)
+2 -50
View File
@@ -3,8 +3,8 @@ import 'package:flutter/widgets.dart';
/// A layer of floating windows painted in the app's root overlay, above the /// A layer of floating windows painted in the app's root overlay, above the
/// page, while it keeps its place in the tree (its inherited widgets, focus /// page, while it keeps its place in the tree (its inherited widgets, focus
/// and state stay where it is built). Every [FloatingLayer] shares that one /// and state stay where it is built). Every [FloatingLayer] shares that one
/// overlay, so windows from different features (the terminal, a floating /// overlay. Only the terminal's floating window still uses it; the app's
/// chat) stack by use: the layer last pressed, focused or opened is on top. /// other windows are in the shell's window host.
/// ///
/// [builder] returns the windows as [Positioned] children of a [Stack] the /// [builder] returns the windows as [Positioned] children of a [Stack] the
/// size of [bounds]: this widget's own box, or the whole overlay when /// size of [bounds]: this widget's own box, or the whole overlay when
@@ -97,51 +97,3 @@ class _FloatingLayerState extends State<FloatingLayer> {
); );
} }
} }
/// A focus parent for floating windows placed above the app's destinations,
/// so a window built inside one destination keeps the keyboard while another
/// destination shows (a hidden destination excludes its own subtree from
/// focus). Windows attach their focus scope here with [maybeOf].
class FloatingFocusRoot extends StatefulWidget {
const FloatingFocusRoot({super.key, required this.child});
final Widget child;
/// The nearest root's focus node, or null outside one.
static FocusNode? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<_FloatingFocusScope>()?.node;
@override
State<FloatingFocusRoot> createState() => _FloatingFocusRootState();
}
class _FloatingFocusRootState extends State<FloatingFocusRoot> {
final FocusNode _node = FocusNode(
debugLabel: 'floating windows',
canRequestFocus: false,
skipTraversal: true,
);
@override
void dispose() {
_node.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Focus(
focusNode: _node,
includeSemantics: false,
child: _FloatingFocusScope(node: _node, child: widget.child),
);
}
class _FloatingFocusScope extends InheritedWidget {
const _FloatingFocusScope({required this.node, required super.child});
final FocusNode node;
@override
bool updateShouldNotify(_FloatingFocusScope oldWidget) =>
oldWidget.node != node;
}
+66 -120
View File
@@ -1,129 +1,75 @@
# Floating chat pane # Floating chats
On a wide layout chats can leave the split tiling and float in windows over On a wide layout a chat can leave the split tiling and float in a window over
the app, like the floating terminal. Ctrl+Y (Cmd+Y on macOS) shows or hides the app. The windows belong to the shell's window system
all of them together, on every destination. (`notes/floating-windows.md`), not to the Chat destination: they show over
every destination and come back at app start without Chat being opened.
## Behaviour ## Behaviour
- **Float**: a tiled pane's More menu offers `Float (Ctrl+Y)` (`Cmd+Y` on Apple - **Float**: a tiled pane's More menu offers `Float (Alt+Y)` (`Option+Y` on
platforms) when another chat stays in the tiling. The last tiled chat cannot Apple platforms) when another chat stays in the tiling; the last tiled chat
float, because the tiling would be empty. Any number of chats can float; cannot float. Any number of chats can float. A new window opens where that
floating one shows every floating chat. A new window opens at the default chat's window last was, else at the default frame stepped 32 px per chat
frame stepped 32 px down and right per window already floating. window already open.
- **Show / hide**: the chord, a window's X and the menu's `Hide floating chats` - **Window**: drag the title bar to move, the lower right corner to resize,
show or hide all floating windows at once. Each window keeps its own frame, double click the title to maximise. The title bar has Dock, Minimise,
so they come back exactly where they were. Maximise and Close.
- **Window**: you drag it by its title bar and resize it from the lower right - **Dock** puts the chat back into the tiling, right of the active pane. When
corner. The title bar has Dock and Hide buttons. The window keeps its frame the Chat destination is not built it opens the chat there instead.
inside the app when the browser window resizes (`fitChatFloat`). Grow and fade - **Minimise** hides that window; the chord brings it back.
in, and shrink and fade out, use `Motion.standard` through `Motion.of`, so - **Close (X)** closes the window and returns nothing to the tiling. The chat
reduced motion and the animation speed apply. Each window animates on its itself is not closed on the server.
own, so a chat floated while others show grows in alone. - **Chord**: Alt+Y, Ctrl+Y, and Cmd+Y on Apple platforms (`chatFloatShortcut`).
- **Floating chat's menu**: Dock (back into the tiling, right of the active pane, With chat windows open it hides or shows all of them. With none it floats the
which it becomes; the others keep floating), `Hide floating chats (Ctrl+Y)`, active tiled pane, when that pane can float and Chat has the keyboard;
and Close pane (removes it from the workspace; no backend close). If the last otherwise the key is left alone (so Ctrl+Y stays the shell's yank in a
tiled pane closes, the oldest floating chat docks in its place. terminal). On macOS Ctrl+Y in a terminal always goes to the shell.
- **Shortcut**: Ctrl+Y on every platform, and Cmd+Y on macOS and iOS. It is an - **Focus**: a window that shows or comes to the top puts the keyboard in its
early key handler, so it works from a composer or the terminal; Y, Shift+Y and composer; hiding the last window gives it back to what had it.
Alt+Y still type. When no chat floats, Ctrl+Y floats the tiled pane that has - **Popups**: sheets, dialogs, menus and tooltips opened from a floating chat
the keyboard. When no pane has the keyboard, or that pane cannot float, the are above every window. Files opens as a page inside the window, and a file
chord is left alone. So in the terminal Ctrl+Y stays the shell's yank until a opened from it stays in the window. Because the window's own title bar names
chat floats. After that, on Windows, Linux and web, Ctrl+Y toggles even from the chat, the More menu has `Chat details`.
the terminal (yank is unavailable there, as with Ctrl+T). On macOS, Ctrl+Y in - **Layout inside a window**: the chat is laid out for the window's size, so a
a `TypingSurface` (terminal) always goes to the shell, and Cmd+Y toggles. narrow window gets the compact action bar.
- **Focus**: showing the chat focuses its composer. Hiding it gives the keyboard - **Narrow layouts**: no Float, the chord passes through, and chat windows are
back to whatever had it before (as `TerminalFocus` does), otherwise the hidden (kept, with their state) until the app is wide again.
keyboard is unfocused.
- **Where it shows**: on a wide layout, over every destination (Runs,
Pipelines, Settings...), like the floating terminal. The windows move,
resize, type, hide and dock there as on Chat. On narrow or phone layouts the
menu item is absent and the chord passes through; floating chats stay
floating, unpainted, with their state, and reappear when the window is wide
again.
- **Other destinations (how)**: the shell hides a destination with
`FadeThroughStack` (muted tickers, no input, no focus). The windows already
paint and hit-test in the root overlay; the host also re-enables tickers
around each window (`TickerMode`) and parents each floating pane's
`FocusScope` on the shell's `FloatingFocusRoot`
(`ui/floating/floating_layer.dart`, above the destination stack), so a
hidden destination's `ExcludeFocus` does not take its keyboard. Before this,
leaving Chat started the hide animation on a muted ticker: the window stayed
painted but ignored input, so it could not be moved or closed.
- **Persistence**: `pipelines.next.chatFloat.v1` is stored device-locally and
scoped like the workspace layout. Record version 2 holds the floating panes
(id and session, oldest first, at most 12), whether they are shown, and a
frame per pane id. A docked pane keeps its frame, so floating it again
returns it to the same place; a closed pane's frame is dropped. Version 1
records (one pane, one frame) still load. It is restored after the workspace
layout. A saved float whose session is already open is dropped.
## Design ## How
- `ChatWorkspaceController` keeps the floating panes outside the tree - `ChatRuntime` (`features/chat/chat_runtime.dart`), one per server scope, kept
(`chat_workspace_float.dart`, a `part` with the `ChatWorkspaceFloat` by `PipelinesApp`: the session list controller, opened rows, accepted models,
extension: `floatingPanes`, `isFloating`, `dock(paneId)`, `restoreFloats`). transcript positions and caches, composer focus requests.
`panes` and `paneCount` stay tiled-only. A pane keeps its id through float, - `buildChatPaneContent` (`chat_pane_content.dart`) builds a conversation with
hide and dock. Frames live in `ChatFloatFrames` (by pane id). its scopes, keyed by `ChatRuntime.viewKey`. The tiling and the chat window
- `ChatWorkspace` gives each pane's content a `GlobalKey`. A floating chat is kind both use it, so Float and Dock move the same live view (transcript,
that same keyed subtree, built by `ChatFloatHost` inside the workspace, so the scroll, draft, running turn) between them in one frame.
`ChatThreadView` State, draft, scroll and running turn move with it and are - `ChatWindows` (`features/chat/windows/`): the `chat` `WindowKind`, the chord,
not rebuilt. Its inherited context and focus tree stay in the workspace. Dock, and what `/new` and `/close` do to a chat in a window. It reads the
- `FloatingLayer` (`lib/ui/floating/`) paints a layer in the root overlay session list for its windows' rows when the Chat destination is not built.
through `OverlayPortal`. The chat window covers the whole app. The terminal's - The workspace controller keeps no floating chats. `detach` takes a pane out,
floating window now uses the same layer, so the two share one z-order: the `dock` puts a chat back, and `showOutside` lets it show a chat's window
last one pressed, focused or opened is on top. Without an overlay (bare instead of opening that chat a second time. A chat is drawn once: if the
widget tests) the layer paints in place. tiling holds a chat that also has a window, the window closes.
- New files: `chat_float_{host,window,binding,store,shortcut}.dart`, - **Saved state**: chat windows are entries of `pipelines.windows.v1`, carrying
`chat_workspace_float.dart`, `chat_screen_float.dart` and their server key. The older `pipelines.next.chatFloat.v1` record (versions 1
`ui/floating/floating_layer.dart`. Existing files changed: workspace and 2) is read once at start and turned into windows.
controller hooks (open, split, close, replace, restore), the
`ChatWorkspace.floatFrame` parameter and keyed content, the pane controls and
`/close` and `/new` handling in `screen.dart`, the persistence wiring in
`chat_screen_workspace.dart`, and `terminal_stage.dart`.
## Not done
- The sidebar's "visible" highlight does not count floating chats.
- Floating windows need the Chat destination to have been built; the shell
builds every destination up front, so this holds today.
- Cmd+Y in a browser on macOS may be taken by the browser (History) before the
app sees it. Ctrl+Y works there.
## Checks ## Checks
### Multiple floats, every destination (2026-11-10) - `test/features/chat/chat_floating_pane_test.dart` (the Chat screen with the
window host), `test/features/chat/windows/chat_windows_test.dart`,
- `tool/memwatch/full.sh 'test/features/chat/chat_floating_pane_test.dart test/features/chat/workspace test/ui/floating'`: `test/features/chat/workspace/chat_workspace_float_test.dart`,
93 passed, 0 failed. `tool/analyze.sh lib test/features/chat`: clean. `chat_float_shortcut_test.dart`, `test/features/chat/chat_runtime_test.dart`.
- New tests: several floats toggled together by the chord and restored to - Real app (capture kit, 2026-11-10/11, 1280x800 and 1920x1080, light and
their frames, docking one keeps the other (`chat_floating_pane_test.dart`); dark), from a floating chat over Chat and over Runs: chat details, model
a float over another destination (a real `FadeThroughStack` page switch) dialog, mode sheet, thinking menu, More menu, title-bar and control tooltips,
is hit-testable, drags, takes focus and typing, and hides by chord and its typing; Files page with its sort menu, row menu and tooltip, a file opened
X; controller, record v1/v2 and per-pane frame tests inside the window; reload restoring the window over Runs without visiting
(`chat_workspace_float_test.dart`). Chat; hide and show by chord, maximise, minimise, Dock; a live turn
- Fixed on the way: a drag read the frame from the last build, so several animating over Runs; the Turn changes page, a diff opened from it and a shell
pointer events in one frame lost movement; and a never-moved window's command's full-screen page, each inside the window; a question card.
cascaded frame shifted when another window docked (frames are now placed - Not captured: paste of text or an image, a question-card dropdown (the
when a chat floats). fixture's question has radio options), the image viewer, and the
text-selection menu (the kit has no right-click).
### Single float (earlier)
- `tool/analyze.sh lib test/features/chat test/ui test/features/terminal`: clean
after the merge with main (pane moves, a410b9e5). In the merge, Float sits in
the pane menu right after the Move items.
- `tool/memwatch/full.sh 'test/features/chat test/features/terminal test/shell test/ui/floating'`:
1395 passed, 0 failed; peak 1936 MB; 592 s. New tests are
`test/features/chat/workspace/chat_workspace_float_test.dart` (controller,
record and binding), `chat_float_shortcut_test.dart` (chord, typing Y,
terminal and macOS, narrow), `test/features/chat/chat_floating_pane_test.dart`
(menu Float and Dock keep the `ChatThreadView` State and draft, reload,
narrow) and `test/ui/floating/floating_layer_test.dart` (z-order and click
pass-through).
- Real-Chrome captures used the fixture (`chats=3&rich=1&colors=1`) at
1280x800 and are in `/tmp/float-cap/c/`: the pane menu with Float, the
floating chat with a typed draft, the chat hidden by Control+y with focus back
in the tiled composer, two films of the chord, and the floating chat over the
terminal panel. Headless Chrome reports macOS, so the label reads `Cmd+Y` and
Control+y also toggles. Not captured: the chat floating over a floating
(rather than panel) terminal.
+10 -6
View File
@@ -1,15 +1,15 @@
# Floating windows (window system core) # Floating windows (window system core)
Plan: `docs/plans/floating-windows.md`. Phase 1 adds the shell-level window Plan: `docs/plans/floating-windows.md`. The shell-level window system hosts
system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3). floating chats (`notes/chat-floating-pane.md`); the terminal moves in Phase 3.
## Pieces (`lib/shell/windows/`) ## Pieces (`lib/shell/windows/`)
- `WindowManager` (`AppWindows.manager`): the open windows bottom to top, frames, - `WindowManager` (one per `PipelinesApp`): the open windows bottom to top, frames,
minimised/maximised, group show/hide, cycling. Saved through `WindowStore` minimised/maximised, group show/hide, cycling. Saved through `WindowStore`
(`pipelines.windows.v1`), one record for every server; server-scoped windows (`pipelines.windows.v1`), one record for every server; server-scoped windows
carry their server key and only the current server's are listed. carry their server key and only the current server's are listed.
- `WindowKind` (`AppWindows.kinds`): what a kind of window builds, its title, - `WindowKind` (registered on the manager's `kinds`): what a kind of window builds, its title,
icon, title-bar actions, minimum size and saved data. icon, title-bar actions, minimum size and saved data.
- `WindowHost`: the windows as plain children of the terminal stage's stack, in - `WindowHost`: the windows as plain children of the terminal stage's stack, in
the shell page (not an overlay above it), outside every destination. the shell page (not an overlay above it), outside every destination.
@@ -31,8 +31,12 @@ system; no feature uses it yet (chats move in Phase 2, the terminal in Phase 3).
and never clipped to one. and never clipped to one.
- The window's navigator covers the whole host so popups anchored to a button - The window's navigator covers the whole host so popups anchored to a button
measure in app coordinates and tooltips paint outside the window; only the measure in app coordinates and tooltips paint outside the window; only the
content area takes input. So a `MenuAnchor` in window content needs content area takes input. So menus are `AppMenuAnchor`
`useRootOverlay: true` (its panel may extend past the window). (`ui/adaptive/app_menu_anchor.dart`), whose panel is in the root overlay; a
test rejects a bare `MenuAnchor`.
- A window takes the keyboard at the press, not after it, and never from a
popup that covers the app; its content is not the current surface
(`SurfaceVisibility`) while one does.
- Known limit: a tooltip of a window that is not on top can be covered by a - Known limit: a tooltip of a window that is not on top can be covered by a
window above it where they overlap (tooltips paint in their own window's window above it where they overlap (tooltips paint in their own window's
overlay). Pressing a window raises it, so menus are not affected. overlay). Pressing a window raises it, so menus are not affected.
@@ -4,12 +4,18 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/server_scope.dart'; import 'package:pipelines_app/core/servers/server_scope.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/screen.dart'; import 'package:pipelines_app/features/chat/screen.dart';
import 'package:pipelines_app/features/chat/windows/chat_windows.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace_store.dart';
import 'package:pipelines_app/ui/floating/floating_layer.dart'; import 'package:pipelines_app/shell/windows/window_frame.dart';
import 'package:pipelines_app/shell/windows/window_host.dart';
import 'package:pipelines_app/shell/windows/window_kind.dart';
import 'package:pipelines_app/shell/windows/window_manager.dart';
import 'package:pipelines_app/shell/windows/window_store.dart';
import 'package:pipelines_app/ui/motion/fade_through_stack.dart'; import 'package:pipelines_app/ui/motion/fade_through_stack.dart';
import 'conversation/chat_thread_fixtures.dart'; import 'conversation/chat_thread_fixtures.dart';
@@ -29,6 +35,17 @@ class _Gateway extends FakeChatGateway {
} }
} }
class _Store implements WindowStore {
String? value;
@override
Future<String?> read() async => value;
@override
Future<bool> write(String record) async {
value = record;
return true;
}
}
Finder _thread(String id) => find.byWidgetPredicate( Finder _thread(String id) => find.byWidgetPredicate(
(widget) => widget is ChatThreadView && widget.sessionId == id, (widget) => widget is ChatThreadView && widget.sessionId == id,
skipOffstage: false, skipOffstage: false,
@@ -38,45 +55,102 @@ Finder _input(String id) => find.descendant(
matching: find.byType(EditableText, skipOffstage: false), matching: find.byType(EditableText, skipOffstage: false),
skipOffstage: false, skipOffstage: false,
); );
ChatWorkspaceController _workspace(WidgetTester tester) => ChatWorkspaceController _workspace(WidgetTester tester) => tester
tester.widget<ChatWorkspace>(find.byType(ChatWorkspace)).controller; .widget<ChatWorkspace>(find.byType(ChatWorkspace, skipOffstage: false))
.controller;
Future<_Gateway> _mount( /// The window whose title is [title].
WidgetTester tester, { Finder _window(String title) =>
Size size = const Size(1800, 1000), find.ancestor(of: find.text(title), matching: find.byType(WindowFrame));
ValueNotifier<int>? destination,
}) async { /// That window's title bar, where it shows and takes input.
tester.view.physicalSize = size; Finder _shown(String title) => find
tester.view.devicePixelRatio = 1; .descendant(
addTearDown(tester.view.reset); of: _window(title),
matching: find.byKey(const ValueKey('window-title')),
)
.hitTestable();
/// The app in miniature: the Chat destination beside another one, and the
/// window host above both, with app-lifetime chat state.
class _App {
_App(this.store);
final _Store store;
final gateway = _Gateway()..history = (_) async => chatPage([]); final gateway = _Gateway()..history = (_) async => chatPage([]);
bindServerIdentity(gateway, 'server-a'); final destination = ValueNotifier(0);
addTearDown(gateway.close); final chatBuilt = ValueNotifier(true);
final chat = ChatScreen(gateway: gateway, persistWorkspace: true); final opened = <String>[];
await tester.pumpWidget( late final ChatRuntime runtime;
MaterialApp( late final WindowManager manager;
home: Scaffold( late final ChatWindows windows;
body: destination == null
? chat Future<void> start(
// As the shell keeps destinations: the hidden one is muted, WidgetTester tester, {
// unfocusable and takes no input. Size size = const Size(1800, 1000),
: FloatingFocusRoot( }) async {
child: ValueListenableBuilder( tester.view.physicalSize = size;
valueListenable: destination, tester.view.devicePixelRatio = 1;
builder: (context, index, _) => FadeThroughStack( addTearDown(tester.view.reset);
index: index, bindServerIdentity(gateway, 'server-a');
children: [ runtime = ChatRuntime(gateway: gateway, serverKey: 'server-a');
chat, manager = WindowManager(
const Center(child: Text('Runs page')), kinds: WindowKinds(),
], store: store,
), server: 'server-a',
);
windows = ChatWindows(
manager: manager,
runtime: runtime,
openInChat: opened.add,
)..start();
await manager.restore();
await windows.migrate(
const SharedPreferencesChatFloatStore(serverScope: 'server-a'),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
ListenableBuilder(
listenable: Listenable.merge([destination, chatBuilt]),
builder: (context, _) => FadeThroughStack(
index: destination.value,
children: [
if (chatBuilt.value)
ChatScreen(
gateway: gateway,
persistWorkspace: true,
runtime: runtime,
windows: windows,
)
else
const Center(child: Text('Not connected')),
const Center(child: Text('Runs page')),
],
), ),
), ),
Positioned.fill(child: WindowHost(manager: manager)),
],
),
),
), ),
), );
); await tester.pumpAndSettle();
await tester.pumpAndSettle(); }
return gateway;
Future<void> stop(WidgetTester tester) async {
await tester.pumpWidget(const SizedBox.shrink());
windows.dispose();
runtime.dispose();
manager.dispose();
destination.dispose();
chatBuilt.dispose();
gateway.close();
}
List<String> get floating => [for (final w in windows.windows) w.contentId];
} }
/// Opens [session]'s pane menu (wherever it is) and chooses [label]. /// Opens [session]'s pane menu (wherever it is) and chooses [label].
@@ -106,26 +180,34 @@ Future<void> _saved(String a, String b, [String? c]) async {
}); });
} }
Future<void> _chord(WidgetTester tester) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
await tester.pumpAndSettle();
}
void main() { void main() {
testWidgets('Float and Dock move the live chat with its draft', ( testWidgets('Float and Dock move the live chat with its draft', (
tester, tester,
) async { ) async {
await _saved('a', 'b'); await _saved('a', 'b');
final gateway = await _mount(tester); final app = _App(_Store());
await app.start(tester);
final b = tester.state(_thread('b')); final b = tester.state(_thread('b'));
await tester.enterText(_input('b'), 'Draft B'); await tester.enterText(_input('b'), 'Draft B');
await _menu(tester, 'b', 'Float (Ctrl+Y)'); await _menu(tester, 'b', 'Float (Alt+Y)');
final controller = _workspace(tester); final controller = _workspace(tester);
expect(controller.floatingPanes.single.sessionId, 'b'); expect(app.floating, ['b']);
expect(controller.panes.map((p) => p.sessionId), ['a']); expect(controller.panes.map((p) => p.sessionId), ['a']);
expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget);
expect(tester.state(_thread('b')), same(b)); expect(tester.state(_thread('b')), same(b));
expect(tester.widget<EditableText>(_input('b')).controller.text, 'Draft B'); expect(tester.widget<EditableText>(_input('b')).controller.text, 'Draft B');
// The window floats over the app, not inside a pane. // A window over the app, titled by its chat, not a pane.
final window = tester.getRect( expect(tester.getSize(_window('Chat b')).width, lessThan(1800 / 2));
find.byKey(const ValueKey('chat-float-title')), expect(
find.descendant(of: _window('Chat b'), matching: find.byTooltip('Dock')),
findsOneWidget,
); );
expect(window.width, lessThan(1800 / 2));
// The lone tiled pane cannot float: the tiling would be empty. // The lone tiled pane cannot float: the tiling would be empty.
await tester.tap( await tester.tap(
@@ -137,157 +219,164 @@ void main() {
.hitTestable(), .hitTestable(),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Float (Ctrl+Y)'), findsNothing); expect(find.textContaining('Float'), findsNothing);
await tester.tapAt(const Offset(5, 995)); await tester.tapAt(const Offset(5, 995));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await _menu(tester, 'b', 'Dock'); await tester.tap(find.byTooltip('Dock'));
expect(controller.floatingPanes, isEmpty); await tester.pumpAndSettle();
expect(app.floating, isEmpty);
expect(controller.panes.map((p) => p.sessionId), ['a', 'b']); expect(controller.panes.map((p) => p.sessionId), ['a', 'b']);
expect(tester.state(_thread('b')), same(b)); expect(tester.state(_thread('b')), same(b));
expect(tester.widget<EditableText>(_input('b')).controller.text, 'Draft B'); expect(tester.widget<EditableText>(_input('b')).controller.text, 'Draft B');
expect( expect(
gateway.calls.where( app.gateway.calls.where(
(call) => ['chat_close', 'chat_interrupt'].contains(call.type), (call) => ['chat_close', 'chat_interrupt'].contains(call.type),
), ),
isEmpty, isEmpty,
); );
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink()); await app.stop(tester);
}); });
testWidgets('the floating chat and its frame survive a reload', ( testWidgets('X closes the window and returns nothing to the tiling', (
tester, tester,
) async { ) async {
await _saved('a', 'b'); await _saved('a', 'b');
await _mount(tester); final app = _App(_Store());
await _menu(tester, 'b', 'Float (Ctrl+Y)'); await app.start(tester);
await _menu(tester, 'b', 'Float (Alt+Y)');
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(app.floating, isEmpty);
expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']);
expect(_thread('b'), findsNothing);
expect(app.gateway.calls.where((c) => c.type == 'chat_close'), isEmpty);
await app.stop(tester);
});
testWidgets('popups from a floating chat open above its window', (
tester,
) async {
await _saved('a', 'b');
final app = _App(_Store());
await app.start(tester);
await _menu(tester, 'b', 'Float (Alt+Y)');
// The More actions menu, opened from inside the window.
await tester.tap(
find
.descendant(
of: _thread('b'),
matching: find.byTooltip('More actions'),
)
.hitTestable(),
);
await tester.pumpAndSettle();
expect(find.text('Chat details').hitTestable(), findsOneWidget);
// Chat details, the sheet that used to open behind the window.
await tester.tap(find.text('Chat details'));
await tester.pumpAndSettle();
final sheet = find.byType(BottomSheet);
expect(sheet.hitTestable(), findsOneWidget);
// On the root navigator: wider than the window, and over it.
expect(
tester.getSize(sheet).width,
greaterThan(tester.getSize(_window('Chat b')).width),
);
expect(_shown('Chat b'), findsNothing);
expect(tester.takeException(), isNull);
await app.stop(tester);
});
testWidgets('windows and their frames survive a reload, without the Chat '
'destination being built', (tester) async {
await _saved('a', 'b');
final store = _Store();
var app = _App(store);
await app.start(tester);
await _menu(tester, 'b', 'Float (Alt+Y)');
await tester.drag( await tester.drag(
find.byKey(const ValueKey('chat-float-title')), find.descendant(
of: _window('Chat b'),
matching: find.byKey(const ValueKey('window-title')),
),
const Offset(200, 40), const Offset(200, 40),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await _menu(tester, 'b', 'Hide floating chats (Ctrl+Y)'); await tester.tap(find.byTooltip('Minimise'));
expect(find.byKey(const ValueKey('chat-float-title')), findsNothing);
await tester.pump(const Duration(seconds: 1));
final preferences = await SharedPreferences.getInstance();
final record = ChatFloatRecord.decode(
preferences.getString(
scopedServerKey(chatFloatPreferenceKey, 'server-a'),
)!,
)!;
final floated = record.panes.single;
expect(floated.sessionId, 'b');
expect(record.shown, isFalse);
expect(record.frames[floated.id]?.left, chatFloatDefaultRect.left + 200);
await tester.pumpWidget(const SizedBox.shrink());
await _mount(tester);
final controller = _workspace(tester);
expect(controller.floatingPanes.single.sessionId, 'b');
expect(controller.floatShown, isFalse);
expect(controller.panes.map((p) => p.sessionId), ['a']);
controller.setFloatShown(true);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect( expect(_shown('Chat b'), findsNothing);
tester.getTopLeft(find.byKey(const ValueKey('chat-float-title'))).dx, await app.stop(tester);
greaterThanOrEqualTo(chatFloatDefaultRect.left + 200),
); app = _App(store)..chatBuilt.value = false;
await tester.pumpWidget(const SizedBox.shrink()); await app.start(tester);
expect(find.text('Not connected'), findsOneWidget);
final entry = app.windows.windows.single;
expect(entry.contentId, 'b');
expect(entry.minimized, isTrue);
expect(entry.frame.left, chatFloatDefaultRect.left + 200);
await _chord(tester);
expect(_shown('Chat b'), findsOneWidget);
expect(tester.getTopLeft(_window('Chat b')).dx, entry.frame.left);
expect(_thread('b').hitTestable(), findsOneWidget);
// Dock with no tiling opens the chat in the Chat destination.
await tester.tap(find.byTooltip('Dock'));
await tester.pumpAndSettle();
expect(app.opened, ['b']);
expect(app.floating, isEmpty);
await app.stop(tester);
}); });
Future<void> chord(WidgetTester tester) async {
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pumpAndSettle();
}
final titles = find.byKey(const ValueKey('chat-float-title'));
testWidgets('several chats float; the chord hides and shows them all ' testWidgets('several chats float; the chord hides and shows them all '
'where they were', (tester) async { 'where they were', (tester) async {
await _saved('a', 'b', 'c'); await _saved('a', 'b', 'c');
await _mount(tester); final app = _App(_Store());
await _menu(tester, 'b', 'Float (Ctrl+Y)'); await app.start(tester);
await _menu(tester, 'c', 'Float (Ctrl+Y)'); await _menu(tester, 'b', 'Float (Alt+Y)');
await _menu(tester, 'c', 'Float (Alt+Y)');
final controller = _workspace(tester); final controller = _workspace(tester);
expect(controller.floatingPanes.map((p) => p.sessionId), ['b', 'c']); expect(app.floating, ['b', 'c']);
expect(controller.panes.map((p) => p.sessionId), ['a']); expect(controller.panes.map((p) => p.sessionId), ['a']);
expect(titles, findsNWidgets(2));
// The second window opens stepped from the first, so both show. // The second window opens stepped from the first, so both show.
final first = tester.getTopLeft(titles.first); final first = tester.getTopLeft(_window('Chat b'));
final second = tester.getTopLeft(titles.last); final second = tester.getTopLeft(_window('Chat c'));
expect(second.dx, greaterThan(first.dx)); expect(second.dx, greaterThan(first.dx));
await tester.drag(titles.first, const Offset(300, 100));
await tester.pumpAndSettle();
final moved = tester.getTopLeft(titles.first);
expect(moved.dx, greaterThan(first.dx + 200));
await chord(tester); await _chord(tester);
expect(controller.floatShown, isFalse); expect(
expect(titles, findsNothing); find.byKey(const ValueKey('window-title')).hitTestable(),
await chord(tester); findsNothing,
expect(controller.floatShown, isTrue); );
expect(titles, findsNWidgets(2)); await _chord(tester);
expect(tester.getTopLeft(titles.first), moved); expect(tester.getTopLeft(_window('Chat b')), first);
expect(tester.getTopLeft(titles.last), second); expect(tester.getTopLeft(_window('Chat c')), second);
// Docking one leaves the other floating. // Docking one leaves the other floating.
await _menu(tester, 'b', 'Dock'); await tester.tap(
expect(controller.floatingPanes.map((p) => p.sessionId), ['c']); find.descendant(of: _window('Chat b'), matching: find.byTooltip('Dock')),
expect(titles, findsOneWidget); );
await tester.pumpAndSettle();
await tester.pump(const Duration(seconds: 1)); expect(app.floating, ['c']);
final preferences = await SharedPreferences.getInstance(); expect(controller.panes.map((p) => p.sessionId), ['a', 'b']);
final record = ChatFloatRecord.decode(
preferences.getString(
scopedServerKey(chatFloatPreferenceKey, 'server-a'),
)!,
)!;
expect(record.panes.map((p) => p.sessionId), ['c']);
// The docked chat keeps its frame for its next float.
expect(record.frames, hasLength(2));
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink()); await app.stop(tester);
}); });
testWidgets('a floating chat moves, types, hides and shows over another ' testWidgets('a floating chat types, runs its tickers, hides and shows over '
'destination', (tester) async { 'another destination', (tester) async {
await _saved('a', 'b'); await _saved('a', 'b');
final destination = ValueNotifier(0); final app = _App(_Store());
addTearDown(destination.dispose); await app.start(tester);
await _mount(tester, destination: destination); await _menu(tester, 'b', 'Float (Alt+Y)');
await _menu(tester, 'b', 'Float (Ctrl+Y)'); app.destination.value = 1;
final controller = _workspace(tester);
destination.value = 1;
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('Runs page'), findsOneWidget); expect(find.text('Runs page'), findsOneWidget);
// The chat page is offstage, so finders look past it; the window itself expect(_shown('Chat b'), findsOneWidget);
// paints and takes input in the root overlay. // Not muted by the hidden Chat destination.
final title = find.byKey( expect(TickerMode.valuesOf(tester.element(_thread('b'))).enabled, isTrue);
const ValueKey('chat-float-title'),
skipOffstage: false,
);
bool hits(Finder finder) {
final box = tester.renderObject(finder);
return tester
.hitTestOnBinding(tester.getCenter(finder))
.path
.any((entry) => identical(entry.target, box));
}
expect(hits(title), isTrue);
final before = tester.getTopLeft(title);
await tester.drag(title, const Offset(150, 60));
await tester.pumpAndSettle();
expect(tester.getTopLeft(title).dx, greaterThan(before.dx + 100));
expect(tester.getTopLeft(title).dy, greaterThan(before.dy + 20));
// The composer takes the keyboard there. // The composer takes the keyboard there.
final input = _input('b'); final input = _input('b');
expect(hits(input), isTrue);
await tester.tapAt(tester.getCenter(input)); await tester.tapAt(tester.getCenter(input));
await tester.pump(); await tester.pump();
final field = tester.widget<EditableText>(input); final field = tester.widget<EditableText>(input);
@@ -296,35 +385,65 @@ void main() {
await tester.pump(); await tester.pump();
expect(field.controller.text, 'From runs'); expect(field.controller.text, 'From runs');
// The chord and the window's own hide button both work there. await _chord(tester);
// The window itself animates away and back, not only the state. expect(_shown('Chat b'), findsNothing);
await chord(tester); await _chord(tester);
expect(controller.floatShown, isFalse); expect(_shown('Chat b'), findsOneWidget);
expect(hits(title), isFalse); // Shown again by the chord, the composer has the keyboard at once.
await chord(tester); expect(tester.widget<EditableText>(_input('b')).focusNode.hasFocus, isTrue);
expect(controller.floatShown, isTrue);
expect(hits(title), isTrue);
final hide = find.byTooltip(
'Hide floating chats (Ctrl+Y)',
skipOffstage: false,
);
expect(hits(hide), isTrue);
await tester.tapAt(tester.getCenter(hide));
await tester.pumpAndSettle();
expect(controller.floatShown, isFalse);
expect(hits(title), isFalse);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink()); await app.stop(tester);
}); });
testWidgets('narrow layouts offer no Float', (tester) async { testWidgets('floating chats saved by an older build come back as windows', (
tester,
) async {
await _saved('a', 'c');
final preferences = await SharedPreferences.getInstance();
await preferences.setString(
scopedServerKey(chatFloatPreferenceKey, 'server-a'),
const ChatFloatRecord(
panes: [ChatWorkspacePane('chat-pane-9', 'b')],
shown: true,
frames: {'chat-pane-9': Rect.fromLTWH(400, 300, 500, 420)},
).encode(),
);
final app = _App(_Store());
await app.start(tester);
expect(app.floating, ['b']);
expect(tester.getTopLeft(_window('Chat b')), const Offset(400, 300));
expect(_workspace(tester).panes.map((p) => p.sessionId), ['a', 'c']);
await app.stop(tester);
});
testWidgets('a chat is drawn once: opening a floating chat from the list '
'shows its window', (tester) async {
await _saved('a', 'b'); await _saved('a', 'b');
await _mount(tester, size: const Size(430, 900)); final app = _App(_Store());
await app.start(tester);
await _menu(tester, 'b', 'Float (Alt+Y)');
app.manager.setGroupShown(chatWindowKind, false);
await tester.pumpAndSettle();
_workspace(tester).open('b');
await tester.pumpAndSettle();
expect(_shown('Chat b'), findsOneWidget);
expect(_workspace(tester).panes.map((p) => p.sessionId), ['a']);
expect(_thread('b'), findsOneWidget);
expect(tester.takeException(), isNull);
await app.stop(tester);
});
testWidgets('narrow layouts offer no Float and show no window', (
tester,
) async {
await _saved('a', 'b');
final app = _App(_Store());
await app.start(tester, size: const Size(430, 900));
final finder = find.byTooltip('More actions').hitTestable(); final finder = find.byTooltip('More actions').hitTestable();
await tester.tap(finder.first); await tester.tap(finder.first);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.textContaining('Float'), findsNothing); expect(find.textContaining('Float'), findsNothing);
expect(find.text('Open chats (2)'), findsOneWidget); expect(find.text('Open chats (2)'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink()); await app.stop(tester);
}); });
} }
@@ -82,7 +82,10 @@ Future<void> _openMenu(WidgetTester tester, String session) async {
MenuItemButton _item(WidgetTester tester, String label) => MenuItemButton _item(WidgetTester tester, String label) =>
tester.widget<MenuItemButton>( tester.widget<MenuItemButton>(
find.ancestor(of: find.text(label), matching: find.byType(MenuItemButton)), find.ancestor(
of: find.text(label),
matching: find.byType(MenuItemButton),
),
); );
ChatWorkspaceController _controller(WidgetTester tester) => ChatWorkspaceController _controller(WidgetTester tester) =>
@@ -205,7 +208,9 @@ void main() {
final gateway = _Gateway()..history = (_) async => chatPage([]); final gateway = _Gateway()..history = (_) async => chatPage([]);
addTearDown(gateway.close); addTearDown(gateway.close);
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp(home: Scaffold(body: ChatScreen(gateway: gateway))), MaterialApp(
home: Scaffold(body: ChatScreen(gateway: gateway)),
),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await tester.tap(find.text('Chat a').first); await tester.tap(find.text('Chat a').first);
@@ -0,0 +1,84 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
class _Gateway implements ApiGateway {
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async => {};
}
void main() {
late ChatRuntime runtime;
late int notified;
setUp(() {
runtime = ChatRuntime(gateway: _Gateway());
notified = 0;
runtime.addListener(() => notified++);
});
tearDown(() => runtime.dispose());
test('adopts listed rows for opened, selected and retained chats only', () {
runtime.opened['a'] = {'id': 'a', 'title': 'Old', 'running': true};
runtime.adoptRows(
[
{'id': 'a', 'title': 'New', 'running': false},
{'id': 'b', 'title': 'B'},
{'id': 'c', 'title': 'C'},
{'id': 'd', 'title': 'D'},
],
selected: 'b',
retained: {'c'},
);
// The conversation keeps its own running flag.
expect(runtime.opened['a'], {'id': 'a', 'title': 'New', 'running': true});
expect(runtime.opened.keys, ['a', 'b', 'c']);
expect(notified, 1);
// A chat that is only listed still resolves its row.
expect(runtime.rowFor('d')?['title'], 'D');
expect(runtime.titleFor('zz'), 'zz');
});
test('an unchanged listing never reverts an accepted mode', () {
final rows = [
{'id': 'a', 'mode': 'ask'},
];
runtime.adoptRows(rows, selected: 'a', retained: const {});
expect(runtime.modeChanged('a', 'auto', 'Auto'), isTrue);
runtime.adoptRows(rows, selected: 'a', retained: const {});
expect(runtime.opened['a']?['mode'], 'auto');
expect(notified, 2);
expect(runtime.modeChanged('missing', 'auto', 'Auto'), isFalse);
});
test('an accepted model wins over the row and follows /new', () {
runtime.opened['a'] = {'id': 'a', 'model': 'old'};
runtime.modelChanged('a', (
provider: 'p',
model: 'new',
selection: 'p/new',
));
expect(runtime.rowFor('a')?['model'], 'new');
runtime.movedToSession('a', {'id': 'b', 'running': true}, 'Started');
expect(runtime.rowFor('b'), {
'id': 'b',
'model': 'new',
'model_provider': 'p',
'model_selection': 'p/new',
});
expect(runtime.startNotice, (id: 'b', notice: 'Started'));
});
test('rename updates the opened row; a new gateway drops transcripts', () {
runtime.opened['a'] = {'id': 'a', 'title': 'Old'};
runtime.renamed('a', 'New');
expect(runtime.titleFor('a'), 'New');
expect(notified, 1);
final other = _Gateway();
runtime.gateway = other;
expect(runtime.gateway, same(other));
expect(runtime.gatewayFor('a'), same(other));
expect(runtime.serverIdFor('a'), '');
});
}
@@ -244,9 +244,6 @@ void main() {
isSameColorAs(tint.foreground), isSameColorAs(tint.foreground),
); );
// Outside the bar the theme's tint is untouched. // Outside the bar the theme's tint is untouched.
expect( expect(CupertinoTheme.of(context).primaryColor, isNot(tint.foreground));
CupertinoTheme.of(context).primaryColor,
isNot(tint.foreground),
);
}); });
} }
@@ -201,9 +201,7 @@ void main() {
await done(tester); await done(tester);
}); });
testWidgets('a focused floating composer takes pasted files', ( testWidgets('a focused floating composer takes pasted files', (tester) async {
tester,
) async {
final accepts = <String, ChatPasteCanAccept>{}; final accepts = <String, ChatPasteCanAccept>{};
ChatClipboardPaste source(String id) => ChatClipboardPaste( ChatClipboardPaste source(String id) => ChatClipboardPaste(
subscribe: (onFiles, canAccept, onError, onText, canAcceptText) { subscribe: (onFiles, canAccept, onError, onText, canAcceptText) {
@@ -271,19 +271,20 @@ void main() {
expect(mounted.gateway.listings, 2); expect(mounted.gateway.listings, 2);
}); });
testWidgets('A refused move is shown in the server\'s words until dismissed', ( testWidgets(
tester, 'A refused move is shown in the server\'s words until dismissed',
) async { (tester) async {
final mounted = await pump(tester); final mounted = await pump(tester);
const refusal = '$shown/docs/notes.txt already exists'; const refusal = '$shown/docs/notes.txt already exists';
mounted.gateway.refusals['move_path'] = refusal; mounted.gateway.refusals['move_path'] = refusal;
await dragOnto(tester, 'notes.txt', 'docs'); await dragOnto(tester, 'notes.txt', 'docs');
expect(find.text(refusal), findsOneWidget); expect(find.text(refusal), findsOneWidget);
expect(mounted.gateway.listings, 2, reason: 'reloaded all the same'); expect(mounted.gateway.listings, 2, reason: 'reloaded all the same');
await tester.tap(find.text('Dismiss')); await tester.tap(find.text('Dismiss'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text(refusal), findsNothing); expect(find.text(refusal), findsNothing);
}); },
);
test('canDropEntryOn refuses files, itself and its own subtree', () { test('canDropEntryOn refuses files, itself and its own subtree', () {
const docs = DirectoryEntry( const docs = DirectoryEntry(
@@ -39,11 +39,10 @@ void main() {
}); });
test('only visible assistant reply text is unread', () { test('only visible assistant reply text is unread', () {
bool attention(Map<String, Object?> event) => bool attention(Map<String, Object?> event) => chatSessionFrameEffect({
chatSessionFrameEffect({ 'type': 'chat_event',
'type': 'chat_event', 'chat_event': {'session_id': 's', ...event},
'chat_event': {'session_id': 's', ...event}, })!.attention;
})!.attention;
for (final status in ['running', 'completed', 'error']) { for (final status in ['running', 'completed', 'error']) {
expect( expect(
attention({ attention({
@@ -67,11 +66,7 @@ void main() {
expect(attention({'kind': 'text', 'delta': ' \n'}), isFalse); expect(attention({'kind': 'text', 'delta': ' \n'}), isFalse);
for (final messageKind in ['notice', 'agent_report']) { for (final messageKind in ['notice', 'agent_report']) {
expect( expect(
attention({ attention({'kind': 'text', 'delta': 'x', 'message_kind': messageKind}),
'kind': 'text',
'delta': 'x',
'message_kind': messageKind,
}),
isFalse, isFalse,
); );
} }
@@ -76,34 +76,36 @@ void main() {
expect(_opacity(tester), 1); expect(_opacity(tester), 1);
}); });
testWidgets('desktop shows it on hover and focus, and keeps semantics', ( testWidgets(
tester, 'desktop shows it on hover and focus, and keeps semantics',
) async { (tester) async {
final semantics = tester.ensureSemantics(); final semantics = tester.ensureSemantics();
await tester.pumpWidget(_host(48)); await tester.pumpWidget(_host(48));
expect(_opacity(tester), 0); expect(_opacity(tester), 0);
// Hidden, it is still reachable by a screen reader. // Hidden, it is still reachable by a screen reader.
expect( expect(
tester.getSemantics(_copy), tester.getSemantics(_copy),
isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true),
); );
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
addTearDown(mouse.removePointer); addTearDown(mouse.removePointer);
await mouse.addPointer(location: Offset.zero); await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(tester.getCenter(find.text('The answer text'))); await mouse.moveTo(tester.getCenter(find.text('The answer text')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(_opacity(tester), 1); expect(_opacity(tester), 1);
await mouse.moveTo(const Offset(5, 590)); await mouse.moveTo(const Offset(5, 590));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(_opacity(tester), 0); expect(_opacity(tester), 0);
// Keyboard focus reveals it too. // Keyboard focus reveals it too.
await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(_opacity(tester), 1); expect(_opacity(tester), 1);
semantics.dispose(); semantics.dispose();
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); },
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
for (final (width, inGutter) in [(1400.0, true), (560.0, false)]) { for (final (width, inGutter) in [(1400.0, true), (560.0, false)]) {
testWidgets('a ${width.toInt()} px conversation puts Copy ' testWidgets('a ${width.toInt()} px conversation puts Copy '
@@ -0,0 +1,278 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/chat_runtime.dart';
import 'package:pipelines_app/features/chat/windows/chat_windows.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart';
import 'package:pipelines_app/shell/windows/window_kind.dart';
import 'package:pipelines_app/shell/windows/window_manager.dart';
import 'package:pipelines_app/ui/input/keyboard_owner.dart';
class _Gateway implements ApiGateway {
final calls = <String>[];
@override
Stream<JsonMap> get frames => const Stream.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(type);
if (type == 'chat_sessions') {
return {
'chat_sessions': [
{'id': 'a', 'title': 'Chat a'},
{'id': 'b', 'title': 'Chat b'},
],
};
}
return {};
}
}
class _Legacy implements ChatFloatStore {
_Legacy(this.record);
ChatFloatRecord? record;
@override
Future<ChatFloatRecord?> read() async => record;
@override
Future<bool> write(ChatFloatRecord value) async {
record = value;
return true;
}
}
class _Harness {
_Harness() {
windows = ChatWindows(
manager: manager,
runtime: runtime,
openInChat: opened.add,
)..start();
}
final gateway = _Gateway();
late final runtime = ChatRuntime(gateway: gateway, serverKey: 'home');
final manager = WindowManager(kinds: WindowKinds(), server: 'home');
final opened = <String>[];
final docked = <String>[];
final floated = <String>[];
final tiled = <String>{};
bool canFloat = true;
late final ChatWindows windows;
void mountTiling() => windows.tiling = ChatTiling(
holds: tiled.contains,
dock: docked.add,
canFloatActive: () => canFloat,
floatActive: () {
floated.add('active');
windows.float('a');
},
);
List<String> get chats => [for (final w in windows.windows) w.contentId];
void dispose() {
windows.dispose();
runtime.dispose();
manager.dispose();
}
}
Future<void> _chord(
WidgetTester tester, [
LogicalKeyboardKey modifier = LogicalKeyboardKey.altLeft,
]) async {
await tester.sendKeyDownEvent(modifier);
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(modifier);
await tester.pump();
}
void main() {
late _Harness h;
// Built inside each test: the chord's handler belongs to that test's
// focus manager.
void start() {
h = _Harness();
addTearDown(h.dispose);
}
Future<void> wide(WidgetTester tester, {Size size = const Size(1280, 800)}) {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
start();
return tester.pumpWidget(const MaterialApp(home: SizedBox()));
}
test('a window is a server-scoped chat entry; show raises it', () {
start();
h.windows.float('a');
h.windows.float('b');
final a = h.manager.find(chatWindowKind, 'a')!;
expect(a.serverKey, 'home');
expect(a.frame, chatFloatDefaultRect);
expect(h.windows.show('a'), isTrue);
expect(h.manager.active!.contentId, 'a');
expect(h.windows.show('zz'), isFalse);
h.manager.setGroupShown(chatWindowKind, false);
expect(h.windows.show('b'), isTrue);
expect(h.manager.groupShown(chatWindowKind), isTrue);
});
test('Dock returns the chat to the tiling, or opens Chat without one', () {
start();
h.windows.float('a');
h.windows.float('b');
h.windows.dock(h.manager.find(chatWindowKind, 'a')!);
expect(h.opened, ['a']);
h.mountTiling();
h.windows.dock(h.manager.find(chatWindowKind, 'b')!);
expect(h.docked, ['b']);
expect(h.chats, isEmpty);
});
test('/new moves the window to the new session; /close closes it', () {
start();
h.windows.float('a');
final id = h.manager.find(chatWindowKind, 'a')!.id;
h.windows.startedNewSession(id, 'a', {'id': 'a2', 'title': 'Fresh'}, 'New');
expect(h.chats, ['a2']);
expect(h.runtime.startNotice, (id: 'a2', notice: 'New'));
expect(h.runtime.titleFor('a2'), 'Fresh');
// Another device moves it again.
h.runtime.sessions.onSessionReplaced!('a2', {'id': 'a3'});
expect(h.chats, ['a3']);
// Into a session the tiling already shows: the duplicate window closes.
h.mountTiling();
h.tiled.add('t');
h.windows.startedNewSession(id, 'a3', {'id': 't'}, 'New');
expect(h.chats, isEmpty);
h.windows.float('b');
h.windows.sessionClosed(h.manager.find(chatWindowKind, 'b')!.id);
expect(h.chats, isEmpty);
});
test('windows read their rows without the Chat destination', () async {
start();
h.windows.float('a');
await pumpEventQueue();
expect(h.gateway.calls, contains('chat_sessions'));
expect(h.runtime.titleFor('a'), 'Chat a');
expect(h.runtime.opened.keys, ['a']);
});
test('saved floating chats of an older build become windows, once', () async {
start();
final legacy = _Legacy(
const ChatFloatRecord(
panes: [ChatWorkspacePane('p1', 'a'), ChatWorkspacePane('p2', 'b')],
shown: false,
frames: {'p2': Rect.fromLTWH(300, 200, 500, 400)},
),
);
await h.windows.migrate(legacy);
expect(h.chats, ['a', 'b']);
expect(
h.manager.find(chatWindowKind, 'b')!.frame,
const Rect.fromLTWH(300, 200, 500, 400),
);
expect(h.manager.groupShown(chatWindowKind), isFalse);
expect(legacy.record!.panes, isEmpty);
h.manager.close(h.manager.find(chatWindowKind, 'a')!.id);
await h.windows.migrate(legacy);
expect(h.chats, ['b']);
// Windows already saved by this build win over an old record.
final other = _Legacy(
const ChatFloatRecord(panes: [ChatWorkspacePane('p9', 'z')]),
);
await h.windows.migrate(other);
expect(h.chats, ['b']);
expect(other.record!.panes, isEmpty);
});
testWidgets('the chord floats the active pane, then hides and shows every '
'chat window', (tester) async {
await wide(tester);
// No tiling and no window: the key is left alone.
await _chord(tester);
expect(h.chats, isEmpty);
h.mountTiling();
h.canFloat = false;
await _chord(tester);
expect(h.floated, isEmpty);
h.canFloat = true;
await _chord(tester);
expect(h.floated, ['active']);
expect(h.chats, ['a']);
h.windows.float('b');
await _chord(tester);
expect(h.manager.groupShown(chatWindowKind), isFalse);
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.manager.groupShown(chatWindowKind), isTrue);
expect(h.floated, ['active']);
// A plain Y is typing.
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
expect(h.manager.groupShown(chatWindowKind), isTrue);
});
testWidgets('a held chord toggles once', (tester) async {
await wide(tester);
h.windows.float('a');
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
await tester.sendKeyDownEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
expect(h.manager.groupShown(chatWindowKind), isFalse);
});
testWidgets(
'on macOS Ctrl+Y in a terminal stays with it; Cmd+Y and Option+Y toggle',
(tester) async {
await wide(tester);
final typing = FocusNode();
addTearDown(typing.dispose);
final typed = <LogicalKeyboardKey>[];
await tester.pumpWidget(
MaterialApp(
home: TypingSurface(
child: Focus(
focusNode: typing,
onKeyEvent: (node, event) {
if (event is KeyDownEvent) typed.add(event.logicalKey);
return KeyEventResult.handled;
},
child: const SizedBox(height: 40),
),
),
),
);
h.windows.float('a');
typing.requestFocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.manager.groupShown(chatWindowKind), isTrue);
expect(typed, contains(LogicalKeyboardKey.keyY));
await _chord(tester, LogicalKeyboardKey.metaLeft);
expect(h.manager.groupShown(chatWindowKind), isFalse);
await _chord(tester);
expect(h.manager.groupShown(chatWindowKind), isTrue);
},
variant: const TargetPlatformVariant({TargetPlatform.macOS}),
);
testWidgets('a narrow app never takes the chord', (tester) async {
await wide(tester, size: const Size(430, 900));
h.mountTiling();
await _chord(tester);
expect(h.chats, isEmpty);
h.windows.float('a');
await _chord(tester);
expect(h.manager.groupShown(chatWindowKind), isTrue);
});
}
@@ -281,7 +281,7 @@ void main() {
addTearDown(workspace.dispose); addTearDown(workspace.dispose);
addTearDown(stage.dispose); addTearDown(stage.dispose);
await tester.pumpWidget(host(workspace, stage)); await tester.pumpWidget(host(workspace, stage));
workspace.float(workspace.panes.first.id); workspace.detach(workspace.panes.first.id);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(workspace.activePane?.sessionId, 'three'); expect(workspace.activePane?.sessionId, 'three');
expect(widthOf(tester, 'three'), 950); expect(widthOf(tester, 'three'), 950);
@@ -289,7 +289,7 @@ void main() {
expect(widthOf(tester, 'two'), 1368 - 12 - 950); expect(widthOf(tester, 'two'), 1368 - 12 - 950);
expect(find.byType(ChatCenterStageStrip), findsNothing); expect(find.byType(ChatCenterStageStrip), findsNothing);
workspace.dock(workspace.floatingPanes.single.id); workspace.dock('one');
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(workspace.activePane?.sessionId, 'one'); expect(workspace.activePane?.sessionId, 'one');
expect(widthOf(tester, 'one'), 950); expect(widthOf(tester, 'one'), 950);
@@ -1,245 +1,54 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_shortcut.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_shortcut.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace.dart';
import 'package:pipelines_app/ui/input/keyboard_owner.dart';
class _Pane extends StatefulWidget { const _y = KeyDownEvent(
const _Pane(this.id); physicalKey: PhysicalKeyboardKey.keyY,
final String id; logicalKey: LogicalKeyboardKey.keyY,
@override timeStamp: Duration.zero,
State<_Pane> createState() => _PaneState();
}
class _PaneState extends State<_Pane> {
final text = TextEditingController();
final focus = FocusNode();
@override
void dispose() {
text.dispose();
focus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Material(
child: TextField(
key: ValueKey('field-${widget.id}'),
controller: text,
focusNode: focus,
),
);
}
Finder _pane(String id) => find.byWidgetPredicate(
(w) => w is _Pane && w.id == id,
skipOffstage: false,
); );
class _Harness {
final controller = ChatWorkspaceController()
..open('a')
..splitActive('b', ChatSplitAxis.horizontal);
final frames = ChatFloatFrames();
final typing = FocusNode(debugLabel: 'terminal');
final typed = <LogicalKeyboardKey>[];
Widget app({bool narrow = false}) => MaterialApp(
home: Scaffold(
body: Column(
children: [
Expanded(
child: ChatWorkspace(
controller: controller,
floatFrames: frames,
singlePane: narrow,
onFocusPane: (pane) => _focus(pane.sessionId),
paneBuilder: (context, pane, active) => _Pane(pane.sessionId),
),
),
TypingSurface(
child: Focus(
focusNode: typing,
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.keyY) {
typed.add(event.logicalKey);
}
return KeyEventResult.handled;
},
child: const SizedBox(height: 40, child: Text('terminal')),
),
),
],
),
),
);
WidgetTester? tester;
void _focus(String session) =>
tester!.state<_PaneState>(_pane(session)).focus.requestFocus();
void dispose() {
controller.dispose();
frames.dispose();
typing.dispose();
}
}
Future<void> _chord(
WidgetTester tester,
LogicalKeyboardKey modifier, {
LogicalKeyboardKey key = LogicalKeyboardKey.keyY,
}) async {
await tester.sendKeyDownEvent(modifier);
await tester.sendKeyEvent(key);
await tester.sendKeyUpEvent(modifier);
await tester.pumpAndSettle();
}
void main() { void main() {
test('the chord is Ctrl+Y, and Cmd+Y on Apple platforms', () { test('menus and tooltips name the Alt chord', () {
expect(chatFloatShortcutLabel(TargetPlatform.linux), 'Ctrl+Y'); expect(chatFloatShortcutLabel(TargetPlatform.linux), 'Alt+Y');
expect(chatFloatShortcutLabel(TargetPlatform.windows), 'Ctrl+Y'); expect(chatFloatShortcutLabel(TargetPlatform.windows), 'Alt+Y');
expect(chatFloatShortcutLabel(TargetPlatform.macOS), 'Cmd+Y'); expect(chatFloatShortcutLabel(TargetPlatform.macOS), 'Option+Y');
}); });
Future<_Harness> pump(WidgetTester tester, {bool narrow = false}) async { test('Alt+Y, Ctrl+Y and Cmd+Y on Apple platforms; a plain Y types', () {
tester.view.physicalSize = const Size(1280, 800); bool chord(Set<LogicalKeyboardKey> held, TargetPlatform platform) =>
tester.view.devicePixelRatio = 1; chatFloatShortcut(_y, _FakeKeyboard(held), platform: platform);
addTearDown(tester.view.reset); expect(chord({}, TargetPlatform.linux), isFalse);
final h = _Harness()..tester = tester; expect(
addTearDown(h.dispose); chord({LogicalKeyboardKey.shiftLeft}, TargetPlatform.linux),
await tester.pumpWidget(h.app(narrow: narrow)); isFalse,
await tester.pumpAndSettle(); );
return h; expect(chord({LogicalKeyboardKey.altLeft}, TargetPlatform.linux), isTrue);
} expect(chord({LogicalKeyboardKey.altLeft}, TargetPlatform.macOS), isTrue);
expect(
testWidgets('Ctrl+Y floats the focused pane, then hides and shows it', ( chord({LogicalKeyboardKey.controlLeft}, TargetPlatform.linux),
tester, isTrue,
) async { );
final h = await pump(tester); expect(chord({LogicalKeyboardKey.metaLeft}, TargetPlatform.linux), isFalse);
final b = tester.state<_PaneState>(_pane('b')); expect(chord({LogicalKeyboardKey.metaLeft}, TargetPlatform.macOS), isTrue);
await tester.enterText(find.byKey(const ValueKey('field-b')), 'draft'); expect(
await tester.tap(find.byKey(const ValueKey('field-a'))); chord({
await tester.pump(); LogicalKeyboardKey.controlLeft,
// Plain Y and Shift+Y type; only the chord acts. LogicalKeyboardKey.metaLeft,
await tester.sendKeyEvent(LogicalKeyboardKey.keyY); }, TargetPlatform.macOS),
await _chord(tester, LogicalKeyboardKey.shiftLeft); isFalse,
expect(h.controller.floatingPanes, isEmpty); );
expect(
tester.state<_PaneState>(_pane('b')).focus.requestFocus(); chatFloatShortcut(
await tester.pump(); const KeyUpEvent(
await _chord(tester, LogicalKeyboardKey.controlLeft); physicalKey: PhysicalKeyboardKey.keyY,
expect(h.controller.floatingPanes.firstOrNull?.sessionId, 'b'); logicalKey: LogicalKeyboardKey.keyY,
expect(h.controller.paneCount, 1); timeStamp: Duration.zero,
expect(find.byKey(const ValueKey('chat-float-title')), findsOneWidget); ),
// The chat moved: same State, same draft, its field has the keyboard. _FakeKeyboard({LogicalKeyboardKey.altLeft}),
expect(tester.state<_PaneState>(_pane('b')), same(b)); ),
expect(b.text.text, 'draft'); isFalse,
expect(b.focus.hasFocus, isTrue); );
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatShown, isFalse);
expect(find.byKey(const ValueKey('chat-float-title')), findsNothing);
expect(tester.state<_PaneState>(_pane('b')), same(b));
// Showing focuses the floating chat; hiding gives the keyboard back.
final a = tester.state<_PaneState>(_pane('a'));
a.focus.requestFocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatShown, isTrue);
expect(b.focus.hasFocus, isTrue);
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(a.focus.hasFocus, isTrue);
// Docking returns the same chat to the tiling.
h.controller.dock(h.controller.floatingPanes.single.id);
await tester.pumpAndSettle();
expect(h.controller.paneCount, 2);
expect(tester.state<_PaneState>(_pane('b')), same(b));
expect(b.text.text, 'draft');
expect(tester.takeException(), isNull);
});
testWidgets('in a terminal, Ctrl+Y acts only when a chat floats', (
tester,
) async {
final h = await pump(tester);
h.typing.requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
await _chord(tester, LogicalKeyboardKey.controlLeft);
// Nothing to float from the terminal: the shell gets Ctrl+Y (yank).
expect(h.controller.floatingPanes, isEmpty);
expect(h.typed, contains(LogicalKeyboardKey.keyY));
expect(h.typed.where((k) => k == LogicalKeyboardKey.keyY).length, 2);
h.controller.float(h.controller.panes.last.id);
await tester.pumpAndSettle();
h.typing.requestFocus();
await tester.pump();
h.typed.clear();
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatShown, isFalse);
expect(h.typed, isNot(contains(LogicalKeyboardKey.keyY)));
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
expect(h.typed, [LogicalKeyboardKey.keyY]);
});
testWidgets(
'on macOS Cmd+Y toggles and Ctrl+Y in a terminal stays with it',
(tester) async {
final h = await pump(tester);
h.controller.float(h.controller.panes.last.id);
await tester.pumpAndSettle();
h.typing.requestFocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatShown, isTrue);
expect(h.typed, [LogicalKeyboardKey.keyY]);
await _chord(tester, LogicalKeyboardKey.metaLeft);
expect(h.controller.floatShown, isFalse);
await _chord(tester, LogicalKeyboardKey.metaLeft);
expect(h.controller.floatShown, isTrue);
},
variant: const TargetPlatformVariant({TargetPlatform.macOS}),
);
testWidgets('narrow layouts never show the window or take the chord', (
tester,
) async {
final h = await pump(tester, narrow: true);
tester.state<_PaneState>(_pane('b')).focus.requestFocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatingPanes, isEmpty);
// A float saved on a wide window stays, unpainted, with its state.
h.controller.float(h.controller.panes.last.id);
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey('chat-float-title')), findsNothing);
expect(_pane('b'), findsOneWidget);
await _chord(tester, LogicalKeyboardKey.controlLeft);
expect(h.controller.floatShown, isTrue);
});
testWidgets('Alt+Y floats, hides and shows like Ctrl+Y, also from a '
'terminal', (tester) async {
final h = await pump(tester);
tester.state<_PaneState>(_pane('b')).focus.requestFocus();
await tester.pump();
await _chord(tester, LogicalKeyboardKey.altLeft);
expect(h.controller.floatingPanes.firstOrNull?.sessionId, 'b');
expect(h.controller.floatShown, isTrue);
h.typing.requestFocus();
await tester.pump();
h.typed.clear();
await _chord(tester, LogicalKeyboardKey.altLeft);
expect(h.controller.floatShown, isFalse);
expect(h.typed, isEmpty);
}); });
test('Option+Y matches by key position; extra modifiers do not', () { test('Option+Y matches by key position; extra modifiers do not', () {
@@ -255,11 +64,6 @@ void main() {
chatFloatShortcut(yen, keyboard, platform: TargetPlatform.macOS), chatFloatShortcut(yen, keyboard, platform: TargetPlatform.macOS),
isTrue, isTrue,
); );
const y = KeyDownEvent(
physicalKey: PhysicalKeyboardKey.keyY,
logicalKey: LogicalKeyboardKey.keyY,
timeStamp: Duration.zero,
);
for (final extra in [ for (final extra in [
LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaLeft,
@@ -267,14 +71,13 @@ void main() {
]) { ]) {
expect( expect(
chatFloatShortcut( chatFloatShortcut(
y, _y,
_FakeKeyboard({LogicalKeyboardKey.altLeft, extra}), _FakeKeyboard({LogicalKeyboardKey.altLeft, extra}),
), ),
isFalse, isFalse,
reason: '$extra', reason: '$extra',
); );
} }
expect(chatFloatShortcut(y, _FakeKeyboard({})), isFalse);
}); });
} }
@@ -125,7 +125,9 @@ void main() {
addTearDown(controller.dispose); addTearDown(controller.dispose);
final outer = controller.root as ChatWorkspaceSplit; final outer = controller.root as ChatWorkspaceSplit;
controller.resize(outer.id, .3); controller.resize(outer.id, .3);
final ids = {for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s)}; final ids = {
for (final s in ['a', 'b', 'c', 'd']) s: _id(controller, s),
};
final serial = controller.moveSerial; final serial = controller.moveSerial;
controller.swap(ids['a']!, ids['c']!); controller.swap(ids['a']!, ids['c']!);
expect(controller.panes.map((p) => p.sessionId), ['c', 'b', 'a', 'd']); expect(controller.panes.map((p) => p.sessionId), ['c', 'b', 'a', 'd']);
@@ -1,7 +1,6 @@
import 'dart:ui'; import 'dart:ui';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_binding.dart';
import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart'; import 'package:pipelines_app/features/chat/workspace/chat_float_store.dart';
import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart'; import 'package:pipelines_app/features/chat/workspace/chat_workspace_controller.dart';
@@ -13,156 +12,63 @@ ChatWorkspaceController _three() => ChatWorkspaceController()
List<String> _sessions(ChatWorkspaceController c) => List<String> _sessions(ChatWorkspaceController c) =>
c.panes.map((p) => p.sessionId).toList(); c.panes.map((p) => p.sessionId).toList();
List<String> _floating(ChatWorkspaceController c) =>
c.floatingPanes.map((p) => p.sessionId).toList();
ChatWorkspacePane _pane(ChatWorkspaceController c, String session) => ChatWorkspacePane _pane(ChatWorkspaceController c, String session) =>
c.panes.firstWhere((p) => p.sessionId == session); c.panes.firstWhere((p) => p.sessionId == session);
class _Store implements ChatFloatStore {
_Store([this.record]);
ChatFloatRecord? record;
int writes = 0;
@override
Future<ChatFloatRecord?> read() async => record;
@override
Future<bool> write(ChatFloatRecord value) async {
writes++;
record = value;
return true;
}
}
void main() { void main() {
test('float takes a pane out of the tiling and keeps its id', () { test('detach takes a pane out of the tiling and activates a neighbour', () {
final c = _three(); final c = _three();
final b = _pane(c, 'b'); final b = _pane(c, 'b');
c.activate(b.id); c.activate(b.id);
c.float(b.id); expect(c.canFloat(b.id), isTrue);
expect(c.floatingPanes.single.id, b.id); expect(c.detach(b.id)?.sessionId, 'b');
expect(c.isFloating(b.id), isTrue);
expect(c.floatShown, isTrue);
expect(_sessions(c), ['a', 'c']); expect(_sessions(c), ['a', 'c']);
expect(c.activePane?.sessionId, isNot('b')); expect(c.activePane, isNotNull);
expect(c.holdsSession('b'), isTrue); expect(c.holdsSession('b'), isFalse);
}); });
test('a lone pane cannot float; the tiling never empties', () { test('a lone pane cannot leave: the tiling never empties by floating', () {
final c = ChatWorkspaceController()..open('a'); final c = ChatWorkspaceController()..open('a');
expect(c.canFloat(c.panes.single.id), isFalse); final only = c.panes.single;
c.float(c.panes.single.id); expect(c.canFloat(only.id), isFalse);
expect(c.floatingPanes, isEmpty); expect(c.detach(only.id), isNull);
c.splitActive('b', ChatSplitAxis.horizontal); expect(c.detach('nope'), isNull);
final b = c.activePane!; expect(_sessions(c), ['a']);
c.float(b.id);
// The last tiled chat stays: it cannot float too.
expect(c.canFloat(c.panes.single.id), isFalse);
// Closing the last tiled pane docks the oldest floating chat in its place.
c.close(c.panes.single.id);
expect(c.floatingPanes, isEmpty);
expect(c.panes.single.id, b.id);
expect(c.activePaneId, b.id);
});
test('several chats float together and show or hide together', () {
final c = _three();
c.float(_pane(c, 'a').id);
c.setFloatShown(false);
c.float(_pane(c, 'c').id);
expect(_floating(c), ['a', 'c']);
// Floating another one shows them all.
expect(c.floatShown, isTrue);
expect(_sessions(c), ['b']);
c.toggleFloatShown();
expect(c.floatShown, isFalse);
c.toggleFloatShown();
expect(c.floatShown, isTrue);
// Docking one leaves the other floating.
final a = c.floatingPanes.first;
c.dock(a.id);
expect(_floating(c), ['c']);
expect(c.activePaneId, a.id);
expect(_sessions(c), ['b', 'a']);
}); });
test('dock puts the chat right of the active pane and activates it', () { test('dock puts the chat right of the active pane and activates it', () {
final c = _three(); final c = _three();
final b = _pane(c, 'b'); c.detach(_pane(c, 'b').id);
c.float(b.id); c.activate(_pane(c, 'a').id);
final active = c.activePane!; c.dock('b');
c.dock(b.id); expect(_sessions(c), ['a', 'b', 'c']);
expect(c.floatingPanes, isEmpty); expect(c.activePane?.sessionId, 'b');
expect(c.activePaneId, b.id); // Docking a chat the tiling already shows only activates it.
final panes = c.panes.map((p) => p.id).toList(); c.dock('c');
expect(panes.indexOf(b.id), panes.indexOf(active.id) + 1); expect(_sessions(c), ['a', 'b', 'c']);
expect(_sessions(c).toSet(), {'a', 'b', 'c'}); expect(c.activePane?.sessionId, 'c');
final empty = ChatWorkspaceController()..dock('z');
expect(_sessions(empty), ['z']);
}); });
test('hide, show, reopen, close and /new follow the floating chat', () { test('a chat out in a window is shown there instead of opened', () {
final c = _three(); final c = _three();
final b = _pane(c, 'b'); final shown = <String>[];
c.float(b.id); c.showOutside = (id) {
c.toggleFloatShown(); if (id != 'w') return false;
expect(c.floatShown, isFalse); shown.add(id);
c.open('b'); return true;
expect(c.floatShown, isTrue); };
expect(_sessions(c), ['a', 'c']); c.open('w');
c.splitActive('b', ChatSplitAxis.vertical); c.splitActive('w', ChatSplitAxis.horizontal);
expect(c.paneCount, 2); expect(_sessions(c), ['a', 'b', 'c']);
c.replaceSession('b', 'b2'); expect(shown, ['w', 'w']);
expect(c.floatingPanes.single.id, b.id); c.open('d');
expect(c.floatingPanes.single.sessionId, 'b2'); expect(c.holdsSession('d'), isTrue);
c.close(b.id); // /new into a session a window holds closes the tiled duplicate.
expect(c.floatingPanes, isEmpty); c.replaceSession('a', 'w');
expect(c.paneCount, 2); expect(c.holdsSession('a'), isFalse);
}); expect(c.holdsSession('w'), isFalse);
test('/new into a session another float holds closes the duplicate', () {
final c = _three();
c.float(_pane(c, 'a').id);
c.float(_pane(c, 'b').id);
c.replaceSession('a', 'b');
expect(_floating(c), ['b']);
});
test('restoreFloats skips open sessions and taken ids', () {
final c = ChatWorkspaceController()
..open('a')
..splitActive('b', ChatSplitAxis.horizontal);
final taken = c.panes.first.id;
expect(
c.restoreFloats([
const ChatWorkspacePane('x', 'a'),
ChatWorkspacePane(taken, 'z'),
], shown: true),
0,
);
expect(c.floatShown, isFalse);
expect(
c.restoreFloats([
const ChatWorkspacePane('x', 'z'),
const ChatWorkspacePane('y', 'w'),
const ChatWorkspacePane('x', 'v'),
], shown: false),
2,
);
expect(_floating(c), ['z', 'w']);
expect(c.floatShown, isFalse);
// A new split id never collides with a floating pane's.
c.splitActive('d', ChatSplitAxis.vertical);
expect(
c.panes.map((p) => p.id),
isNot(anyOf(contains('x'), contains('y'))),
);
});
test('a restored layout drops every floating chat', () {
final c = _three();
c.float(c.panes.first.id);
c.float(c.panes.first.id);
final snapshot = c.snapshot()!;
c.restoreLayout(snapshot);
expect(c.floatingPanes, isEmpty);
}); });
test('records round-trip, read version 1 and reject malformed input', () { test('records round-trip, read version 1 and reject malformed input', () {
@@ -213,63 +119,4 @@ void main() {
expect(ChatFloatRecord.decode(bad), isNull, reason: bad); expect(ChatFloatRecord.decode(bad), isNull, reason: bad);
} }
}); });
test('frames are kept per pane, cascade by default and restore', () {
final frames = ChatFloatFrames();
expect(frames.rectFor('a'), chatFloatDefaultRect);
expect(
frames.rectFor('b', index: 2),
chatFloatDefaultRect.shift(const Offset(64, 64)),
);
frames.move('a', const Rect.fromLTWH(1, 2, 400, 300));
expect(frames.rectFor('a', index: 3), const Rect.fromLTWH(1, 2, 400, 300));
frames.restore({'b': const Rect.fromLTWH(9, 9, 400, 300)});
expect(frames.rectFor('a'), chatFloatDefaultRect);
expect(frames.rectFor('b'), const Rect.fromLTWH(9, 9, 400, 300));
});
test('binding restores after the layout and saves changes', () async {
final c = ChatWorkspaceController()
..open('a')
..splitActive('b', ChatSplitAxis.horizontal);
final store = _Store(
const ChatFloatRecord(
panes: [ChatWorkspacePane('f', 'c'), ChatWorkspacePane('g', 'd')],
shown: true,
frames: {
'f': Rect.fromLTWH(5, 6, 400, 300),
'g': Rect.fromLTWH(50, 60, 400, 300),
},
),
);
final frames = ChatFloatFrames();
final binding = ChatFloatBinding(
controller: c,
frames: frames,
store: store,
debounce: Duration.zero,
);
await binding.start();
expect(_floating(c), ['c', 'd']);
expect(c.floatShown, isTrue);
expect(frames.rectFor('f'), const Rect.fromLTWH(5, 6, 400, 300));
expect(frames.rectFor('g'), const Rect.fromLTWH(50, 60, 400, 300));
expect(store.writes, 0);
c.setFloatShown(false);
await Future<void>.delayed(Duration.zero);
await binding.flush();
expect(store.record?.shown, isFalse);
frames.move('f', const Rect.fromLTWH(70, 80, 400, 300));
final writes = store.writes;
await binding.flush();
expect(store.writes, writes + 1);
expect(store.record?.frames['f']?.left, 70);
// A docked chat keeps its frame for the next float; a closed one drops it.
c.dock('f');
c.close('g');
binding.dispose();
await Future<void>.delayed(Duration.zero);
expect(store.record?.panes, isEmpty);
expect(store.record?.frames.keys, ['f']);
});
} }
@@ -234,18 +234,19 @@ void main() {
web: false, web: false,
platform: TargetPlatform.macOS, platform: TargetPlatform.macOS,
); );
expect(mac.toggle, ['Cmd+T', 'Ctrl+T', 'Option+T', 'Ctrl+`']); expect(mac.toggle, ['Option+T', 'Cmd+T', 'Ctrl+T', 'Ctrl+`']);
expect(mac.tabs, ['Ctrl+Tab', 'Ctrl+Shift+Tab']); expect(mac.tabs, ['Ctrl+Tab', 'Ctrl+Shift+Tab']);
const linux = TerminalShortcutLabels( const linux = TerminalShortcutLabels(
web: false, web: false,
platform: TargetPlatform.linux, platform: TargetPlatform.linux,
); );
expect(linux.toggle, ['Ctrl+T', 'Alt+T', 'Ctrl+`']); expect(linux.toggle, ['Alt+T', 'Ctrl+T', 'Ctrl+`']);
const macWeb = TerminalShortcutLabels( const macWeb = TerminalShortcutLabels(
web: true, web: true,
platform: TargetPlatform.macOS, platform: TargetPlatform.macOS,
); );
expect(macWeb.toggle, ['Ctrl+T', 'Option+T', 'Ctrl+`']); expect(macWeb.toggle, ['Option+T', 'Ctrl+T', 'Ctrl+`']);
expect(macWeb.button, 'Terminal (Option+T)');
expect(macWeb.tabs, isEmpty); expect(macWeb.tabs, isEmpty);
expect(macWeb.summary, isNot(contains('Tab'))); expect(macWeb.summary, isNot(contains('Tab')));
const windowsWeb = TerminalShortcutLabels( const windowsWeb = TerminalShortcutLabels(
+1 -4
View File
@@ -33,10 +33,7 @@ void main() {
// semantics (a page route's barrier hides what is behind it). // semantics (a page route's barrier hides what is behind it).
final handle = tester.ensureSemantics(); final handle = tester.ensureSemantics();
expect(find.bySemanticsLabel('Window: Probe a'), findsOneWidget); expect(find.bySemanticsLabel('Window: Probe a'), findsOneWidget);
expect( expect(tester.getSemantics(find.byTooltip('Minimise')).tooltip, 'Minimise');
tester.getSemantics(find.byTooltip('Minimise')).tooltip,
'Minimise',
);
expect(find.bySemanticsLabel('sheet'), findsOneWidget); expect(find.bySemanticsLabel('sheet'), findsOneWidget);
expect(find.bySemanticsLabel('Chat'), findsOneWidget); expect(find.bySemanticsLabel('Chat'), findsOneWidget);
expect( expect(
@@ -7,6 +7,8 @@ import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/shell/windows/window_manager.dart'; import 'package:pipelines_app/shell/windows/window_manager.dart';
import 'package:pipelines_app/ui/motion/surface_visibility.dart';
import 'window_test_harness.dart'; import 'window_test_harness.dart';
/// Layering acceptance (docs/plans/floating-windows.md, Phase 1.4): every /// Layering acceptance (docs/plans/floating-windows.md, Phase 1.4): every
@@ -210,6 +212,31 @@ void main() {
expect(find.text('Sheet item').hitTestable(), findsOneWidget); expect(find.text('Sheet item').hitTestable(), findsOneWidget);
}); });
testWidgets('a popup opened by the press that focuses its window keeps the '
'keyboard', (tester) async {
await open(tester, 0);
// The keyboard is in the app behind, as after using another tab.
FocusManager.instance.primaryFocus?.unfocus();
await tester.pump();
await tester.tap(find.byKey(const ValueKey('b-sheet')));
await tester.pumpAndSettle();
expect(find.text('Sheet item').hitTestable(), findsOneWidget);
final focus = FocusManager.instance.primaryFocus!.context!;
expect(ModalRoute.of(focus), isA<PopupRoute<void>>());
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.text('Sheet item'), findsNothing);
// The window content is not the current surface under a popup.
await tester.tap(find.byKey(const ValueKey('b-dialog')));
await tester.pumpAndSettle();
expect(
SurfaceVisibility.currentOf(
tester.element(find.byKey(const ValueKey('content-b'))),
),
isFalse,
);
});
testWidgets('Escape closes the popup, not the window', (tester) async { testWidgets('Escape closes the popup, not the window', (tester) async {
await open(tester, 0); await open(tester, 0);
await tester.tap(find.byKey(const ValueKey('a-dialog'))); await tester.tap(find.byKey(const ValueKey('a-dialog')));
@@ -0,0 +1,24 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
/// Window content takes input only inside its window (see `WindowNavigator`),
/// so a menu panel, which may extend past the window, must be in the root
/// overlay. Any content can end up in a window, so the app's menus are all
/// `AppMenuAnchor`, the one place a `MenuAnchor` is built.
void main() {
test('MenuAnchor is used only through AppMenuAnchor', () {
final offenders = <String>[];
for (final file in Directory('lib').listSync(recursive: true)) {
if (file is! File || !file.path.endsWith('.dart')) continue;
if (file.path.endsWith('ui/adaptive/app_menu_anchor.dart')) continue;
final source = file.readAsStringSync();
for (final match in RegExp(r'\bMenuAnchor\(').allMatches(source)) {
if (match.start > 0 && source[match.start - 1] == 'p') continue;
final line = '\n'.allMatches(source.substring(0, match.start)).length;
offenders.add('${file.path}:${line + 1}');
}
}
expect(offenders, isEmpty);
});
}
@@ -0,0 +1,61 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/ui/adaptive/app_menu_anchor.dart';
void main() {
testWidgets('Escape closes the menu and the keyboard returns to the field', (
tester,
) async {
var picked = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
const TextField(key: ValueKey('field')),
AppMenuAnchor(
menuChildren: [
MenuItemButton(
onPressed: () => picked++,
child: const Text('First'),
),
MenuItemButton(
onPressed: () => picked += 10,
child: const Text('Second'),
),
],
builder: (context, menu, _) => IconButton(
tooltip: 'More',
onPressed: () => menu.isOpen ? menu.close() : menu.open(),
icon: const Icon(Icons.more_vert),
),
),
],
),
),
),
);
await tester.tap(find.byKey(const ValueKey('field')));
await tester.pump();
final field = FocusManager.instance.primaryFocus;
await tester.tap(find.byTooltip('More'));
await tester.pumpAndSettle();
expect(find.text('First'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.text('First'), findsNothing);
expect(FocusManager.instance.primaryFocus, same(field));
// The arrow keys and Enter work from wherever the keyboard was.
await tester.tap(find.byTooltip('More'));
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(picked, 10);
expect(find.text('First'), findsNothing);
});
}