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>
This commit is contained in:
2026-12-03 12:47:42 +00:00
parent c4de1de27b
commit 61c7eee2b0
46 changed files with 3223 additions and 72 deletions
@@ -0,0 +1,246 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import '../../core/servers/chat/chat_server_pool.dart';
import '../../core/servers/server_context.dart';
import '../../core/servers/server_scope.dart';
import '../../core/transport/pipelines_client.dart';
import '../../features/settings/server_connections.dart';
import '../../features/terminal/terminal_layout.dart';
import '../../ui/adaptive/window_margins.dart';
import '../../ui/scale/ui_scale.dart';
import '../../ui/theme/app_font_controller.dart';
import '../../ui/theme/app_theme.dart';
import '../app_route.dart';
import '../app_session.dart';
import '../app_terminals.dart';
import '../clipboard_failures.dart' show appScaffoldMessengerKey;
import '../server_endpoint.dart';
import 'detached_chat.dart';
import 'detached_diff.dart';
import 'detached_platform.dart';
import 'detached_route.dart';
import 'detached_terminal.dart';
import 'detached_window_body.dart';
import 'detached_windows.dart';
/// A detached window's whole app: one item ([route]) over its own
/// connection, without the shell (no navigation rail, lists, floating
/// windows, notifications or update checks).
///
/// It writes none of the shared layout the main window owns: not the
/// server's open-chat workspace (no Chat destination is built), not the
/// floating windows (there is no window manager) and not the terminal
/// layout ([TerminalLayout.persist] is off). System notifications stay the
/// main window's, so nothing is posted twice.
class DetachedWindowApp extends StatefulWidget {
const DetachedWindowApp({
super.key,
required this.route,
required this.server,
this.client,
this.chatPool,
this.servers,
this.serverId,
this.serverAddresses,
this.platform,
this.web = kIsWeb,
});
final DetachedRoute route;
final ServerEndpoint server;
final PipelinesClient? client;
final ChatServerPool? chatPool;
final ServerConnections? servers;
final String? serverId;
final List<Uri>? serverAddresses;
final DetachedPlatform? platform;
final bool web;
@override
State<DetachedWindowApp> createState() => _DetachedWindowAppState();
}
class _DetachedWindowAppState extends State<DetachedWindowApp> {
late final AppSession _session;
late final DetachedPlatform _platform =
widget.platform ?? DetachedPlatform.instance;
final _title = ValueNotifier<String>('');
final _ready = ValueNotifier<bool>(false);
final _sync = ValueNotifier<int>(0);
AppTerminals? _terminals;
late final DetachedWindowControls _controls = DetachedWindowControls(
ready: _ready,
sync: _sync,
setTitle: _setTitle,
close: () => unawaited(_platform.closeSelf()),
bringBackItem: (kind, id, files, index) => unawaited(
_bringBack(DetachedReturn(kind, id, files: files, initialIndex: index)),
),
);
@override
void initState() {
super.initState();
TerminalLayout.instance.persist = false;
_session = AppSession(
endpoint: widget.server.uri,
client: widget.client,
knownServer: true,
addresses: widget.serverAddresses,
);
bindServerIdentity(_session.gateway, widget.serverId);
bindServerIdentity(_session.client, widget.serverId);
_session.addListener(_connectionChanged);
widget.chatPool?.addListener(_connectionChanged);
_connectionChanged();
if (widget.route.kind == DetachedKind.terminal) {
_terminals = AppTerminals(
pool: widget.chatPool,
connection: Listenable.merge([_session, ?widget.servers]),
connected: () => _session.connected,
gateway: _session.gateway,
machineId: widget.serverId ?? 'server',
machineName: _serverName,
layout: TerminalLayout.instance,
);
}
unawaited(_session.start());
}
@override
void dispose() {
_session.removeListener(_connectionChanged);
widget.chatPool?.removeListener(_connectionChanged);
_terminals?.dispose();
_session.dispose();
_title.dispose();
_ready.dispose();
_sync.dispose();
super.dispose();
}
void _connectionChanged() {
final pool = widget.chatPool;
_ready.value =
(pool != null && pool.servers.catalog.servers.isNotEmpty) ||
_session.connected;
_sync.value = pool?.revision ?? _session.connectionEpoch;
}
String _serverName() {
final servers = widget.servers;
for (final server in servers?.catalog.servers ?? const []) {
if (server.id == widget.serverId) return server.name;
}
return servers?.originHostname ?? _session.endpoint?.host ?? 'Server';
}
/// Titles change from listeners that may fire while a frame is built; the
/// app's title follows after it.
void _setTitle(String title) {
if (SchedulerBinding.instance.schedulerPhase ==
SchedulerPhase.persistentCallbacks) {
SchedulerBinding.instance.addPostFrameCallback((_) {
if (mounted) _title.value = title;
});
return;
}
_title.value = title;
}
/// Hands the item to the main window and closes this one. With no main
/// window, a chat or the terminal opens the full app here instead; a diff
/// stays (it exists only in this window).
Future<void> _bringBack(DetachedReturn item) async {
if (await _platform.sendToMain(item.toMessage())) {
await _platform.closeSelf();
return;
}
final path = switch (item.kind) {
DetachedKind.chat => AppRoute.chatSession(item.id).path,
DetachedKind.terminal => AppRoute.chat.path,
DetachedKind.diff => null,
};
if (path != null && await _platform.becomeMain(path)) return;
appScaffoldMessengerKey.currentState?.showSnackBar(
const SnackBar(content: Text('No main window is open to take it back.')),
);
}
Widget _body() => switch (widget.route.kind) {
DetachedKind.chat => DetachedChat(
sessionId:
widget.chatPool?.gateway.normalizeId(widget.route.id) ??
widget.route.id,
gateway: widget.chatPool?.gateway ?? _session.gateway,
serverKey: widget.chatPool != null
? 'all-saved-servers'
: serverStorageScope(widget.serverId),
window: _controls,
),
DetachedKind.terminal => DetachedTerminal(
terminals: _terminals!,
tabKey: widget.route.id,
window: _controls,
),
DetachedKind.diff => DetachedDiff(
token: widget.route.id,
platform: _platform,
window: _controls,
),
};
Route<void> _page() => MaterialPageRoute<void>(
settings: RouteSettings(name: widget.route.path),
builder: (_) => _DetachedHome(child: _body()),
);
@override
Widget build(BuildContext context) {
final fonts = AppFontController.instance;
final app = ListenableBuilder(
listenable: Listenable.merge([fonts, _title]),
builder: (context, _) => MaterialApp(
title: _title.value.isEmpty
? 'Pipelines'
: '${_title.value} · Pipelines',
scaffoldMessengerKey: appScaffoldMessengerKey,
debugShowCheckedModeBanner: false,
builder: (context, child) => UiScaleHost(
child: WindowMargins(child: child ?? const SizedBox.shrink()),
),
theme: appLightTheme(fontFamily: fonts.family),
darkTheme: appDarkTheme(fontFamily: fonts.family),
themeMode: ThemeMode.system,
// The window's one page is named by its route, so the address bar
// (and a reload) keeps the detached location instead of `/`.
initialRoute: widget.route.path,
onGenerateInitialRoutes: (_) => [_page()],
onGenerateRoute: (_) => _page(),
),
);
final servers = widget.servers;
return servers == null
? app
: ServerContext(
connections: servers,
serverId: widget.serverId,
child: app,
);
}
}
/// The window's single page: the item fills it.
class _DetachedHome extends StatelessWidget {
const _DetachedHome({required this.child});
final Widget child;
@override
Widget build(BuildContext context) =>
Scaffold(key: const ValueKey('detached-window'), body: child);
}
@@ -0,0 +1,153 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../features/chat/chat_pane_content.dart';
import '../../features/chat/chat_runtime.dart';
import '../../features/chat/data/chat_recency.dart';
import '../../features/chat/ui/sessions/chat_adaptive.dart';
import '../../features/chat/workspace/chat_pane_commands.dart';
import 'detached_route.dart';
import 'detached_window_body.dart';
/// One chat alone in a detached window: the same live pane as in the Chat
/// destination (header, transcript, find, composer), with "Bring back to
/// main window" in its More menu. It has its own [ChatRuntime] over this
/// window's connection and keeps no workspace: nothing it does is saved as
/// the device's or the server's open-chat layout.
class DetachedChat extends StatefulWidget {
const DetachedChat({
super.key,
required this.sessionId,
required this.gateway,
required this.window,
this.serverKey = '',
});
final String sessionId;
final ApiGateway gateway;
final String serverKey;
final DetachedWindowControls window;
@override
State<DetachedChat> createState() => _DetachedChatState();
}
class _DetachedChatState extends State<DetachedChat> {
// An in-memory recency: the main window keeps the device's.
late final ChatRuntime _runtime = ChatRuntime(
gateway: widget.gateway,
serverKey: widget.serverKey,
recency: ChatRecency(),
);
final _paneCommands = ChatPaneCommands();
late String _sessionId = widget.sessionId;
bool _reading = false;
@override
void initState() {
super.initState();
_runtime.addListener(_retitle);
_runtime.sessions.addListener(_rowsChanged);
_runtime.addSessionReplacedListener(_replacedElsewhere);
widget.window.ready.addListener(_rowsChanged);
_rowsChanged();
_runtime.composerFocus.request(_sessionId);
_retitle();
}
@override
void didUpdateWidget(DetachedChat oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.gateway, widget.gateway)) {
_runtime.gateway = widget.gateway;
}
if (oldWidget.window.ready != widget.window.ready) {
oldWidget.window.ready.removeListener(_rowsChanged);
widget.window.ready.addListener(_rowsChanged);
}
}
@override
void dispose() {
widget.window.ready.removeListener(_rowsChanged);
_runtime.removeListener(_retitle);
_runtime.sessions.removeListener(_rowsChanged);
_runtime.removeSessionReplacedListener(_replacedElsewhere);
_paneCommands.dispose();
_runtime.dispose();
super.dispose();
}
void _retitle() => widget.window.setTitle(_runtime.titleFor(_sessionId));
/// The pane's title, model and mode come from the session list, read once
/// connected (and again on every reconnect, see [build]).
void _rowsChanged() {
if (!widget.window.ready.value) return;
final sessions = _runtime.sessions;
if (_runtime.rowFor(_sessionId) == null && !_reading) {
_reading = true;
unawaited(sessions.refresh().whenComplete(() => _reading = false));
}
final rows = sessions.sessions;
scheduleMicrotask(() {
if (mounted) {
_runtime.adoptRows(rows, selected: _sessionId, retained: {_sessionId});
}
});
}
/// `/new` here, or on another device: the window follows the new session.
void _follow(String previousId, JsonMap session, String notice) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty || previousId != _sessionId) return;
_runtime.movedToSession(previousId, session, notice);
setState(() => _sessionId = id);
_retitle();
}
void _startedNewSession(String previousId, JsonMap session, String notice) {
_runtime.sessions.replaceSession(previousId, session);
_follow(previousId, session, notice);
unawaited(_runtime.sessions.refresh());
}
void _replacedElsewhere(String previousId, JsonMap session) =>
_follow(previousId, session, 'This chat continues in a new session.');
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([widget.window.ready, widget.window.sync]),
builder: (context, _) {
if (!widget.window.ready.value) return const DetachedConnecting();
final sessionId = _sessionId;
return buildChatPaneContent(
runtime: _runtime,
sessionId: sessionId,
placement: ChatPanePlacement(
syncToken: widget.window.sync.value,
onBack: () {},
showBackButton: false,
// The only chat here: a paste with no field focused is its.
pasteTarget: true,
paneCommands: _paneCommands,
onComposerFocus: () => _runtime.composerFocus.request(sessionId),
onNewSession: _startedNewSession,
// `/close` was accepted: nothing is left to show.
onSessionClosed: widget.window.close,
paneControls: (_) => [
ChatBarAction(
label: detachedBringBackLabel,
identifier: 'detached-bring-back',
onPressed: () =>
widget.window.bringBack(DetachedKind.chat, sessionId),
materialIcon: Icons.login,
),
],
),
);
},
);
}
@@ -0,0 +1,107 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import '../../features/changes/domain/file_change.dart';
import '../../features/changes/widgets/file_diff_page.dart';
import 'detached_platform.dart';
import 'detached_route.dart';
import 'detached_window_body.dart';
/// The diff a window was handed: its files and the one it opened on.
typedef DetachedDiffContent = ({List<FileChange> files, int index});
/// Reads the hand-over [json] (`{"files": [...], "index": n}`); null when it
/// holds no file.
DetachedDiffContent? decodeDetachedDiff(String? json) {
if (json == null) return null;
try {
final value = jsonDecode(json);
if (value is! Map) return null;
final raw = value['files'];
final files = [
if (raw is List)
for (final entry in raw) ?FileChange.fromHandover(entry),
];
if (files.isEmpty) return null;
final index = value['index'];
return (
files: files,
index: index is int ? index.clamp(0, files.length - 1) : 0,
);
} on FormatException {
return null;
}
}
/// A diff alone in a detached window. Its files are in memory only, handed
/// over through the platform (see [DetachedPlatform.take]); there is nothing
/// to read from the server.
class DetachedDiff extends StatefulWidget {
const DetachedDiff({
super.key,
required this.token,
required this.platform,
required this.window,
});
final String token;
final DetachedPlatform platform;
final DetachedWindowControls window;
@override
State<DetachedDiff> createState() => _DetachedDiffState();
}
class _DetachedDiffState extends State<DetachedDiff> {
late final Future<DetachedDiffContent?> _content = widget.platform
.take(widget.token)
.then(decodeDetachedDiff);
@override
void initState() {
super.initState();
unawaited(_content.then(_retitle));
}
void _retitle(DetachedDiffContent? content) {
final files = content?.files;
widget.window.setTitle(switch (files) {
null || [] => 'Diff',
[final file] => file.path.split('/').last,
_ => '${files.length} files changed',
});
}
@override
Widget build(BuildContext context) => FutureBuilder<DetachedDiffContent?>(
future: _content,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const Material(child: SizedBox.expand());
}
final content = snapshot.data;
if (content == null) {
return const Material(
child: Center(child: Text('This diff is no longer available.')),
);
}
return FileDiffPage(
files: content.files,
initialIndex: content.index,
inWindow: true,
actions: [
DetachedBringBackButton(
onPressed: () => widget.window.bringBack(
DetachedKind.diff,
widget.token,
files: [for (final file in content.files) file.toJson()],
initialIndex: content.index,
),
),
],
);
},
);
}
@@ -0,0 +1,96 @@
import 'dart:convert';
import 'dart:ui';
import 'detached_platform_stub.dart'
if (dart.library.js_interop) 'detached_platform_web.dart'
if (dart.library.io) 'detached_platform_io.dart'
as host;
import 'detached_route.dart';
/// How a launch went.
enum DetachedLaunch {
/// The window is open (or an open one came to the front).
opened,
/// The browser blocked the popup; a click may open it as a tab.
blocked,
/// Nothing could be opened.
failed,
}
/// A message between a detached window and the main window, as JSON.
typedef DetachedMessage = Map<String, Object?>;
/// The platform's side of detached windows: opening one, the messages they
/// send back to the main window, and a hand-over of data too large for a
/// URL (a diff's files).
///
/// - Web: `window.open` with popup features, `postMessage` to the opener,
/// and `localStorage` for the hand-over.
/// - Linux and macOS: a second process of the app with `--detached <path>`,
/// a line on its standard output, and a temporary file.
/// - Android and iOS: unsupported.
abstract class DetachedPlatform {
/// The app's platform.
static DetachedPlatform instance = host.createDetachedPlatform();
/// Extra query parameters every detached browser window's URL carries.
/// The capture fixture sets its own (`chats=2`, `theme=dark`), so the
/// window it opens runs on the same fixture; the app sets none.
static Map<String, String> Function()? extraQuery;
/// Whether this platform can open detached windows.
bool get supported;
/// Opens [route] in a new window of [size] named [title]; [tab] opens a
/// browser tab instead (from a click, after a blocked popup).
Future<DetachedLaunch> launch(
DetachedRoute route, {
required String title,
required Size size,
bool tab = false,
});
/// Messages the detached windows send to this (main) window.
Stream<DetachedMessage> get messages;
/// Keeps [json] for the window that will ask for [token].
Future<void> put(String token, String json);
/// The data kept under [token], for this window; null when there is none.
Future<String?> take(String token);
/// Sends [message] to the main window that opened this one; false when
/// there is none to receive it.
Future<bool> sendToMain(DetachedMessage message);
/// Closes this detached window.
Future<void> closeSelf();
/// Opens the full app (the main window) at [appPath], in place of this
/// detached window; false when this platform cannot.
Future<bool> becomeMain(String appPath);
}
/// The detached window this launch opens, or null for the main window: the
/// browser location on the web, `--detached <path>` (or the environment) on
/// a desktop.
DetachedRoute? detachedLaunchRoute(List<String> args) =>
host.launchedDetachedRoute(args);
/// The marker a message carries, so the main window ignores anything else.
const detachedMessageMarker = 'pipelines.detached.v1';
String encodeDetachedMessage(DetachedMessage message) =>
jsonEncode({...message, 'marker': detachedMessageMarker});
DetachedMessage? decodeDetachedMessage(String text) {
try {
final value = jsonDecode(text);
if (value is! Map || value['marker'] != detachedMessageMarker) return null;
return Map<String, Object?>.from(value)..remove('marker');
} on FormatException {
return null;
}
}
@@ -0,0 +1,159 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'detached_platform.dart';
import 'detached_route.dart';
/// Widget tests run on a desktop host but are not a desktop app: there the
/// action stays hidden unless a test supplies a platform.
DetachedPlatform createDetachedPlatform() => IoDetachedPlatform(
supported:
(Platform.isLinux || Platform.isMacOS) &&
!Platform.environment.containsKey('FLUTTER_TEST'),
);
DetachedRoute? launchedDetachedRoute(List<String> args) =>
DetachedRoute.fromLaunch(args, Platform.environment);
/// Detached windows as second processes of the desktop app (Linux, macOS).
///
/// Flutter 3.44's multi-window API is still experimental (behind a flag and
/// without macOS parity), so each detached window is the same executable
/// started with `--detached <path>`; `PIPELINES_DETACHED` carries the path
/// too, since the macOS runner does not hand its arguments to Dart. It
/// shares the saved servers, session and preferences on disk, and has its
/// own connection. It writes messages for the main window as lines on its
/// standard output, which the main process reads.
class IoDetachedPlatform extends DetachedPlatform {
IoDetachedPlatform({bool? supported})
: _supported = supported ?? (Platform.isLinux || Platform.isMacOS);
final bool _supported;
final Map<DetachedRoute, Process> _children = {};
final _messages = StreamController<DetachedMessage>.broadcast();
static const _linePrefix = '@@pipelines-window ';
static const titleVariable = 'PIPELINES_WINDOW_TITLE';
static const sizeVariable = 'PIPELINES_WINDOW_SIZE';
static const parentVariable = 'PIPELINES_PARENT_PID';
@override
bool get supported => _supported;
@override
Future<DetachedLaunch> launch(
DetachedRoute route, {
required String title,
required Size size,
bool tab = false,
}) async {
if (!_supported) return DetachedLaunch.failed;
// A window already open for the item is left as it is: another process
// cannot be raised from here.
if (_children.containsKey(route)) return DetachedLaunch.opened;
final Process process;
try {
process = await Process.start(
Platform.resolvedExecutable,
[DetachedRoute.argument, route.path],
environment: {
DetachedRoute.environment: route.path,
titleVariable: title,
sizeVariable: '${size.width.round()}x${size.height.round()}',
parentVariable: '$pid',
},
);
} catch (_) {
return DetachedLaunch.failed;
}
_children[route] = process;
// Both streams are drained, so a chatty child never blocks on a full
// pipe; only marked lines are messages.
process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(_line, onError: (_) {});
process.stderr.listen((_) {}, onError: (_) {});
unawaited(process.exitCode.then((_) => _children.remove(route)));
return DetachedLaunch.opened;
}
void _line(String line) {
if (!line.startsWith(_linePrefix)) return;
final message = decodeDetachedMessage(line.substring(_linePrefix.length));
if (message != null) _messages.add(message);
}
@override
Stream<DetachedMessage> get messages => _messages.stream;
File _file(String token) =>
File('${Directory.systemTemp.path}/pipelines-detached-$token.json');
@override
Future<void> put(String token, String json) async {
try {
await _file(token).writeAsString(json, flush: true);
} catch (_) {
// The window says the diff is gone.
}
}
@override
Future<String?> take(String token) async {
final file = _file(token);
try {
final text = await file.readAsString();
await file.delete();
return text;
} catch (_) {
return null;
}
}
int? get _parent => int.tryParse(Platform.environment[parentVariable] ?? '');
Future<bool> _parentAlive() async {
final parent = _parent;
if (parent == null) return false;
try {
return (await Process.run('kill', ['-0', '$parent'])).exitCode == 0;
} catch (_) {
return false;
}
}
@override
Future<bool> sendToMain(DetachedMessage message) async {
if (!await _parentAlive()) return false;
try {
stdout.writeln('$_linePrefix${encodeDetachedMessage(message)}');
await stdout.flush();
return true;
} catch (_) {
return false;
}
}
@override
Future<void> closeSelf() async => exit(0);
/// Starts the app as an ordinary main window (it opens where it last was)
/// for this one to close.
@override
Future<bool> becomeMain(String appPath) async {
try {
await Process.start(
Platform.resolvedExecutable,
const [],
environment: {DetachedRoute.environment: '', parentVariable: ''},
mode: ProcessStartMode.detached,
);
} catch (_) {
return false;
}
exit(0);
}
}
@@ -0,0 +1,41 @@
import 'dart:ui';
import 'detached_platform.dart';
import 'detached_route.dart';
DetachedPlatform createDetachedPlatform() => UnsupportedDetachedPlatform();
DetachedRoute? launchedDetachedRoute(List<String> args) =>
DetachedRoute.fromLaunch(args);
/// A platform without windows of its own (a phone): nothing opens.
class UnsupportedDetachedPlatform extends DetachedPlatform {
@override
bool get supported => false;
@override
Future<DetachedLaunch> launch(
DetachedRoute route, {
required String title,
required Size size,
bool tab = false,
}) async => DetachedLaunch.failed;
@override
Stream<DetachedMessage> get messages => const Stream.empty();
@override
Future<void> put(String token, String json) async {}
@override
Future<String?> take(String token) async => null;
@override
Future<bool> sendToMain(DetachedMessage message) async => false;
@override
Future<void> closeSelf() async {}
@override
Future<bool> becomeMain(String appPath) async => false;
}
@@ -0,0 +1,164 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:ui';
import 'package:web/web.dart' as web;
import 'detached_platform.dart';
import 'detached_route.dart';
DetachedPlatform createDetachedPlatform() => WebDetachedPlatform();
DetachedRoute? launchedDetachedRoute(List<String> args) =>
DetachedRoute.parse(Uri.base.toString());
/// Detached windows as browser windows of the same origin: the session
/// cookie and the local preferences are shared, and each window is its own
/// app instance with its own connection.
class WebDetachedPlatform extends DetachedPlatform {
final Map<String, web.Window> _opened = {};
StreamController<DetachedMessage>? _messages;
JSFunction? _listener;
@override
bool get supported => true;
@override
Future<DetachedLaunch> launch(
DetachedRoute route, {
required String title,
required Size size,
bool tab = false,
}) async {
final name = _name(route);
final open = _opened[name];
if (open != null && !open.closed) {
open.focus();
return DetachedLaunch.opened;
}
final url = _url(route);
final web.Window? window;
try {
window = tab
? web.window.open(url, name)
: web.window.open(
url,
name,
'popup,width=${size.width.round()},height=${size.height.round()}',
);
} catch (_) {
return DetachedLaunch.failed;
}
if (window == null) {
return tab ? DetachedLaunch.failed : DetachedLaunch.blocked;
}
_opened[name] = window;
return DetachedLaunch.opened;
}
/// One browser window per item: opening it again brings that one forward.
static String _name(DetachedRoute route) =>
'pipelines-${route.kind.name}-'
'${route.id.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_')}';
static String _url(DetachedRoute route) {
final base = Uri.base.resolve(route.path);
final extra = DetachedPlatform.extraQuery?.call() ?? const {};
if (extra.isEmpty) return base.toString();
return base
.replace(queryParameters: {...extra, ...base.queryParameters})
.toString();
}
@override
Stream<DetachedMessage> get messages {
final existing = _messages;
if (existing != null) return existing.stream;
final controller = _messages = StreamController.broadcast();
final listener = ((web.MessageEvent event) {
if (event.origin != web.window.location.origin) return;
final data = event.data;
if (!data.isA<JSString>()) return;
final message = decodeDetachedMessage((data as JSString).toDart);
if (message != null) controller.add(message);
}).toJS;
_listener = listener;
web.window.addEventListener('message', listener);
return controller.stream;
}
static String _key(String token) => 'pipelines.detached.$token';
@override
Future<void> put(String token, String json) async {
try {
web.window.localStorage.setItem(_key(token), json);
} catch (_) {
// Storage full or off: the window says the diff is gone.
}
}
/// The hand-over is read once from the shared storage, then kept in this
/// window's own session storage so a reload still has it.
@override
Future<String?> take(String token) async {
final key = _key(token);
try {
final shared = web.window.localStorage.getItem(key);
if (shared != null) {
web.window.localStorage.removeItem(key);
web.window.sessionStorage.setItem(key, shared);
return shared;
}
return web.window.sessionStorage.getItem(key);
} catch (_) {
return null;
}
}
web.Window? get _opener {
final opener = web.window.opener;
// The opener is a window of another realm: `instanceof Window` (isA)
// would refuse it, so it is taken as one.
if (opener == null) return null;
final window = opener as web.Window;
try {
return window.closed ? null : window;
} catch (_) {
return null;
}
}
@override
Future<bool> sendToMain(DetachedMessage message) async {
final opener = _opener;
if (opener == null) return false;
try {
opener.postMessage(
encodeDetachedMessage(message).toJS,
web.window.location.origin.toJS,
);
opener.focus();
return true;
} catch (_) {
return false;
}
}
@override
Future<void> closeSelf() async => web.window.close();
@override
Future<bool> becomeMain(String appPath) async {
web.window.location.assign(appPath);
return true;
}
void dispose() {
final listener = _listener;
if (listener != null) {
web.window.removeEventListener('message', listener);
}
unawaited(_messages?.close());
}
}
@@ -0,0 +1,108 @@
import '../app_route.dart';
/// What a detached window shows.
enum DetachedKind { chat, terminal, diff }
/// The route of a detached window: one chat, the terminal (on one tab) or
/// one diff, alone in its own browser window or app process, without the
/// shell's navigation.
///
/// /window/chat/:sessionId one chat pane
/// /window/terminal[?tab=:key] the terminal, on the tab [key]
/// /window/diff/:token a diff handed over under [token]
///
/// A native process gets the same path as `--detached <path>` (or the
/// `PIPELINES_DETACHED` environment variable, which macOS also passes).
class DetachedRoute {
const DetachedRoute._(this.kind, this.id);
/// One chat; null when [sessionId] is not a chat session id.
static DetachedRoute? chat(String sessionId) =>
AppRoute.isChatSessionId(sessionId)
? DetachedRoute._(DetachedKind.chat, sessionId)
: null;
/// The terminal on the tab [tabKey] (empty: the one selected).
static DetachedRoute terminal([String tabKey = '']) => DetachedRoute._(
DetachedKind.terminal,
tabKey.length > _maxTabKey ? '' : tabKey,
);
/// A diff whose files were handed over under [token].
static DetachedRoute? diff(String token) =>
_token.hasMatch(token) ? DetachedRoute._(DetachedKind.diff, token) : null;
final DetachedKind kind;
/// The chat session id, the terminal tab key or the diff token.
final String id;
static const prefix = '/window';
static const argument = '--detached';
static const environment = 'PIPELINES_DETACHED';
static final _token = RegExp(r'^[A-Za-z0-9_-]{1,64}$');
static const _maxTabKey = 512;
/// The app-relative location of this window.
String get path => switch (kind) {
DetachedKind.chat => '$prefix/chat/${Uri.encodeComponent(id)}',
DetachedKind.terminal =>
id.isEmpty
? '$prefix/terminal'
: '$prefix/terminal?${Uri(queryParameters: {'tab': id}).query}',
DetachedKind.diff => '$prefix/diff/$id',
};
/// The detached route [location] names (a path with its query, or a full
/// URL), or null when it is an ordinary app location.
static DetachedRoute? parse(String location) {
final uri = Uri.tryParse(location.trim());
if (uri == null) return null;
final segments = uri.pathSegments.where((s) => s.isNotEmpty).toList();
if (segments.length < 2 || segments.first != prefix.substring(1)) {
return null;
}
return switch ((segments[1], segments.length)) {
('chat', 3) => chat(segments[2]),
('terminal', 2) => terminal(_query(uri)['tab'] ?? ''),
('diff', 3) => diff(segments[2]),
_ => null,
};
}
/// The route a native launch names: `--detached <path>` (or
/// `--detached=<path>`) in [args], else [env]'s `PIPELINES_DETACHED`.
static DetachedRoute? fromLaunch(
List<String> args, [
Map<String, String> env = const {},
]) {
for (var i = 0; i < args.length; i++) {
final arg = args[i];
if (arg == argument && i + 1 < args.length) return parse(args[i + 1]);
if (arg.startsWith('$argument=')) {
return parse(arg.substring(argument.length + 1));
}
}
final value = env[environment];
return value == null || value.isEmpty ? null : parse(value);
}
static Map<String, String> _query(Uri uri) {
try {
return uri.queryParameters;
} on FormatException {
return const {};
}
}
@override
bool operator ==(Object other) =>
other is DetachedRoute && other.kind == kind && other.id == id;
@override
int get hashCode => Object.hash(kind, id);
@override
String toString() => path;
}
@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import '../../features/terminal/terminal_body.dart';
import '../../features/terminal/terminal_hub.dart';
import '../../features/terminal/terminal_layout.dart';
import '../../features/terminal/terminal_tab_strip.dart';
import '../app_terminals.dart';
import 'detached_route.dart';
import 'detached_window_body.dart';
/// The terminal alone in a detached window: its tabs (the machines'
/// terminals, which every client of the server shares) on the tab it was
/// sent from. The device's terminal layout is read, never written (see
/// [TerminalLayout.persist]); there is no panel or window mode to choose.
class DetachedTerminal extends StatefulWidget {
const DetachedTerminal({
super.key,
required this.terminals,
required this.tabKey,
required this.window,
});
/// This window's terminals, over its own connection.
final AppTerminals terminals;
/// The tab to select once the machines' terminals are listed.
final String tabKey;
final DetachedWindowControls window;
@override
State<DetachedTerminal> createState() => _DetachedTerminalState();
}
class _DetachedTerminalState extends State<DetachedTerminal> {
TerminalHub get _hub => widget.terminals.hub;
bool _placed = false;
@override
void initState() {
super.initState();
_hub
..addListener(_changed)
..activate();
_changed();
}
@override
void dispose() {
_hub.removeListener(_changed);
super.dispose();
}
/// Selects the tab the window was opened on as soon as it is listed, once,
/// and names the window after the selected tab.
void _changed() {
if (!_placed && widget.tabKey.isNotEmpty) {
final tab = _hub.tabs.where((tab) => tab.key == widget.tabKey);
if (tab.isNotEmpty) {
_placed = true;
_hub.select(tab.first);
}
}
final title = _hub.selected?.title;
widget.window.setTitle(
title == null || title.isEmpty ? 'Terminal' : 'Terminal: $title',
);
}
void _bringBack() =>
widget.window.bringBack(DetachedKind.terminal, _hub.selected?.key ?? '');
@override
Widget build(BuildContext context) => Material(
child: SafeArea(
child: ListenableBuilder(
listenable: Listenable.merge([_hub, widget.terminals.layout]),
builder: (context, _) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TerminalTabStrip(
hub: _hub,
layout: widget.terminals.layout,
showModes: false,
trailing: [DetachedBringBackButton(onPressed: _bringBack)],
),
Expanded(child: TerminalBody(hub: _hub)),
],
),
),
),
);
}
@@ -0,0 +1,72 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'detached_route.dart';
/// The action that hands a detached item back to the main window.
const detachedBringBackLabel = 'Bring back to main window';
/// What a detached window offers the item it shows.
class DetachedWindowControls {
const DetachedWindowControls({
required this.ready,
required this.sync,
required this.setTitle,
required this.close,
required this.bringBackItem,
});
/// Whether the server has been reached, so the item can be read.
final ValueListenable<bool> ready;
/// Advances when the connection is replaced; open views re-subscribe.
final ValueListenable<int> sync;
/// Names the window after the item (the browser or desktop title).
final ValueChanged<String> setTitle;
/// Closes this window.
final VoidCallback close;
/// Gives the item back to the main window and closes this one.
final void Function(
DetachedKind kind,
String id,
List<Map<String, Object?>> files,
int initialIndex,
)
bringBackItem;
void bringBack(
DetachedKind kind,
String id, {
List<Map<String, Object?>> files = const [],
int initialIndex = 0,
}) => bringBackItem(kind, id, files, initialIndex);
}
/// Shown until the window's connection first succeeds.
class DetachedConnecting extends StatelessWidget {
const DetachedConnecting({super.key});
@override
Widget build(BuildContext context) => Center(
child: Text('Connecting…', style: Theme.of(context).textTheme.bodyMedium),
);
}
/// The "Bring back to main window" button of a window without a menu of its
/// own (the terminal's tab strip, the diff's bar).
class DetachedBringBackButton extends StatelessWidget {
const DetachedBringBackButton({super.key, required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) => IconButton(
key: const ValueKey('detached-bring-back'),
tooltip: detachedBringBackLabel,
onPressed: onPressed,
icon: const Icon(Icons.login),
);
}
@@ -0,0 +1,193 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import '../../shell/detached/detached_window_scope.dart';
import '../clipboard_failures.dart' show appScaffoldMessengerKey;
import 'detached_platform.dart';
import 'detached_route.dart';
/// What a detached window hands back to the main window ("Bring back to
/// main window"): the item, and a diff's files.
class DetachedReturn {
const DetachedReturn(
this.kind,
this.id, {
this.files = const [],
this.initialIndex = 0,
});
final DetachedKind kind;
final String id;
final List<Map<String, Object?>> files;
final int initialIndex;
DetachedMessage toMessage() => {
'type': 'bring-back',
'kind': kind.name,
'id': id,
if (kind == DetachedKind.diff) ...{'files': files, 'index': initialIndex},
};
static DetachedReturn? fromMessage(DetachedMessage message) {
if (message['type'] != 'bring-back') return null;
final kind = DetachedKind.values.asNameMap()['${message['kind']}'];
if (kind == null) return null;
final files = message['files'];
final index = message['index'];
return DetachedReturn(
kind,
'${message['id'] ?? ''}',
files: files is List
? [
for (final file in files)
if (file is Map) Map<String, Object?>.from(file),
]
: const [],
initialIndex: index is int ? index : 0,
);
}
}
/// Window sizes a detached item opens at.
const detachedChatSize = Size(720, 860);
const detachedTerminalSize = Size(960, 600);
const detachedDiffSize = Size(1000, 820);
/// The main window's side of detached windows: opening them (see
/// [DetachedWindowOpener]) and taking items back from them.
class DetachedWindows implements DetachedWindowOpener {
DetachedWindows({
DetachedPlatform? platform,
required this.onReturn,
GlobalKey<ScaffoldMessengerState>? messenger,
}) : platform = platform ?? DetachedPlatform.instance,
_messenger = messenger ?? appScaffoldMessengerKey;
final DetachedPlatform platform;
/// Puts an item a detached window gave back into the main window.
final void Function(DetachedReturn item) onReturn;
final GlobalKey<ScaffoldMessengerState> _messenger;
StreamSubscription<DetachedMessage>? _messages;
bool get supported => platform.supported;
void start() {
if (!supported || _messages != null) return;
_messages = platform.messages.listen((message) {
final item = DetachedReturn.fromMessage(message);
if (item != null) onReturn(item);
});
}
void dispose() {
unawaited(_messages?.cancel());
_messages = null;
}
@override
void openChat(
String sessionId, {
required String title,
VoidCallback? onOpened,
}) {
final route = DetachedRoute.chat(sessionId);
if (route == null) return;
unawaited(_open(route, title, detachedChatSize, onOpened));
}
@override
void openTerminal({
String tabKey = '',
required String title,
VoidCallback? onOpened,
}) => unawaited(
_open(
DetachedRoute.terminal(tabKey),
title,
detachedTerminalSize,
onOpened,
),
);
@override
void openDiff(
List<Map<String, Object?>> files, {
int initialIndex = 0,
required String title,
VoidCallback? onOpened,
}) {
final token = _token();
final route = DetachedRoute.diff(token)!;
// The hand-over is written before the window opens, so its first read
// finds it. A popup must open within the click: on the web the write is
// synchronous, so no frame passes before it.
final written = platform.put(
token,
jsonEncode({'files': files, 'index': initialIndex}),
);
unawaited(
written.then((_) => _open(route, title, detachedDiffSize, onOpened)),
);
}
Future<void> _open(
DetachedRoute route,
String title,
Size size,
VoidCallback? onOpened,
) async {
switch (await platform.launch(route, title: title, size: size)) {
case DetachedLaunch.opened:
onOpened?.call();
case DetachedLaunch.blocked:
_say(
'The browser blocked the new window. Allow pop-ups for this site, '
'or open it in a tab.',
action: SnackBarAction(
label: 'Open in tab',
onPressed: () => unawaited(_openTab(route, title, size, onOpened)),
),
);
case DetachedLaunch.failed:
_say('Could not open a new window.');
}
}
Future<void> _openTab(
DetachedRoute route,
String title,
Size size,
VoidCallback? onOpened,
) async {
final result = await platform.launch(
route,
title: title,
size: size,
tab: true,
);
if (result == DetachedLaunch.opened) {
onOpened?.call();
} else {
_say('Could not open a new tab either.');
}
}
void _say(String text, {SnackBarAction? action}) =>
_messenger.currentState?.showSnackBar(
SnackBar(
content: Text(text),
action: action,
duration: Duration(seconds: action == null ? 4 : 10),
),
);
static final _random = Random.secure();
static String _token() => base64Url
.encode(List.generate(12, (_) => _random.nextInt(256)))
.replaceAll('=', '');
}