Files
pipelines/app/lib/features/chat/windows/chat_windows.dart
T
alan 61c7eee2b0 App: open a chat, the terminal or a diff in a new window
"Open in new window" sits beside Float: the chat pane and chat list row
menus, a floating chat window's title bar, the terminal options menu and
the diff bar, plus Alt+Shift+Y for the chat with the keyboard (listed in
the shortcut help). Once the window opens the item leaves the main window
as Float takes a pane out of the tiling.

The window is its own app instance at /window/chat/<id>,
/window/terminal?tab=<key> or /window/diff/<token>: only that item, named
after it, with "Bring back to main window". It has its own connection and
writes no shared layout (no open-chat workspace, window store or terminal
layout) and posts no notifications, so they stay the main window's.

Web opens a popup window (a blocked popup offers a tab); Linux and macOS
start a second process with --detached (Flutter's multi-window API is still
experimental); Android and iOS hide the action. The capture kit gains a
follow step for windows a page opens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 12:47:42 +00:00

433 lines
14 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../shell/detached/detached_window_scope.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 '../../terminal/terminal_scope.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';
import 'chat_window_tabs.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,
this.release,
this.activeSession,
});
/// 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;
/// Takes [sessionId]'s panes out of the tiling (it went to a window of
/// its own).
final void Function(String sessionId)? release;
/// The active pane's chat.
final String? Function()? activeSession;
}
/// 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;
/// Opens a chat in a window of its own (a browser window or app process);
/// null where the platform has none.
DetachedWindowOpener? detached;
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);
Iterable<String> get floatingSessionIds =>
windows.map((window) => window.contentId);
/// 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)
..addEarlyKeyEventHandler(_tabKey)
..addEarlyKeyEventHandler(_detachKey);
runtime.addSessionReplacedListener(_replacedElsewhere);
runtime.sessions.addListener(_rowsChanged);
manager.addListener(_rowsChanged);
readiness.addListener(_rowsChanged);
}
void dispose() {
if (!_started) return;
_started = false;
FocusManager.instance
..removeEarlyKeyEventHandler(_key)
..removeEarlyKeyEventHandler(_tabKey)
..removeEarlyKeyEventHandler(_detachKey);
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;
}
/// Whether [sessionId] is in a chat window.
bool holds(String sessionId) =>
manager.find(chatWindowKind, sessionId) != null;
/// Hides every chat window (the group stays, to be shown again later).
void hideAll() => manager.setGroupShown(chatWindowKind, false);
/// 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);
}
}
/// Opens [sessionId] in a window of its own. Once that window is open the
/// chat leaves this one: its floating window closes and its tiled panes
/// close, as Float takes a pane out of the tiling.
void detach(String sessionId) {
final opener = detached;
if (opener == null || sessionId.isEmpty) return;
opener.openChat(
sessionId,
title: runtime.titleFor(sessionId),
onOpened: () {
final entry = manager.find(chatWindowKind, sessionId);
if (entry != null) manager.close(entry.id);
tiling?.release?.call(sessionId);
},
);
}
/// A detached window gave [sessionId] back: it goes into the tiling, or
/// opens in the Chat destination when that is not built.
void bringBack(String sessionId) {
if (sessionId.isEmpty) return;
final tiling = this.tiling;
if (tiling != null) {
tiling.dock(sessionId);
} else {
openInChat(sessionId);
}
}
/// `/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() {
_noteOpenOrder();
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.toggleOrRaiseGroup(chatWindowKind);
return KeyEventResult.handled;
}
/// Alt+Shift+Y sends the chat with the keyboard (a floating window's, else
/// the active tiled pane's) to a new window. Left alone when there is no
/// such chat or no platform window.
KeyEventResult _detachKey(KeyEvent event) {
if (detached == null ||
!detachedWindowShortcut(event, HardwareKeyboard.instance)) {
return KeyEventResult.ignored;
}
final scope = keyboardWindow();
String? id;
if (scope != null) {
if (scope.entry.kind == chatWindowKind) id = scope.entry.contentId;
} else {
final tiling = this.tiling;
if (tiling != null && tiling.canFloatActive()) {
id = tiling.activeSession?.call();
}
}
if (id == null || id.isEmpty) return KeyEventResult.ignored;
if (event is KeyDownEvent) detach(id);
return KeyEventResult.handled;
}
/// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the
/// keyboard: the next (previous) shown chat window, in open order and
/// wrapping, comes to the top. The window host then gives it the keyboard,
/// its composer. Left alone when another window or the tiling has the
/// keyboard, when the terminal claims tab keys, or with one window.
KeyEventResult _tabKey(KeyEvent event) {
final step = chatWindowTabStep(event, HardwareKeyboard.instance);
if (step == null || !_wide) return KeyEventResult.ignored;
final scope = keyboardWindow();
if (scope == null ||
scope.entry.kind != chatWindowKind ||
_terminalClaimsTabs()) {
return KeyEventResult.ignored;
}
final target = chatWindowAfter(shownInOpenOrder(), scope.entry.id, step);
if (target == null) return KeyEventResult.ignored;
manager.raise(target.id);
return KeyEventResult.handled;
}
/// The ids of the chat windows in the order they were opened; a window
/// restored from a saved layout keeps its saved place. Raising a window
/// changes the stacking order, not this one, so the Ctrl+Tab cycle is
/// stable. Kept in step on every change of the windows (see [_rowsChanged]).
final List<String> _openOrder = [];
void _noteOpenOrder() {
final ids = {for (final w in windows) w.id};
_openOrder.removeWhere((id) => !ids.contains(id));
for (final w in windows) {
if (!_openOrder.contains(w.id)) _openOrder.add(w.id);
}
}
/// The shown chat windows (not minimised, their group shown), in open order.
List<WindowEntry> shownInOpenOrder() {
_noteOpenOrder();
final shown = {
for (final w in windows)
if (manager.isVisible(w)) w.id: w,
};
return [for (final id in _openOrder) ?shown[id]];
}
/// Ctrl+Tab from the tiling or the chat list while chat windows are shown:
/// the top-most shown chat window comes to the top and its composer takes
/// the keyboard. False, doing nothing, when no chat window is shown.
bool raiseTopFromTiling() {
final top = windows.where(manager.isVisible).lastOrNull;
if (top == null) return false;
manager.raise(top.id);
kind.focusContent(top);
return true;
}
bool _terminalClaimsTabs() {
final context = FocusManager.instance.primaryFocus?.context;
return context != null &&
TerminalScope.peek(context)?.claimsTabKeys == true;
}
}
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),
),
if (windows.detached != null)
WindowAction(
label: detachedChatWindowLabel(),
icon: Icons.open_in_browser,
onPressed: () => windows.detach(entry.contentId),
),
];
@override
void focusContent(WindowEntry entry) =>
windows.runtime.composerFocus.request(entry.contentId);
}