Merge branch 'main' into worktree-agent-a3cb3553b5c91a345
This commit is contained in:
@@ -24,10 +24,18 @@ COPY --chmod=0755 build.sh /usr/local/bin/pipelines-app-build
|
|||||||
WORKDIR /tmp
|
WORKDIR /tmp
|
||||||
|
|
||||||
FROM web AS linux
|
FROM web AS linux
|
||||||
|
# Flutter's CMake backend passes `-dTreeShakeIcons="true"` with the quotes
|
||||||
|
# kept (no shell parses them), so `flutter build linux` never tree-shakes the
|
||||||
|
# icon fonts and ships the full 1.6 MB MaterialIcons font. Pass the plain value
|
||||||
|
# in this image's copy; the grep fails the build if the line ever changes.
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install -y --no-install-recommends clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-12-dev liblzma-dev \
|
&& apt-get install -y --no-install-recommends clang cmake ninja-build pkg-config libgtk-3-dev libstdc++-12-dev liblzma-dev \
|
||||||
&& rm -rf /var/lib/apt/lists/* \
|
&& rm -rf /var/lib/apt/lists/* \
|
||||||
&& flutter precache --linux \
|
&& flutter precache --linux \
|
||||||
|
&& backend=/opt/flutter/packages/flutter_tools/bin/tool_backend.dart \
|
||||||
|
&& grep -q "'-dTreeShakeIcons=\"\$treeShakeIcons\"'," "$backend" \
|
||||||
|
&& sed -i "s/'-dTreeShakeIcons=\"\$treeShakeIcons\"',/'-dTreeShakeIcons=\$treeShakeIcons',/" "$backend" \
|
||||||
|
&& grep -q "'-dTreeShakeIcons=\$treeShakeIcons'," "$backend" \
|
||||||
&& chmod -R a+rwX /opt/flutter /home/builder
|
&& chmod -R a+rwX /opt/flutter /home/builder
|
||||||
|
|
||||||
FROM web AS android
|
FROM web AS android
|
||||||
|
|||||||
+5
-1
@@ -42,8 +42,12 @@ PROPERTIES
|
|||||||
/tmp/apk-certificates.txt > /out/signing-certificate-sha256.txt
|
/tmp/apk-certificates.txt > /out/signing-certificate-sha256.txt
|
||||||
;;
|
;;
|
||||||
linux)
|
linux)
|
||||||
flutter build linux --release "$@"
|
# Dart symbols go beside the bundle, not into libapp.so (about 18%
|
||||||
|
# smaller); `flutter symbolize -i <trace> -d .debug-info/app.linux-x64.symbols`
|
||||||
|
# reads a release stack trace. Icon fonts are tree-shaken (see Dockerfile).
|
||||||
|
flutter build linux --release --split-debug-info=/tmp/debug-info "$@"
|
||||||
cp -a build/linux/x64/release/bundle/. /out/
|
cp -a build/linux/x64/release/bundle/. /out/
|
||||||
|
cp -a /tmp/debug-info /out/.debug-info
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "unknown build: $kind" >&2
|
echo "unknown build: $kind" >&2
|
||||||
|
|||||||
@@ -75,6 +75,15 @@ class AppTerminals {
|
|||||||
Widget? barToggle(BuildContext context) =>
|
Widget? barToggle(BuildContext context) =>
|
||||||
showsListBesideDetail(context) ? toggle() : null;
|
showsListBesideDetail(context) ? toggle() : null;
|
||||||
|
|
||||||
|
/// The terminal came back from a detached window: it shows again, on
|
||||||
|
/// [tabKey] once that tab is listed.
|
||||||
|
void bringBack(String tabKey) {
|
||||||
|
hub.activate();
|
||||||
|
final tab = hub.tabs.where((tab) => tab.key == tabKey).firstOrNull;
|
||||||
|
if (tab != null) hub.select(tab);
|
||||||
|
layout.show();
|
||||||
|
}
|
||||||
|
|
||||||
void dispose() {
|
void dispose() {
|
||||||
floating?.dispose();
|
floating?.dispose();
|
||||||
hub.dispose();
|
hub.dispose();
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
|
|||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
import 'app_url_strategy.dart';
|
import 'app_url_strategy.dart';
|
||||||
|
import 'detached/detached_platform.dart';
|
||||||
import 'pipelines_binding.dart';
|
import 'pipelines_binding.dart';
|
||||||
import 'pipelines_root.dart';
|
import 'pipelines_root.dart';
|
||||||
import 'server_endpoint.dart';
|
import 'server_endpoint.dart';
|
||||||
@@ -49,13 +50,19 @@ Future<ServerEndpoint> resolveLaunchServer({
|
|||||||
/// system font.
|
/// system font.
|
||||||
const appFontStartupWait = Duration(milliseconds: 1500);
|
const appFontStartupWait = Duration(milliseconds: 1500);
|
||||||
|
|
||||||
/// Resolves the endpoint for this launch and starts the normal composition.
|
/// Resolves the endpoint for this launch and starts the normal composition,
|
||||||
|
/// or a detached window's when the launch names one ([args] on a desktop,
|
||||||
|
/// the location on the web; see `detachedLaunchRoute`).
|
||||||
Future<void> runPipelinesApp({
|
Future<void> runPipelinesApp({
|
||||||
Uri? base,
|
Uri? base,
|
||||||
String configured = configuredServerUrl,
|
String configured = configuredServerUrl,
|
||||||
SettingsStore? settingsStore,
|
SettingsStore? settingsStore,
|
||||||
|
List<String> args = const [],
|
||||||
}) async {
|
}) async {
|
||||||
useAppUrlStrategy();
|
useAppUrlStrategy();
|
||||||
|
final detached = detachedLaunchRoute(args);
|
||||||
|
// A detached window reads the device's terminal layout, never writes it.
|
||||||
|
if (detached != null) TerminalLayout.instance.persist = false;
|
||||||
PipelinesBinding.ensureInitialized();
|
PipelinesBinding.ensureInitialized();
|
||||||
registerAppFontLicenses();
|
registerAppFontLicenses();
|
||||||
// The device's chosen font loads beside the session; a slow download does
|
// The device's chosen font loads beside the session; a slow download does
|
||||||
@@ -83,6 +90,7 @@ Future<void> runPipelinesApp({
|
|||||||
server: server,
|
server: server,
|
||||||
buildDefault: configured,
|
buildDefault: configured,
|
||||||
signedIn: kIsWeb || ServerSession.cookie != null,
|
signedIn: kIsWeb || ServerSession.cookie != null,
|
||||||
|
detached: detached,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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('=', '');
|
||||||
|
}
|
||||||
@@ -57,7 +57,12 @@ import 'app_terminals.dart';
|
|||||||
import '../features/chat/chat_run_opener.dart';
|
import '../features/chat/chat_run_opener.dart';
|
||||||
import '../features/chat/chat_runtime.dart';
|
import '../features/chat/chat_runtime.dart';
|
||||||
import '../features/chat/data/chat_recency.dart';
|
import '../features/chat/data/chat_recency.dart';
|
||||||
|
import '../features/changes/domain/file_change.dart';
|
||||||
import '../features/changes/windows/diff_windows.dart';
|
import '../features/changes/windows/diff_windows.dart';
|
||||||
|
import '../shell/detached/detached_window_scope.dart';
|
||||||
|
import 'detached/detached_platform.dart';
|
||||||
|
import 'detached/detached_route.dart';
|
||||||
|
import 'detached/detached_windows.dart';
|
||||||
import '../features/chat/windows/chat_windows.dart';
|
import '../features/chat/windows/chat_windows.dart';
|
||||||
import 'open_in_chat.dart';
|
import 'open_in_chat.dart';
|
||||||
import 'send_to_chat.dart';
|
import 'send_to_chat.dart';
|
||||||
@@ -119,10 +124,14 @@ class PipelinesApp extends StatefulWidget {
|
|||||||
this.tabLocationsStore,
|
this.tabLocationsStore,
|
||||||
this.terminalLayout,
|
this.terminalLayout,
|
||||||
this.windows,
|
this.windows,
|
||||||
|
this.detachedPlatform,
|
||||||
});
|
});
|
||||||
|
|
||||||
final TabLocationsStore? tabLocationsStore;
|
final TabLocationsStore? tabLocationsStore;
|
||||||
|
|
||||||
|
/// How items open in windows of their own; the platform's when null.
|
||||||
|
final DetachedPlatform? detachedPlatform;
|
||||||
|
|
||||||
/// 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;
|
||||||
|
|
||||||
@@ -330,6 +339,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
|||||||
late final DiffWindows _diffWindows;
|
late final DiffWindows _diffWindows;
|
||||||
late final ChatRuntime _chatRuntime;
|
late final ChatRuntime _chatRuntime;
|
||||||
late final ChatWindows _chatWindows;
|
late final ChatWindows _chatWindows;
|
||||||
|
late final DetachedWindows _detached;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
@@ -391,6 +401,11 @@ class _PipelinesAppState extends State<PipelinesApp>
|
|||||||
windows: _windows,
|
windows: _windows,
|
||||||
);
|
);
|
||||||
_diffWindows = DiffWindows(_windows)..start();
|
_diffWindows = DiffWindows(_windows)..start();
|
||||||
|
_detached = DetachedWindows(
|
||||||
|
platform: widget.detachedPlatform,
|
||||||
|
onReturn: _detachedReturned,
|
||||||
|
)..start();
|
||||||
|
if (_detached.supported) _chatWindows.detached = _detached;
|
||||||
// Every kind is registered: saved windows can be restored. Then the
|
// Every kind is registered: saved windows can be restored. Then the
|
||||||
// terminal may open its window, and the floating chats an older build
|
// terminal may open its window, and the floating chats an older build
|
||||||
// saved are brought over once.
|
// saved are brought over once.
|
||||||
@@ -656,6 +671,7 @@ class _PipelinesAppState extends State<PipelinesApp>
|
|||||||
_session.removeListener(_chatSyncChanged);
|
_session.removeListener(_chatSyncChanged);
|
||||||
_session.removeListener(_learnServerHostname);
|
_session.removeListener(_learnServerHostname);
|
||||||
widget.chatPool?.removeListener(_chatSyncChanged);
|
widget.chatPool?.removeListener(_chatSyncChanged);
|
||||||
|
_detached.dispose();
|
||||||
_chatWindows.dispose();
|
_chatWindows.dispose();
|
||||||
_diffWindows.dispose();
|
_diffWindows.dispose();
|
||||||
_chatRuntime.dispose();
|
_chatRuntime.dispose();
|
||||||
@@ -747,9 +763,12 @@ class _PipelinesAppState extends State<PipelinesApp>
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
// A chat's run card (show_run) opens the run's detail.
|
// A chat's run card (show_run) opens the run's detail.
|
||||||
|
final router = MyApp.router(routerConfig: _config);
|
||||||
final app = ChatRunOpener(
|
final app = ChatRunOpener(
|
||||||
openRun: _openRunFromChat,
|
openRun: _openRunFromChat,
|
||||||
child: MyApp.router(routerConfig: _config),
|
child: _detached.supported
|
||||||
|
? DetachedWindowScope(opener: _detached, child: router)
|
||||||
|
: router,
|
||||||
);
|
);
|
||||||
return widget.servers == null
|
return widget.servers == null
|
||||||
? app
|
? app
|
||||||
@@ -762,6 +781,26 @@ class _PipelinesAppState extends State<PipelinesApp>
|
|||||||
|
|
||||||
void _openRunFromChat(int id) => _delegate.goTo(AppRoute.run(id));
|
void _openRunFromChat(int id) => _delegate.goTo(AppRoute.run(id));
|
||||||
|
|
||||||
|
/// A detached window gave its item back ("Bring back to main window").
|
||||||
|
void _detachedReturned(DetachedReturn item) {
|
||||||
|
if (!mounted) return;
|
||||||
|
switch (item.kind) {
|
||||||
|
case DetachedKind.chat:
|
||||||
|
_chatWindows.bringBack(item.id);
|
||||||
|
case DetachedKind.terminal:
|
||||||
|
_terminals.bringBack(item.id);
|
||||||
|
case DetachedKind.diff:
|
||||||
|
final files = [
|
||||||
|
for (final file in item.files) ?FileChange.fromHandover(file),
|
||||||
|
];
|
||||||
|
if (files.isEmpty) return;
|
||||||
|
_diffWindows.open(
|
||||||
|
files,
|
||||||
|
initialIndex: item.initialIndex.clamp(0, files.length - 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Open a result through the exact identity the hit records. An unresolvable
|
/// Open a result through the exact identity the hit records. An unresolvable
|
||||||
/// hit navigates nowhere: the screen already presents it read-only rather than
|
/// hit navigates nowhere: the screen already presents it read-only rather than
|
||||||
/// guessing a destination.
|
/// guessing a destination.
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ import '../features/settings/settings_store.dart';
|
|||||||
import '../ui/scale/ui_scale.dart';
|
import '../ui/scale/ui_scale.dart';
|
||||||
import '../ui/theme/app_font_controller.dart';
|
import '../ui/theme/app_font_controller.dart';
|
||||||
import '../ui/theme/app_theme.dart';
|
import '../ui/theme/app_theme.dart';
|
||||||
|
import 'detached/detached_app.dart';
|
||||||
|
import 'detached/detached_route.dart';
|
||||||
import 'pipelines_app.dart';
|
import 'pipelines_app.dart';
|
||||||
import 'server_endpoint.dart';
|
import 'server_endpoint.dart';
|
||||||
|
|
||||||
@@ -38,8 +40,12 @@ class PipelinesRoot extends StatefulWidget {
|
|||||||
this.nativeUpdatesSupported,
|
this.nativeUpdatesSupported,
|
||||||
this.federatedChats = true,
|
this.federatedChats = true,
|
||||||
this.chatPoolFactory,
|
this.chatPoolFactory,
|
||||||
|
this.detached,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/// The detached window this launch shows instead of the whole app.
|
||||||
|
final DetachedRoute? detached;
|
||||||
|
|
||||||
final ServerEndpoint server;
|
final ServerEndpoint server;
|
||||||
|
|
||||||
/// The server this build was made for; it pre-fills onboarding.
|
/// The server this build was made for; it pre-fills onboarding.
|
||||||
@@ -321,6 +327,20 @@ class _PipelinesRootState extends State<PipelinesRoot> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (!_onboarding && widget.detached != null) {
|
||||||
|
return DetachedWindowApp(
|
||||||
|
key: ValueKey(_generation),
|
||||||
|
route: widget.detached!,
|
||||||
|
server: _server,
|
||||||
|
client: _client,
|
||||||
|
chatPool: _chatPool,
|
||||||
|
servers: _servers,
|
||||||
|
serverId: _servers.catalog.active?.id,
|
||||||
|
serverAddresses: widget.web
|
||||||
|
? null
|
||||||
|
: _servers.catalog.active?.endpoints.map(Uri.parse).toList(),
|
||||||
|
);
|
||||||
|
}
|
||||||
if (!_onboarding) {
|
if (!_onboarding) {
|
||||||
return PipelinesApp(
|
return PipelinesApp(
|
||||||
androidSupported: widget.nativeUpdatesSupported,
|
androidSupported: widget.nativeUpdatesSupported,
|
||||||
|
|||||||
@@ -1,18 +1,25 @@
|
|||||||
import 'package:file_picker/file_picker.dart';
|
import 'package:file_picker/file_picker.dart';
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:share_plus/share_plus.dart';
|
import 'package:share_plus/share_plus.dart';
|
||||||
|
|
||||||
import 'artifact_file.dart';
|
import 'artifact_file.dart';
|
||||||
import 'artifact_transfer.dart';
|
import 'artifact_transfer.dart';
|
||||||
|
|
||||||
/// Phones and desktops: Download asks where to save the exact bytes (the
|
/// Phones and desktops: Download asks where to save the exact bytes (the
|
||||||
/// system "Save as"), Share hands the named file to the share sheet.
|
/// system "Save as"; on Linux the desktop portal's file chooser), Share hands
|
||||||
|
/// the named file to the share sheet. Linux has no share sheet for files
|
||||||
|
/// (share_plus throws), so Share is not offered there.
|
||||||
bool get artifactDownloadSupported => true;
|
bool get artifactDownloadSupported => true;
|
||||||
|
|
||||||
bool get artifactShareSupported => true;
|
bool get artifactShareSupported =>
|
||||||
|
defaultTargetPlatform != TargetPlatform.linux;
|
||||||
|
|
||||||
String get artifactDownloadUnsupportedMessage => '';
|
String get artifactDownloadUnsupportedMessage => '';
|
||||||
|
|
||||||
String get artifactShareUnsupportedMessage => '';
|
String get artifactShareUnsupportedMessage =>
|
||||||
|
defaultTargetPlatform == TargetPlatform.linux
|
||||||
|
? 'Sharing files is not available on Linux; use Download.'
|
||||||
|
: '';
|
||||||
|
|
||||||
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async {
|
Future<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -12,6 +12,18 @@ import 'artifact_external_open.dart';
|
|||||||
/// the full-screen view needs no zoom buttons.
|
/// the full-screen view needs no zoom buttons.
|
||||||
const bool inertHtmlZoomButtons = false;
|
const bool inertHtmlZoomButtons = false;
|
||||||
|
|
||||||
|
/// The webview plugin has Android, iOS and macOS implementations only; the
|
||||||
|
/// Linux and Windows apps say so instead of failing to create a web view.
|
||||||
|
bool inertHtmlViewSupported([TargetPlatform? platform]) => switch (platform ??
|
||||||
|
defaultTargetPlatform) {
|
||||||
|
TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.macOS => true,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const String inertHtmlUnsupportedMessage =
|
||||||
|
'This app cannot preview HTML on this platform: it has no web view. '
|
||||||
|
'Download the file to open it in a browser.';
|
||||||
|
|
||||||
/// A web view with JavaScript disabled that refuses every navigation after the
|
/// A web view with JavaScript disabled that refuses every navigation after the
|
||||||
/// recorded document itself loads.
|
/// recorded document itself loads.
|
||||||
///
|
///
|
||||||
@@ -99,6 +111,7 @@ class _InertHtmlViewState extends State<InertHtmlView> {
|
|||||||
@override
|
@override
|
||||||
void didUpdateWidget(covariant InertHtmlView oldWidget) {
|
void didUpdateWidget(covariant InertHtmlView oldWidget) {
|
||||||
super.didUpdateWidget(oldWidget);
|
super.didUpdateWidget(oldWidget);
|
||||||
|
if (!inertHtmlViewSupported()) return;
|
||||||
if (oldWidget.html != widget.html || oldWidget.dark != widget.dark) {
|
if (oldWidget.html != widget.html || oldWidget.dark != widget.dark) {
|
||||||
_loaded = false;
|
_loaded = false;
|
||||||
_controller.loadHtmlString(_document);
|
_controller.loadHtmlString(_document);
|
||||||
@@ -106,8 +119,20 @@ class _InertHtmlViewState extends State<InertHtmlView> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) => WebViewWidget(
|
Widget build(BuildContext context) => inertHtmlViewSupported()
|
||||||
controller: _controller,
|
? WebViewWidget(
|
||||||
gestureRecognizers: widget.interactive ? _allGestures : _inlineGestures,
|
controller: _controller,
|
||||||
);
|
gestureRecognizers: widget.interactive
|
||||||
|
? _allGestures
|
||||||
|
: _inlineGestures,
|
||||||
|
)
|
||||||
|
: const Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.all(16),
|
||||||
|
child: Text(
|
||||||
|
inertHtmlUnsupportedMessage,
|
||||||
|
textAlign: TextAlign.center,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||||
|
|
||||||
import 'notification_bridge.dart';
|
import 'notification_bridge.dart';
|
||||||
@@ -7,8 +8,10 @@ import 'notification_models.dart';
|
|||||||
|
|
||||||
/// System notifications from the native app: Android's notification shade (when
|
/// System notifications from the native app: Android's notification shade (when
|
||||||
/// its background notification service is off), iOS's and macOS's
|
/// its background notification service is off), iOS's and macOS's
|
||||||
/// notification centre. [close] removes a delivered one by its tag. The permission is cached so [environment] stays synchronous; it
|
/// notification centre, and the Linux desktop's notification daemon (the
|
||||||
/// is refreshed when the bridge starts and after every request.
|
/// freedesktop D-Bus service: mako, dunst, GNOME Shell, Plasma). [close]
|
||||||
|
/// removes a delivered one by its tag. The permission is cached so
|
||||||
|
/// [environment] stays synchronous; it is refreshed when the bridge starts and after every request.
|
||||||
class NativeNotificationBridge implements NotificationBridge {
|
class NativeNotificationBridge implements NotificationBridge {
|
||||||
NativeNotificationBridge() {
|
NativeNotificationBridge() {
|
||||||
_ready = _start();
|
_ready = _start();
|
||||||
@@ -40,13 +43,27 @@ class NativeNotificationBridge implements NotificationBridge {
|
|||||||
requestSoundPermission: false,
|
requestSoundPermission: false,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/// The bundle's icon (installed by the Linux runner's CMake beside
|
||||||
|
/// `flutter_assets`), so a portable, uninstalled bundle has one too.
|
||||||
|
static final _linuxSettings = LinuxInitializationSettings(
|
||||||
|
defaultActionName: 'Open',
|
||||||
|
defaultIcon: FilePathLinuxIcon(
|
||||||
|
'${File(Platform.resolvedExecutable).parent.path}/data/app_icon.png',
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// The Linux app, by its target platform rather than the host's, so a test
|
||||||
|
/// on a Linux machine still sees the (Android) test platform.
|
||||||
|
static bool get _linux => defaultTargetPlatform == TargetPlatform.linux;
|
||||||
|
|
||||||
Future<void> _start() async {
|
Future<void> _start() async {
|
||||||
try {
|
try {
|
||||||
await _plugin.initialize(
|
await _plugin.initialize(
|
||||||
settings: const InitializationSettings(
|
settings: InitializationSettings(
|
||||||
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
android: AndroidInitializationSettings('@mipmap/ic_launcher'),
|
||||||
iOS: _darwin,
|
iOS: _darwin,
|
||||||
macOS: _darwin,
|
macOS: _darwin,
|
||||||
|
linux: _linuxSettings,
|
||||||
),
|
),
|
||||||
onDidReceiveNotificationResponse: (response) {
|
onDidReceiveNotificationResponse: (response) {
|
||||||
final id = response.id;
|
final id = response.id;
|
||||||
@@ -63,7 +80,10 @@ class NativeNotificationBridge implements NotificationBridge {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _refresh() async {
|
Future<void> _refresh() async {
|
||||||
if (Platform.isAndroid) {
|
if (_linux) {
|
||||||
|
// A notification daemon asks no permission.
|
||||||
|
_permission = 'granted';
|
||||||
|
} else if (Platform.isAndroid) {
|
||||||
final enabled = await _plugin
|
final enabled = await _plugin
|
||||||
.resolvePlatformSpecificImplementation<
|
.resolvePlatformSpecificImplementation<
|
||||||
AndroidFlutterLocalNotificationsPlugin
|
AndroidFlutterLocalNotificationsPlugin
|
||||||
@@ -82,7 +102,8 @@ class NativeNotificationBridge implements NotificationBridge {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
NotificationEnvironment environment() => NotificationEnvironment(
|
NotificationEnvironment environment() => NotificationEnvironment(
|
||||||
supported: Platform.isAndroid || Platform.isIOS || Platform.isMacOS,
|
supported:
|
||||||
|
Platform.isAndroid || Platform.isIOS || Platform.isMacOS || _linux,
|
||||||
// A native app needs no secure origin.
|
// A native app needs no secure origin.
|
||||||
secureContext: true,
|
secureContext: true,
|
||||||
permission: _permission,
|
permission: _permission,
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ String? noPatchReasonMessage(String? reason) => switch (reason) {
|
|||||||
'budget' =>
|
'budget' =>
|
||||||
'The workspace snapshot ran out of text budget, so no diff text was '
|
'The workspace snapshot ran out of text budget, so no diff text was '
|
||||||
'recorded.',
|
'recorded.',
|
||||||
'lines' => 'The change is over 5,000 lines, so no diff text was recorded.',
|
'lines' => 'The change is over 20,000 lines, so no diff text was recorded.',
|
||||||
'evidence_size' =>
|
'evidence_size' =>
|
||||||
"This visit's recorded changes reached their size limit, so this patch "
|
"This visit's recorded changes reached their size limit, so this patch "
|
||||||
'was dropped.',
|
'was dropped.',
|
||||||
@@ -121,6 +121,15 @@ String? noPatchReasonMessage(String? reason) => switch (reason) {
|
|||||||
'baseline' =>
|
'baseline' =>
|
||||||
"The file's content at stage start couldn't be recovered from Git, so no "
|
"The file's content at stage start couldn't be recovered from Git, so no "
|
||||||
'diff was recorded.',
|
'diff was recorded.',
|
||||||
|
'symlink' => 'Symbolic link; only the change to its target was recorded.',
|
||||||
|
'protected' =>
|
||||||
|
'A protected file (secrets, credentials or a database); its content is '
|
||||||
|
'never read, only that it changed.',
|
||||||
|
'generated' =>
|
||||||
|
'A lockfile, minified or generated file; it is listed without a diff.',
|
||||||
|
'large' =>
|
||||||
|
'This file is too large to hash, so it was compared by size and '
|
||||||
|
'modification time only.',
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -36,8 +36,10 @@ class FileChange {
|
|||||||
final bool truncated;
|
final bool truncated;
|
||||||
|
|
||||||
/// Why the server recorded no (complete) patch: `binary`, `file_size`,
|
/// Why the server recorded no (complete) patch: `binary`, `file_size`,
|
||||||
/// `budget`, `lines`, `evidence_size`, `git_status` or `baseline`. Null from
|
/// `budget`, `lines`, `evidence_size`, `git_status`, `baseline`, `symlink`,
|
||||||
/// an older server or when a patch was recorded.
|
/// `protected` (content never read), `generated` (lockfile/minified) or
|
||||||
|
/// `large` (compared by size and mtime only). Null from an older server or
|
||||||
|
/// when a patch was recorded; an unknown value gets the generic wording.
|
||||||
final String? noPatchReason;
|
final String? noPatchReason;
|
||||||
final String? beforeMode;
|
final String? beforeMode;
|
||||||
final String? afterMode;
|
final String? afterMode;
|
||||||
@@ -82,6 +84,30 @@ class FileChange {
|
|||||||
parsedPatch: parsedPatch,
|
parsedPatch: parsedPatch,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/// The entry as the server records it ([tryParse] reads it back), with
|
||||||
|
/// the stages that touched it, so a diff can be handed to another window.
|
||||||
|
Map<String, Object?> toJson() => {
|
||||||
|
'path': path,
|
||||||
|
'kind': kind.name,
|
||||||
|
'patch': ?patch,
|
||||||
|
if (binary) 'binary': true,
|
||||||
|
if (truncated) 'truncated': true,
|
||||||
|
'no_patch_reason': ?noPatchReason,
|
||||||
|
'before_mode': ?beforeMode,
|
||||||
|
'after_mode': ?afterMode,
|
||||||
|
if (steps.isNotEmpty) 'steps': steps,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Reads back an entry [toJson] wrote, stages included.
|
||||||
|
static FileChange? fromHandover(Object? value) {
|
||||||
|
final file = tryParse(value);
|
||||||
|
if (file == null || value is! Map) return file;
|
||||||
|
final steps = value['steps'];
|
||||||
|
return steps is List && steps.isNotEmpty
|
||||||
|
? file.withSteps([for (final step in steps) '$step'])
|
||||||
|
: file;
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses one server file entry; null when it has no usable path. The
|
/// Parses one server file entry; null when it has no usable path. The
|
||||||
/// capture owns the decision to skip such an entry, so it is never rendered
|
/// capture owns the decision to skip such an entry, so it is never rendered
|
||||||
/// as an anonymous row.
|
/// as an anonymous row.
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import 'diff_search_bar.dart';
|
|||||||
import 'diff_search_controller.dart';
|
import 'diff_search_controller.dart';
|
||||||
import 'file_diff_viewer.dart';
|
import 'file_diff_viewer.dart';
|
||||||
import 'stacked_diff_view.dart';
|
import 'stacked_diff_view.dart';
|
||||||
|
import '../../../shell/detached/detached_window_scope.dart';
|
||||||
|
import '../../../shell/windows/window_scope.dart';
|
||||||
import '../windows/diff_windows.dart';
|
import '../windows/diff_windows.dart';
|
||||||
|
|
||||||
/// Whether diff pages show every file stacked (GitHub's Files changed) rather
|
/// Whether diff pages show every file stacked (GitHub's Files changed) rather
|
||||||
@@ -54,6 +56,7 @@ class FileDiffPage extends StatefulWidget {
|
|||||||
required this.files,
|
required this.files,
|
||||||
this.initialIndex = 0,
|
this.initialIndex = 0,
|
||||||
this.inWindow = false,
|
this.inWindow = false,
|
||||||
|
this.actions = const [],
|
||||||
});
|
});
|
||||||
|
|
||||||
final List<FileChange> files;
|
final List<FileChange> files;
|
||||||
@@ -62,6 +65,10 @@ class FileDiffPage extends StatefulWidget {
|
|||||||
/// Shown inside a floating window: no Back, and no Open in a window.
|
/// Shown inside a floating window: no Back, and no Open in a window.
|
||||||
final bool inWindow;
|
final bool inWindow;
|
||||||
|
|
||||||
|
/// The host's own bar buttons, after the diff's (a detached window's
|
||||||
|
/// Bring back).
|
||||||
|
final List<Widget> actions;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<FileDiffPage> createState() => _FileDiffPageState();
|
State<FileDiffPage> createState() => _FileDiffPageState();
|
||||||
}
|
}
|
||||||
@@ -184,6 +191,25 @@ class _FileDiffPageState extends State<FileDiffPage> {
|
|||||||
windows.open(widget.files, initialIndex: _index);
|
windows.open(widget.files, initialIndex: _index);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sends the diff to a window of its own; once it opens, this page closes
|
||||||
|
/// (or the floating window it is in).
|
||||||
|
void _openInNewWindow(DetachedWindowOpener opener, String title) {
|
||||||
|
final window = WindowScope.maybeOf(context);
|
||||||
|
opener.openDiff(
|
||||||
|
[for (final file in widget.files) file.toJson()],
|
||||||
|
initialIndex: _index,
|
||||||
|
title: title,
|
||||||
|
onOpened: () {
|
||||||
|
if (!mounted) return;
|
||||||
|
if (window != null) {
|
||||||
|
window.manager.close(window.entry.id);
|
||||||
|
} else {
|
||||||
|
Navigator.of(context).maybePop();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
void _toggleFile(int index) => setState(() {
|
void _toggleFile(int index) => setState(() {
|
||||||
if (!_collapsed.remove(index)) _collapsed.add(index);
|
if (!_collapsed.remove(index)) _collapsed.add(index);
|
||||||
});
|
});
|
||||||
@@ -288,6 +314,13 @@ class _FileDiffPageState extends State<FileDiffPage> {
|
|||||||
),
|
),
|
||||||
null => null,
|
null => null,
|
||||||
},
|
},
|
||||||
|
if (DetachedWindowScope.maybeOf(context) case final opener?)
|
||||||
|
IconButton(
|
||||||
|
key: const ValueKey('diff-open-new-window'),
|
||||||
|
tooltip: detachedWindowLabel,
|
||||||
|
onPressed: () => _openInNewWindow(opener, title),
|
||||||
|
icon: const Icon(Icons.open_in_browser),
|
||||||
|
),
|
||||||
IconButton(
|
IconButton(
|
||||||
key: const ValueKey('diff-search-open'),
|
key: const ValueKey('diff-search-open'),
|
||||||
tooltip: 'Find in diff (/)',
|
tooltip: 'Find in diff (/)',
|
||||||
@@ -315,6 +348,7 @@ class _FileDiffPageState extends State<FileDiffPage> {
|
|||||||
_all ? Icons.article_outlined : Icons.view_agenda_outlined,
|
_all ? Icons.article_outlined : Icons.view_agenda_outlined,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
...widget.actions,
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
body: body,
|
body: body,
|
||||||
|
|||||||
@@ -25,6 +25,8 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
final pane = _workspace.activePane;
|
final pane = _workspace.activePane;
|
||||||
if (pane != null) _floatPane(pane.id);
|
if (pane != null) _floatPane(pane.id);
|
||||||
},
|
},
|
||||||
|
release: _releaseSession,
|
||||||
|
activeSession: () => _workspace.activePane?.sessionId,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,6 +68,19 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [sessionId] went to a window of its own: its panes leave the tiling,
|
||||||
|
/// as a floated pane does, and the list shows when none is left.
|
||||||
|
void _releaseSession(String sessionId) {
|
||||||
|
if (!mounted) return;
|
||||||
|
final panes = _workspace.panes.where((p) => p.sessionId == sessionId);
|
||||||
|
if (panes.isEmpty) return;
|
||||||
|
for (final pane in panes.toList()) {
|
||||||
|
_workspace.detach(pane.id);
|
||||||
|
}
|
||||||
|
_syncOpenWorkspace();
|
||||||
|
if (_workspace.paneCount == 0) _back();
|
||||||
|
}
|
||||||
|
|
||||||
void _dockSession(String sessionId) {
|
void _dockSession(String sessionId) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
_workspaceVisible = true;
|
_workspaceVisible = true;
|
||||||
@@ -75,15 +90,25 @@ mixin _ChatScreenFloat on State<ChatScreen>, _ChatScreenWorkspace {
|
|||||||
_composerFocus.request(sessionId);
|
_composerFocus.request(sessionId);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The pane menu's Float choice, on a tiled pane that can.
|
/// The pane menu's Float choice, on a tiled pane that can, and Open in
|
||||||
|
/// new window where the platform has windows.
|
||||||
List<Widget> _floatControls(ChatWorkspacePane pane) {
|
List<Widget> _floatControls(ChatWorkspacePane pane) {
|
||||||
if (!_floatsHere || !_workspace.canFloat(pane.id)) return const [];
|
final windows = widget.windows;
|
||||||
|
if (windows == null || !_workspace.canFloat(pane.id)) return const [];
|
||||||
return [
|
return [
|
||||||
ChatBarAction(
|
if (_floatsHere)
|
||||||
label: 'Float (${chatFloatShortcutLabel()})',
|
ChatBarAction(
|
||||||
onPressed: () => _floatPane(pane.id),
|
label: 'Float (${chatFloatShortcutLabel()})',
|
||||||
materialIcon: Icons.picture_in_picture_alt_outlined,
|
onPressed: () => _floatPane(pane.id),
|
||||||
),
|
materialIcon: Icons.picture_in_picture_alt_outlined,
|
||||||
|
),
|
||||||
|
if (windows.detached != null)
|
||||||
|
ChatBarAction(
|
||||||
|
label: detachedChatWindowLabel(),
|
||||||
|
identifier: 'chat-open-new-window',
|
||||||
|
onPressed: () => windows.detach(pane.sessionId),
|
||||||
|
materialIcon: Icons.open_in_browser,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,6 +43,12 @@ mixin _ChatScreenPaneMenu on State<ChatScreen>, _ChatScreenWorkspace
|
|||||||
final moves = pane == null ? null : _paneMoveTargets[pane.id];
|
final moves = pane == null ? null : _paneMoveTargets[pane.id];
|
||||||
final directory = '${session['directory'] ?? ''}'.trim();
|
final directory = '${session['directory'] ?? ''}'.trim();
|
||||||
return [
|
return [
|
||||||
|
if (widget.windows?.detached != null)
|
||||||
|
(
|
||||||
|
action: SessionPaneAction.newWindow,
|
||||||
|
label: detachedChatWindowLabel(),
|
||||||
|
enabled: true,
|
||||||
|
),
|
||||||
(
|
(
|
||||||
action: SessionPaneAction.addPane,
|
action: SessionPaneAction.addPane,
|
||||||
label: 'Add chat pane',
|
label: 'Add chat pane',
|
||||||
@@ -97,6 +103,8 @@ mixin _ChatScreenPaneMenu on State<ChatScreen>, _ChatScreenWorkspace
|
|||||||
final id = '${session['id'] ?? ''}';
|
final id = '${session['id'] ?? ''}';
|
||||||
if (id.isEmpty) return;
|
if (id.isEmpty) return;
|
||||||
switch (action) {
|
switch (action) {
|
||||||
|
case SessionPaneAction.newWindow:
|
||||||
|
widget.windows?.detach(id);
|
||||||
case SessionPaneAction.addPane:
|
case SessionPaneAction.addPane:
|
||||||
_openBySelection(session);
|
_openBySelection(session);
|
||||||
_addPane(context);
|
_addPane(context);
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import 'package:flutter/widgets.dart';
|
|||||||
import 'chat_attachment_picker.dart';
|
import 'chat_attachment_picker.dart';
|
||||||
import 'chat_clipboard_paste.dart';
|
import 'chat_clipboard_paste.dart';
|
||||||
|
|
||||||
/// The macOS Runner's pasteboard reader (macos/Runner/MainFlutterWindow.swift).
|
/// The desktop Runners' clipboard reader: macOS's
|
||||||
|
/// (macos/Runner/MainFlutterWindow.swift) and Linux's
|
||||||
|
/// (linux/runner/clipboard_files.cc).
|
||||||
const MethodChannel chatClipboardFilesChannel = MethodChannel(
|
const MethodChannel chatClipboardFilesChannel = MethodChannel(
|
||||||
'pipelines/clipboard_files',
|
'pipelines/clipboard_files',
|
||||||
);
|
);
|
||||||
@@ -17,7 +19,7 @@ const MethodChannel chatClipboardFilesChannel = MethodChannel(
|
|||||||
///
|
///
|
||||||
/// Flutter's own [Clipboard] carries text only, so a native host reads the
|
/// Flutter's own [Clipboard] carries text only, so a native host reads the
|
||||||
/// pasteboard through the Runner. Each subscription watches for the platform
|
/// pasteboard through the Runner. Each subscription watches for the platform
|
||||||
/// paste shortcut (Cmd+V). When its composer may take the paste it consumes
|
/// paste shortcut (Cmd+V on macOS, Ctrl+V on Linux). When its composer may take the paste it consumes
|
||||||
/// the key, asks the Runner for the pasteboard's files (Finder file URLs, else
|
/// the key, asks the Runner for the pasteboard's files (Finder file URLs, else
|
||||||
/// a copied or screenshot image) and hands them over; a pasteboard without
|
/// a copied or screenshot image) and hands them over; a pasteboard without
|
||||||
/// files pastes its text into the composer instead, so the consumed key never
|
/// files pastes its text into the composer instead, so the consumed key never
|
||||||
@@ -46,13 +48,14 @@ ChatClipboardPaste nativeChatClipboardPaste({
|
|||||||
);
|
);
|
||||||
|
|
||||||
/// Whether the held modifiers make V the host's paste shortcut: Cmd alone on
|
/// Whether the held modifiers make V the host's paste shortcut: Cmd alone on
|
||||||
/// macOS.
|
/// macOS; Ctrl on Linux, also with Super held (Omarchy's universal Super+V
|
||||||
bool chatIsNativePasteShortcut() {
|
/// sends Ctrl+V while Super is down).
|
||||||
|
bool chatIsNativePasteShortcut([TargetPlatform? platform]) {
|
||||||
final keys = HardwareKeyboard.instance;
|
final keys = HardwareKeyboard.instance;
|
||||||
return keys.isMetaPressed &&
|
if (keys.isAltPressed || keys.isShiftPressed) return false;
|
||||||
!keys.isControlPressed &&
|
return (platform ?? defaultTargetPlatform) == TargetPlatform.linux
|
||||||
!keys.isAltPressed &&
|
? keys.isControlPressed
|
||||||
!keys.isShiftPressed;
|
: keys.isMetaPressed && !keys.isControlPressed;
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _readPasteboard(
|
Future<void> _readPasteboard(
|
||||||
@@ -121,4 +124,5 @@ String chatNothingToPasteMessage(List<String> types) => types.isEmpty
|
|||||||
|
|
||||||
/// Whether [platform] has a Runner that answers [chatClipboardFilesChannel].
|
/// Whether [platform] has a Runner that answers [chatClipboardFilesChannel].
|
||||||
bool chatHostReadsClipboardFiles(TargetPlatform platform) =>
|
bool chatHostReadsClipboardFiles(TargetPlatform platform) =>
|
||||||
!kIsWeb && platform == TargetPlatform.macOS;
|
!kIsWeb &&
|
||||||
|
(platform == TargetPlatform.macOS || platform == TargetPlatform.linux);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import 'chat_clipboard_paste_native.dart';
|
|||||||
|
|
||||||
/// Native clipboard-file paste.
|
/// Native clipboard-file paste.
|
||||||
///
|
///
|
||||||
/// macOS reads the pasteboard through its Runner
|
/// macOS and Linux read the clipboard through their Runners
|
||||||
/// ([nativeChatClipboardPaste]). Other native hosts have no pasteboard reader
|
/// ([nativeChatClipboardPaste]). Other native hosts have no pasteboard reader
|
||||||
/// yet: they report that missing capability rather than pretending no paste
|
/// yet: they report that missing capability rather than pretending no paste
|
||||||
/// happened, and the composer keeps the host field's own text paste.
|
/// happened, and the composer keeps the host field's own text paste.
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import 'package:flutter/services.dart';
|
|||||||
import '../../core/api_gateway.dart';
|
import '../../core/api_gateway.dart';
|
||||||
import '../../core/servers/server_context.dart';
|
import '../../core/servers/server_context.dart';
|
||||||
import '../../core/servers/server_scope.dart';
|
import '../../core/servers/server_scope.dart';
|
||||||
|
import '../../shell/detached/detached_window_scope.dart';
|
||||||
import '../../shell/windows/window_scope.dart';
|
import '../../shell/windows/window_scope.dart';
|
||||||
import 'shell/chat_shell_dismiss.dart';
|
import 'shell/chat_shell_dismiss.dart';
|
||||||
import '../terminal/terminal_open_action.dart';
|
import '../terminal/terminal_open_action.dart';
|
||||||
|
|||||||
@@ -105,6 +105,7 @@ class SessionActionsButton extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
IconData _paneIcon(SessionPaneAction action) => switch (action) {
|
IconData _paneIcon(SessionPaneAction action) => switch (action) {
|
||||||
|
SessionPaneAction.newWindow => Icons.open_in_browser,
|
||||||
SessionPaneAction.addPane => Icons.add_box_outlined,
|
SessionPaneAction.addPane => Icons.add_box_outlined,
|
||||||
SessionPaneAction.openChats => Icons.view_quilt_outlined,
|
SessionPaneAction.openChats => Icons.view_quilt_outlined,
|
||||||
SessionPaneAction.centerStage => Icons.center_focus_strong_outlined,
|
SessionPaneAction.centerStage => Icons.center_focus_strong_outlined,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import '../../../../core/api_gateway.dart';
|
|||||||
|
|
||||||
/// The pane More menu's choices that a chat row's menu also offers.
|
/// The pane More menu's choices that a chat row's menu also offers.
|
||||||
enum SessionPaneAction {
|
enum SessionPaneAction {
|
||||||
|
newWindow,
|
||||||
addPane,
|
addPane,
|
||||||
openChats,
|
openChats,
|
||||||
centerStage,
|
centerStage,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
|
|||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
import '../../../core/api_gateway.dart';
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../../../shell/detached/detached_window_scope.dart';
|
||||||
import '../../../shell/list_detail_policy.dart';
|
import '../../../shell/list_detail_policy.dart';
|
||||||
import '../../../shell/windows/window_entry.dart';
|
import '../../../shell/windows/window_entry.dart';
|
||||||
import '../../../shell/windows/window_kind.dart';
|
import '../../../shell/windows/window_kind.dart';
|
||||||
@@ -25,6 +26,8 @@ class ChatTiling {
|
|||||||
required this.dock,
|
required this.dock,
|
||||||
required this.canFloatActive,
|
required this.canFloatActive,
|
||||||
required this.floatActive,
|
required this.floatActive,
|
||||||
|
this.release,
|
||||||
|
this.activeSession,
|
||||||
});
|
});
|
||||||
|
|
||||||
/// Whether the tiling shows [sessionId].
|
/// Whether the tiling shows [sessionId].
|
||||||
@@ -36,6 +39,13 @@ class ChatTiling {
|
|||||||
/// Whether the chord can float the active pane now.
|
/// Whether the chord can float the active pane now.
|
||||||
final bool Function() canFloatActive;
|
final bool Function() canFloatActive;
|
||||||
final VoidCallback floatActive;
|
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
|
/// The floating chat windows, for the app's lifetime: the `chat` window kind
|
||||||
@@ -66,6 +76,10 @@ class ChatWindows {
|
|||||||
/// The mounted Chat destination's tiling, if it is built.
|
/// The mounted Chat destination's tiling, if it is built.
|
||||||
ChatTiling? tiling;
|
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);
|
late final ChatWindowKind kind = ChatWindowKind(this);
|
||||||
bool _started = false;
|
bool _started = false;
|
||||||
|
|
||||||
@@ -86,7 +100,8 @@ class ChatWindows {
|
|||||||
manager.kinds.register(kind);
|
manager.kinds.register(kind);
|
||||||
FocusManager.instance
|
FocusManager.instance
|
||||||
..addEarlyKeyEventHandler(_key)
|
..addEarlyKeyEventHandler(_key)
|
||||||
..addEarlyKeyEventHandler(_tabKey);
|
..addEarlyKeyEventHandler(_tabKey)
|
||||||
|
..addEarlyKeyEventHandler(_detachKey);
|
||||||
runtime.addSessionReplacedListener(_replacedElsewhere);
|
runtime.addSessionReplacedListener(_replacedElsewhere);
|
||||||
runtime.sessions.addListener(_rowsChanged);
|
runtime.sessions.addListener(_rowsChanged);
|
||||||
manager.addListener(_rowsChanged);
|
manager.addListener(_rowsChanged);
|
||||||
@@ -98,7 +113,8 @@ class ChatWindows {
|
|||||||
_started = false;
|
_started = false;
|
||||||
FocusManager.instance
|
FocusManager.instance
|
||||||
..removeEarlyKeyEventHandler(_key)
|
..removeEarlyKeyEventHandler(_key)
|
||||||
..removeEarlyKeyEventHandler(_tabKey);
|
..removeEarlyKeyEventHandler(_tabKey)
|
||||||
|
..removeEarlyKeyEventHandler(_detachKey);
|
||||||
runtime.removeSessionReplacedListener(_replacedElsewhere);
|
runtime.removeSessionReplacedListener(_replacedElsewhere);
|
||||||
runtime.sessions.removeListener(_rowsChanged);
|
runtime.sessions.removeListener(_rowsChanged);
|
||||||
manager.removeListener(_rowsChanged);
|
manager.removeListener(_rowsChanged);
|
||||||
@@ -154,6 +170,35 @@ class ChatWindows {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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
|
/// `/new` in a window's chat: the window follows the new session, unless
|
||||||
/// that session is already open elsewhere.
|
/// that session is already open elsewhere.
|
||||||
void startedNewSession(
|
void startedNewSession(
|
||||||
@@ -242,6 +287,29 @@ class ChatWindows {
|
|||||||
return KeyEventResult.handled;
|
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
|
/// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the
|
||||||
/// keyboard: the next (previous) shown chat window, in open order and
|
/// keyboard: the next (previous) shown chat window, in open order and
|
||||||
/// wrapping, comes to the top. The window host then gives it the keyboard,
|
/// wrapping, comes to the top. The window host then gives it the keyboard,
|
||||||
@@ -350,6 +418,12 @@ class ChatWindowKind extends WindowKind {
|
|||||||
icon: Icons.vertical_split_outlined,
|
icon: Icons.vertical_split_outlined,
|
||||||
onPressed: () => windows.dock(entry),
|
onPressed: () => windows.dock(entry),
|
||||||
),
|
),
|
||||||
|
if (windows.detached != null)
|
||||||
|
WindowAction(
|
||||||
|
label: detachedChatWindowLabel(),
|
||||||
|
icon: Icons.open_in_browser,
|
||||||
|
onPressed: () => windows.detach(entry.contentId),
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
@override
|
@override
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// The `check` stage type: a model-free stage that runs shell commands and
|
||||||
|
// routes `pass`/`fail` (plus `error`). Its `delivery` config marks the landing
|
||||||
|
// gate, which runs the commands in a fresh worktree and fast-forwards main on
|
||||||
|
// pass. Pure data only; an older graph simply has no check stages.
|
||||||
|
|
||||||
|
/// The stage type word the server uses for a check stage.
|
||||||
|
const String checkStageType = 'check';
|
||||||
|
|
||||||
|
/// Whether [stage] (a graph stage declaration) is a check stage.
|
||||||
|
bool isCheckStage(dynamic stage) =>
|
||||||
|
stage is Map && '${stage['type'] ?? ''}'.trim() == checkStageType;
|
||||||
|
|
||||||
|
/// Whether a check [stage] is the delivery (landing) gate.
|
||||||
|
///
|
||||||
|
/// Configs are strings on the wire (`"true"`); a JSON boolean is accepted too.
|
||||||
|
bool isDeliveryGate(dynamic stage) {
|
||||||
|
if (!isCheckStage(stage)) return false;
|
||||||
|
final configs = (stage as Map)['configs'];
|
||||||
|
if (configs is! Map) return false;
|
||||||
|
final value = configs['delivery'];
|
||||||
|
return value == true || '${value ?? ''}'.trim().toLowerCase() == 'true';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The check stage's commands, one per non-blank line of `blocks.commands`
|
||||||
|
/// (a list of strings is read item by item), in declared order.
|
||||||
|
List<String> checkCommands(dynamic stage) {
|
||||||
|
if (stage is! Map) return const <String>[];
|
||||||
|
final blocks = stage['blocks'];
|
||||||
|
if (blocks is! Map) return const <String>[];
|
||||||
|
final raw = blocks['commands'];
|
||||||
|
final lines = raw is List
|
||||||
|
? [for (final item in raw) '${item ?? ''}']
|
||||||
|
: '${raw ?? ''}'.split('\n');
|
||||||
|
return [
|
||||||
|
for (final line in lines)
|
||||||
|
if (line.trim().isNotEmpty) line.trimRight(),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The short kind a graph node shows under its name: `Check` or
|
||||||
|
/// `Delivery gate`, or null for every other stage type.
|
||||||
|
String? checkStageCaption({required String type, required bool delivery}) {
|
||||||
|
if (type.trim() != checkStageType) return null;
|
||||||
|
return delivery ? 'Delivery gate' : 'Check';
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'check_stage.dart';
|
||||||
import 'graph_protocol.dart';
|
import 'graph_protocol.dart';
|
||||||
|
|
||||||
/// The graph definition: nodes and edges declared by a pipeline, never the
|
/// The graph definition: nodes and edges declared by a pipeline, never the
|
||||||
@@ -70,11 +71,27 @@ class GraphEdge {
|
|||||||
/// One graph definition node: a declared stage, or a terminal the definition
|
/// One graph definition node: a declared stage, or a terminal the definition
|
||||||
/// routes to.
|
/// routes to.
|
||||||
class GraphNode {
|
class GraphNode {
|
||||||
const GraphNode({required this.key, required this.terminal, this.stageIndex});
|
const GraphNode({
|
||||||
|
required this.key,
|
||||||
|
required this.terminal,
|
||||||
|
this.stageIndex,
|
||||||
|
this.type = '',
|
||||||
|
this.delivery = false,
|
||||||
|
});
|
||||||
|
|
||||||
final String key;
|
final String key;
|
||||||
final bool terminal;
|
final bool terminal;
|
||||||
|
|
||||||
|
/// The stage's declared `type` exactly as recorded (blank reads `model`);
|
||||||
|
/// empty for a terminal.
|
||||||
|
final String type;
|
||||||
|
|
||||||
|
/// Whether this is a check stage marked as the delivery gate.
|
||||||
|
final bool delivery;
|
||||||
|
|
||||||
|
/// `Check` or `Delivery gate` for a check stage, otherwise null.
|
||||||
|
String? get kindCaption => checkStageCaption(type: type, delivery: delivery);
|
||||||
|
|
||||||
/// The node's stage declaration index, or null for a terminal.
|
/// The node's stage declaration index, or null for a terminal.
|
||||||
final int? stageIndex;
|
final int? stageIndex;
|
||||||
|
|
||||||
@@ -142,7 +159,15 @@ List<GraphNode> graphNodes(dynamic graph) {
|
|||||||
for (var index = 0; index < stages.length; index += 1) {
|
for (var index = 0; index < stages.length; index += 1) {
|
||||||
final key = _stageKey(stages[index]);
|
final key = _stageKey(stages[index]);
|
||||||
if (key.isEmpty || !seen.add(key)) continue;
|
if (key.isEmpty || !seen.add(key)) continue;
|
||||||
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index));
|
nodes.add(
|
||||||
|
GraphNode(
|
||||||
|
key: key,
|
||||||
|
terminal: false,
|
||||||
|
stageIndex: index,
|
||||||
|
type: '${stages[index]['type'] ?? ''}',
|
||||||
|
delivery: isDeliveryGate(stages[index]),
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
|
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
|
||||||
nodes.add(const GraphNode(key: failureEnd, terminal: true));
|
nodes.add(const GraphNode(key: failureEnd, terminal: true));
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import 'check_stage.dart';
|
||||||
import 'graph_definition.dart';
|
import 'graph_definition.dart';
|
||||||
import 'graph_protocol.dart';
|
import 'graph_protocol.dart';
|
||||||
|
|
||||||
@@ -9,13 +10,22 @@ import 'graph_protocol.dart';
|
|||||||
/// reads run visits, so a definition can be inspected without claiming that a
|
/// reads run visits, so a definition can be inspected without claiming that a
|
||||||
/// stage executed.
|
/// stage executed.
|
||||||
class StageDefinitionField {
|
class StageDefinitionField {
|
||||||
const StageDefinitionField(this.label, this.value, {this.block = false});
|
const StageDefinitionField(
|
||||||
|
this.label,
|
||||||
|
this.value, {
|
||||||
|
this.block = false,
|
||||||
|
this.monospace = false,
|
||||||
|
});
|
||||||
|
|
||||||
final String label;
|
final String label;
|
||||||
final String value;
|
final String value;
|
||||||
|
|
||||||
/// Multi-line content (prompt, output, outcomes, tools, memory, routes).
|
/// Multi-line content (prompt, output, outcomes, tools, memory, routes).
|
||||||
final bool block;
|
final bool block;
|
||||||
|
|
||||||
|
/// Literal code (a check stage's commands): always shown verbatim in a
|
||||||
|
/// monospace block, never rendered as markdown.
|
||||||
|
final bool monospace;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The one stage declaration [key] names, or null when this version does not
|
/// The one stage declaration [key] names, or null when this version does not
|
||||||
@@ -58,6 +68,12 @@ String stageConfigLabel(String key) {
|
|||||||
return 'Budget (tokens)';
|
return 'Budget (tokens)';
|
||||||
case 'harness':
|
case 'harness':
|
||||||
return 'Harness';
|
return 'Harness';
|
||||||
|
case 'command_timeout':
|
||||||
|
return 'Command timeout';
|
||||||
|
case 'keep_going':
|
||||||
|
return 'Keep going';
|
||||||
|
case 'delivery':
|
||||||
|
return 'Delivery gate';
|
||||||
default:
|
default:
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
@@ -69,10 +85,27 @@ String stageConfigLabel(String key) {
|
|||||||
/// interpreted here; the pane keeps the stage's raw JSON so they stay visible.
|
/// interpreted here; the pane keeps the stage's raw JSON so they stay visible.
|
||||||
List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
|
List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
|
||||||
if (stage is! Map) return const <StageDefinitionField>[];
|
if (stage is! Map) return const <StageDefinitionField>[];
|
||||||
|
final type = effectiveStageType(stage['type']);
|
||||||
final fields = <StageDefinitionField>[
|
final fields = <StageDefinitionField>[
|
||||||
StageDefinitionField('Type', effectiveStageType(stage['type'])),
|
StageDefinitionField(
|
||||||
|
'Type',
|
||||||
|
isDeliveryGate(stage) ? '$type (delivery gate)' : type,
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// A check stage runs commands where a model stage has its prompt.
|
||||||
|
final commands = checkCommands(stage);
|
||||||
|
if (isCheckStage(stage) && commands.isNotEmpty) {
|
||||||
|
fields.add(
|
||||||
|
StageDefinitionField(
|
||||||
|
'Commands',
|
||||||
|
commands.join('\n'),
|
||||||
|
block: true,
|
||||||
|
monospace: true,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
final prompt = _text(stage['prompt']);
|
final prompt = _text(stage['prompt']);
|
||||||
if (prompt.trim().isNotEmpty) {
|
if (prompt.trim().isNotEmpty) {
|
||||||
fields.add(StageDefinitionField('Prompt', prompt, block: true));
|
fields.add(StageDefinitionField('Prompt', prompt, block: true));
|
||||||
|
|||||||
@@ -45,10 +45,7 @@ class GraphStageNode extends StatelessWidget {
|
|||||||
return status != null && status.trim().isNotEmpty ? status : null;
|
return status != null && status.trim().isNotEmpty ? status : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
String get _label {
|
String get _label => graphNodeSemanticsLabel(node, _status);
|
||||||
final status = _status;
|
|
||||||
return status == null ? node.label : '${node.label}\n$status';
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -112,11 +109,13 @@ class GraphStageNode extends StatelessWidget {
|
|||||||
graphStatusState(status),
|
graphStatusState(status),
|
||||||
Theme.of(context).colorScheme,
|
Theme.of(context).colorScheme,
|
||||||
);
|
);
|
||||||
|
final caption = node.kindCaption;
|
||||||
return Column(
|
return Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text(_breakable(node.label), softWrap: true),
|
Text(_breakable(node.label), softWrap: true),
|
||||||
|
if (caption != null) _kind(context, caption),
|
||||||
if (status != null)
|
if (status != null)
|
||||||
Row(
|
Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
@@ -144,6 +143,29 @@ class GraphStageNode extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A check stage's kind under its name: the check icon (a gate icon for the
|
||||||
|
/// delivery gate) and `Check`/`Delivery gate` in the muted label role.
|
||||||
|
Widget _kind(BuildContext context, String caption) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final color = theme.colorScheme.onSurfaceVariant;
|
||||||
|
final style = (theme.textTheme.labelSmall ?? const TextStyle()).copyWith(
|
||||||
|
color: color,
|
||||||
|
);
|
||||||
|
return Row(
|
||||||
|
key: ValueKey('graph-node-kind-${node.key}'),
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
checkStageIcon(delivery: node.delivery),
|
||||||
|
size: (style.fontSize ?? 11) * 1.4,
|
||||||
|
color: color,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Flexible(child: Text(caption, style: style, softWrap: true)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a
|
/// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a
|
||||||
/// long unbroken key, so the same invisible break opportunities are added.
|
/// long unbroken key, so the same invisible break opportunities are added.
|
||||||
/// The visible text and the semantics label stay unchanged.
|
/// The visible text and the semantics label stay unchanged.
|
||||||
@@ -265,6 +287,18 @@ class StageActivityHaloPainter extends CustomPainter {
|
|||||||
oldDelegate.color != color || oldDelegate.progress != progress;
|
oldDelegate.color != color || oldDelegate.progress != progress;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The icon for a check stage; the delivery gate gets the landing icon.
|
||||||
|
IconData checkStageIcon({required bool delivery}) =>
|
||||||
|
delivery ? Icons.verified_outlined : Icons.fact_check_outlined;
|
||||||
|
|
||||||
|
/// A node's accessible name: its label, a check stage's kind, then the run's
|
||||||
|
/// recorded status when there is one.
|
||||||
|
String graphNodeSemanticsLabel(GraphNode node, String? status) => [
|
||||||
|
node.label,
|
||||||
|
?node.kindCaption,
|
||||||
|
if (status != null && status.trim().isNotEmpty) status,
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
/// The run state a recorded step status colours as: done is green, an error or
|
/// The run state a recorded step status colours as: done is green, an error or
|
||||||
/// a block is red, running is blue, waiting teal, anything else grey.
|
/// a block is red, running is blue, waiting teal, anything else grey.
|
||||||
String graphStatusState(String status) {
|
String graphStatusState(String status) {
|
||||||
|
|||||||
@@ -401,7 +401,7 @@ class RunGraphNode extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
return Semantics(
|
return Semantics(
|
||||||
container: true,
|
container: true,
|
||||||
label: status == null ? node.label : '${node.label}\n$status',
|
label: graphNodeSemanticsLabel(node, status),
|
||||||
child: ExcludeSemantics(
|
child: ExcludeSemantics(
|
||||||
child: IgnorePointer(
|
child: IgnorePointer(
|
||||||
child: GraphStageNode(
|
child: GraphStageNode(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
|
|||||||
|
|
||||||
import '../../../ui/adaptive/segmented_bar.dart';
|
import '../../../ui/adaptive/segmented_bar.dart';
|
||||||
import '../../../ui/text/markdown_source_view.dart';
|
import '../../../ui/text/markdown_source_view.dart';
|
||||||
|
import '../../../ui/text/monospace.dart';
|
||||||
import '../../chat/ui/transcript/chat_markdown_view.dart';
|
import '../../chat/ui/transcript/chat_markdown_view.dart';
|
||||||
import '../../../core/api_gateway.dart';
|
import '../../../core/api_gateway.dart';
|
||||||
import '../../../ui/adaptive/floating_bar_layout.dart';
|
import '../../../ui/adaptive/floating_bar_layout.dart';
|
||||||
@@ -190,8 +191,15 @@ class _StageDefinitionFieldView extends StatelessWidget {
|
|||||||
children: [
|
children: [
|
||||||
Text(field.label, style: style.label),
|
Text(field.label, style: style.label),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
|
// Commands are literal code: verbatim and monospace in either mode.
|
||||||
|
if (field.monospace)
|
||||||
|
_SelectableDefinitionText(
|
||||||
|
key: ValueKey('stage-definition-${field.label}'),
|
||||||
|
value: field.value,
|
||||||
|
style: style.value.copyWith(fontFamily: appMonospaceFamily),
|
||||||
|
)
|
||||||
// An authored text block (a prompt) is markdown: rendered or raw.
|
// An authored text block (a prompt) is markdown: rendered or raw.
|
||||||
if (field.block && raw)
|
else if (field.block && raw)
|
||||||
_SelectableDefinitionText(value: field.value, style: style.value)
|
_SelectableDefinitionText(value: field.value, style: style.value)
|
||||||
else if (field.block)
|
else if (field.block)
|
||||||
ChatMarkdownView(text: field.value)
|
ChatMarkdownView(text: field.value)
|
||||||
@@ -215,7 +223,11 @@ class _StageDefinitionFieldView extends StatelessWidget {
|
|||||||
/// fallback font with taller metrics and double-space only that block. It is
|
/// fallback font with taller metrics and double-space only that block. It is
|
||||||
/// the host's own line metrics, not a font override or a fixed height.
|
/// the host's own line metrics, not a font override or a fixed height.
|
||||||
class _SelectableDefinitionText extends StatelessWidget {
|
class _SelectableDefinitionText extends StatelessWidget {
|
||||||
const _SelectableDefinitionText({required this.value, required this.style});
|
const _SelectableDefinitionText({
|
||||||
|
super.key,
|
||||||
|
required this.value,
|
||||||
|
required this.style,
|
||||||
|
});
|
||||||
|
|
||||||
final String value;
|
final String value;
|
||||||
final TextStyle style;
|
final TextStyle style;
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
// A check stage visit's recorded output: the per-command results the server
|
||||||
|
// ran for a `check` stage, read without widget imports.
|
||||||
|
//
|
||||||
|
// Only an output map carrying a `checks` list is a check output; older
|
||||||
|
// servers never send one, so every other step keeps its ordinary rendering.
|
||||||
|
|
||||||
|
/// How one command ended. [unknown] keeps a status this client does not know
|
||||||
|
/// (its raw word stays in [CheckCommandResult.statusWord]).
|
||||||
|
enum CheckCommandStatus { passed, failed, timedOut, notRun, unknown }
|
||||||
|
|
||||||
|
CheckCommandStatus checkCommandStatus(String word) =>
|
||||||
|
switch (word.trim().toLowerCase()) {
|
||||||
|
'passed' => CheckCommandStatus.passed,
|
||||||
|
'failed' => CheckCommandStatus.failed,
|
||||||
|
'timed_out' => CheckCommandStatus.timedOut,
|
||||||
|
'not_run' => CheckCommandStatus.notRun,
|
||||||
|
_ => CheckCommandStatus.unknown,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The status as the row reads it; an unknown status shows its raw word.
|
||||||
|
String checkStatusLabel(CheckCommandResult check) => switch (check.status) {
|
||||||
|
CheckCommandStatus.passed => 'Passed',
|
||||||
|
CheckCommandStatus.failed => 'Failed',
|
||||||
|
CheckCommandStatus.timedOut => 'Timed out',
|
||||||
|
CheckCommandStatus.notRun => 'Not run',
|
||||||
|
CheckCommandStatus.unknown =>
|
||||||
|
check.statusWord.isEmpty ? 'Unknown status' : check.statusWord,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// One command's recorded result.
|
||||||
|
class CheckCommandResult {
|
||||||
|
const CheckCommandResult({
|
||||||
|
required this.command,
|
||||||
|
required this.statusWord,
|
||||||
|
this.exitCode,
|
||||||
|
this.durationMs,
|
||||||
|
this.output = '',
|
||||||
|
this.truncated = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
final String command;
|
||||||
|
|
||||||
|
/// The server's status word verbatim.
|
||||||
|
final String statusWord;
|
||||||
|
|
||||||
|
/// Null when not recorded (a command that never ran has none).
|
||||||
|
final int? exitCode;
|
||||||
|
final int? durationMs;
|
||||||
|
final String output;
|
||||||
|
|
||||||
|
/// Whether the server cut [output] at its capture limit.
|
||||||
|
final bool truncated;
|
||||||
|
|
||||||
|
CheckCommandStatus get status => checkCommandStatus(statusWord);
|
||||||
|
|
||||||
|
/// `exit 1 · 51s`, leaving out whichever fact was not recorded.
|
||||||
|
String get meta => [
|
||||||
|
if (exitCode != null) 'exit $exitCode',
|
||||||
|
if (durationMs != null) formatCheckDuration(durationMs!),
|
||||||
|
].join(' · ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A check visit's whole recorded output.
|
||||||
|
class CheckStepOutput {
|
||||||
|
const CheckStepOutput({
|
||||||
|
required this.checks,
|
||||||
|
this.summary,
|
||||||
|
this.markdown,
|
||||||
|
this.delivery = false,
|
||||||
|
});
|
||||||
|
|
||||||
|
final List<CheckCommandResult> checks;
|
||||||
|
|
||||||
|
/// The server's one-line summary (`1 of 2 checks failed: go test ./...`).
|
||||||
|
final String? summary;
|
||||||
|
|
||||||
|
/// The handoff document the next stage reads.
|
||||||
|
final String? markdown;
|
||||||
|
|
||||||
|
/// Whether this visit was the delivery gate.
|
||||||
|
final bool delivery;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The check output recorded in [output], or null when it is not one.
|
||||||
|
CheckStepOutput? checkStepOutput(dynamic output) {
|
||||||
|
if (output is! Map) return null;
|
||||||
|
final checks = output['checks'];
|
||||||
|
if (checks is! List) return null;
|
||||||
|
return CheckStepOutput(
|
||||||
|
checks: [
|
||||||
|
for (final item in checks)
|
||||||
|
if (item is Map) _check(item),
|
||||||
|
],
|
||||||
|
summary: _text(output['summary']),
|
||||||
|
markdown: _text(output['markdown']),
|
||||||
|
delivery: output['delivery'] == true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
CheckCommandResult _check(Map item) => CheckCommandResult(
|
||||||
|
command: '${item['command'] ?? ''}',
|
||||||
|
statusWord: '${item['status'] ?? ''}'.trim(),
|
||||||
|
exitCode: _int(item['exit_code']),
|
||||||
|
durationMs: _int(item['duration_ms']),
|
||||||
|
output: item['output'] is String ? item['output'] as String : '',
|
||||||
|
truncated: item['truncated'] == true,
|
||||||
|
);
|
||||||
|
|
||||||
|
/// A command duration: `850ms`, `2.1s`, `51s`, `3m 05s`.
|
||||||
|
String formatCheckDuration(int ms) {
|
||||||
|
if (ms < 1000) return '${ms}ms';
|
||||||
|
if (ms < 10000) {
|
||||||
|
final tenths = (ms / 100).round();
|
||||||
|
return tenths % 10 == 0 ? '${tenths ~/ 10}s' : '${tenths / 10}s';
|
||||||
|
}
|
||||||
|
final seconds = (ms / 1000).round();
|
||||||
|
if (seconds < 60) return '${seconds}s';
|
||||||
|
final minutes = seconds ~/ 60;
|
||||||
|
final rest = (seconds % 60).toString().padLeft(2, '0');
|
||||||
|
if (minutes < 60) return '${minutes}m ${rest}s';
|
||||||
|
return '${minutes ~/ 60}h ${(minutes % 60).toString().padLeft(2, '0')}m';
|
||||||
|
}
|
||||||
|
|
||||||
|
int? _int(dynamic value) {
|
||||||
|
if (value is num) return value.toInt();
|
||||||
|
if (value is String) return int.tryParse(value.trim());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _text(dynamic value) {
|
||||||
|
if (value is! String) return null;
|
||||||
|
return value.trim().isEmpty ? null : value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../../ui/status/run_status_icon.dart';
|
||||||
|
import '../../../ui/text/monospace.dart';
|
||||||
|
import '../../chat/ui/transcript/chat_markdown_view.dart';
|
||||||
|
import '../domain/check_step_output.dart';
|
||||||
|
|
||||||
|
/// The note under a command whose recorded output the server cut short.
|
||||||
|
const String checkOutputTruncated =
|
||||||
|
'The server truncated this output at its capture limit.';
|
||||||
|
|
||||||
|
/// The body of a command that recorded no output.
|
||||||
|
const String checkOutputEmpty = 'No output recorded.';
|
||||||
|
|
||||||
|
/// A check visit's Output: its summary, a delivery-gate marker, one
|
||||||
|
/// expandable row per command and the handoff document the next stage reads.
|
||||||
|
class RunCheckOutputView extends StatelessWidget {
|
||||||
|
const RunCheckOutputView({super.key, required this.output});
|
||||||
|
|
||||||
|
final CheckStepOutput output;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final summary = output.summary;
|
||||||
|
final markdown = output.markdown;
|
||||||
|
return Column(
|
||||||
|
key: const Key('run-check-output'),
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
children: [
|
||||||
|
if (output.delivery)
|
||||||
|
Align(
|
||||||
|
alignment: AlignmentDirectional.centerStart,
|
||||||
|
child: Chip(
|
||||||
|
key: const Key('run-check-delivery'),
|
||||||
|
avatar: const Icon(Icons.verified_outlined),
|
||||||
|
label: const Text('Delivery gate'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (summary != null)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||||
|
child: SelectableText(summary, style: theme.textTheme.bodyLarge),
|
||||||
|
),
|
||||||
|
if (output.checks.isEmpty)
|
||||||
|
const Text('No commands were recorded.')
|
||||||
|
else
|
||||||
|
for (final (index, check) in output.checks.indexed)
|
||||||
|
RunCheckCommandRow(
|
||||||
|
key: ValueKey('run-check-command-$index'),
|
||||||
|
check: check,
|
||||||
|
),
|
||||||
|
if (markdown != null) ...[
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text('Handoff', style: theme.textTheme.titleSmall),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
ChatMarkdownView(text: markdown),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One command: a status icon, the command, its status, exit code and
|
||||||
|
/// duration; expanding it shows the recorded output as selectable monospace.
|
||||||
|
class RunCheckCommandRow extends StatelessWidget {
|
||||||
|
const RunCheckCommandRow({super.key, required this.check});
|
||||||
|
|
||||||
|
final CheckCommandResult check;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final mono = (theme.textTheme.bodyMedium ?? const TextStyle()).copyWith(
|
||||||
|
fontFamily: appMonospaceFamily,
|
||||||
|
);
|
||||||
|
final color = runStatusColor(_state(check.status), theme.colorScheme);
|
||||||
|
final meta = check.meta;
|
||||||
|
return ExpansionTile(
|
||||||
|
tilePadding: EdgeInsets.zero,
|
||||||
|
childrenPadding: const EdgeInsets.only(bottom: 12),
|
||||||
|
expandedCrossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
|
leading: Icon(
|
||||||
|
_icon(check.status),
|
||||||
|
color: color,
|
||||||
|
semanticLabel: checkStatusLabel(check),
|
||||||
|
),
|
||||||
|
title: Text(
|
||||||
|
check.command.isEmpty ? '(no command)' : check.command,
|
||||||
|
style: mono,
|
||||||
|
),
|
||||||
|
subtitle: Text(
|
||||||
|
[checkStatusLabel(check), if (meta.isNotEmpty) meta].join(' · '),
|
||||||
|
),
|
||||||
|
children: [
|
||||||
|
if (check.output.isEmpty)
|
||||||
|
const Text(checkOutputEmpty)
|
||||||
|
else
|
||||||
|
DecoratedBox(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest,
|
||||||
|
borderRadius: BorderRadius.circular(8),
|
||||||
|
),
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
child: SelectableText(check.output, style: mono),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
if (check.truncated)
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 4),
|
||||||
|
child: Text(
|
||||||
|
checkOutputTruncated,
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String _state(CheckCommandStatus status) => switch (status) {
|
||||||
|
CheckCommandStatus.passed => 'succeeded',
|
||||||
|
CheckCommandStatus.failed || CheckCommandStatus.timedOut => 'failed',
|
||||||
|
CheckCommandStatus.notRun || CheckCommandStatus.unknown => 'unknown',
|
||||||
|
};
|
||||||
|
|
||||||
|
static IconData _icon(CheckCommandStatus status) => switch (status) {
|
||||||
|
CheckCommandStatus.passed => Icons.check_circle_outline,
|
||||||
|
CheckCommandStatus.failed => Icons.cancel_outlined,
|
||||||
|
CheckCommandStatus.timedOut => Icons.timer_off_outlined,
|
||||||
|
CheckCommandStatus.notRun => Icons.remove_circle_outline,
|
||||||
|
CheckCommandStatus.unknown => Icons.help_outline,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -133,6 +133,22 @@ String? detailVisitSkills(JsonMap step) {
|
|||||||
return (option: option, reason: reason);
|
return (option: option, reason: reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many times the server sent its one "missing `# outcome`" repair
|
||||||
|
/// follow-up for this visit (`control.outcome_repairs`); 0 when not recorded,
|
||||||
|
/// which older servers and unrepaired visits both mean.
|
||||||
|
int detailVisitOutcomeRepairs(JsonMap step) {
|
||||||
|
final control = step['control'];
|
||||||
|
if (control is! Map) return 0;
|
||||||
|
final value = control['outcome_repairs'];
|
||||||
|
if (value is num) return value.toInt();
|
||||||
|
return int.tryParse('${value ?? ''}'.trim()) ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The note a repaired visit shows under its facts.
|
||||||
|
String outcomeRepairNote(int repairs) => repairs == 1
|
||||||
|
? 'Outcome repaired by follow-up'
|
||||||
|
: 'Outcome repaired by follow-up ($repairs times)';
|
||||||
|
|
||||||
/// The visit's diagnostic exactly as recorded, or null when it is blank.
|
/// The visit's diagnostic exactly as recorded, or null when it is blank.
|
||||||
String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']);
|
String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']);
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ class RunVisitFactsView extends StatelessWidget {
|
|||||||
final facts = detailVisitFacts(step);
|
final facts = detailVisitFacts(step);
|
||||||
final verdict = detailVisitVerdict(step);
|
final verdict = detailVisitVerdict(step);
|
||||||
final diagnostic = detailVisitDiagnostic(step);
|
final diagnostic = detailVisitDiagnostic(step);
|
||||||
|
final repairs = detailVisitOutcomeRepairs(step);
|
||||||
return Padding(
|
return Padding(
|
||||||
key: const Key('run-visit-facts'),
|
key: const Key('run-visit-facts'),
|
||||||
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12),
|
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12),
|
||||||
@@ -28,6 +29,23 @@ class RunVisitFactsView extends StatelessWidget {
|
|||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
_FactGrid(facts: facts, style: style),
|
_FactGrid(facts: facts, style: style),
|
||||||
|
if (repairs > 0) ...[
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Row(
|
||||||
|
key: const Key('run-visit-outcome-repaired'),
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.build_circle_outlined,
|
||||||
|
size: 16,
|
||||||
|
color: style.muted.color,
|
||||||
|
),
|
||||||
|
const SizedBox(width: 6),
|
||||||
|
Flexible(
|
||||||
|
child: Text(outcomeRepairNote(repairs), style: style.muted),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
if (verdict != null) ...[
|
if (verdict != null) ...[
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Text('Verdict', style: style.heading),
|
Text('Verdict', style: style.heading),
|
||||||
@@ -57,10 +75,14 @@ class _FactGrid extends StatelessWidget {
|
|||||||
static String _stateOf(VisitFact fact) {
|
static String _stateOf(VisitFact fact) {
|
||||||
final value = fact.value.trim().toLowerCase();
|
final value = fact.value.trim().toLowerCase();
|
||||||
if (fact.label == 'Outcome') {
|
if (fact.label == 'Outcome') {
|
||||||
if (value == 'error' || value == 'failed' || value == 'blocked') {
|
if (value == 'error' ||
|
||||||
|
value == 'failed' ||
|
||||||
|
value == 'fail' ||
|
||||||
|
value == 'blocked') {
|
||||||
return 'failed';
|
return 'failed';
|
||||||
}
|
}
|
||||||
if (value == 'success') return 'succeeded';
|
// A check stage routes `pass`/`fail`.
|
||||||
|
if (value == 'success' || value == 'pass') return 'succeeded';
|
||||||
return 'running';
|
return 'running';
|
||||||
}
|
}
|
||||||
return graphStatusState(fact.value);
|
return graphStatusState(fact.value);
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import 'package:flutter/services.dart';
|
|||||||
import '../../../core/api_gateway.dart';
|
import '../../../core/api_gateway.dart';
|
||||||
import '../../../ui/adaptive/floating_destination_bar.dart';
|
import '../../../ui/adaptive/floating_destination_bar.dart';
|
||||||
import '../../changes/changes.dart';
|
import '../../changes/changes.dart';
|
||||||
|
import '../domain/check_step_output.dart';
|
||||||
|
import 'run_check_output_view.dart';
|
||||||
import 'run_detail_tab_bodies.dart';
|
import 'run_detail_tab_bodies.dart';
|
||||||
import 'run_field_body.dart';
|
import 'run_field_body.dart';
|
||||||
import '../../../ui/layout/sticky_section.dart';
|
import '../../../ui/layout/sticky_section.dart';
|
||||||
@@ -216,6 +218,9 @@ class _VisitSummaryState extends State<_VisitSummary> {
|
|||||||
);
|
);
|
||||||
final open = !_closed.contains(name);
|
final open = !_closed.contains(name);
|
||||||
const padding = EdgeInsets.fromLTRB(16, 0, 16, 16);
|
const padding = EdgeInsets.fromLTRB(16, 0, 16, 16);
|
||||||
|
// A check visit's Output is its command results, not a field map.
|
||||||
|
final check = name == 'Output' ? checkStepOutput(value) : null;
|
||||||
|
final sliver = lazy && check == null;
|
||||||
return StickySection(
|
return StickySection(
|
||||||
key: ValueKey('run-visit-section-$name'),
|
key: ValueKey('run-visit-section-$name'),
|
||||||
title: name,
|
title: name,
|
||||||
@@ -224,13 +229,15 @@ class _VisitSummaryState extends State<_VisitSummary> {
|
|||||||
if (!_closed.remove(name)) _closed.add(name);
|
if (!_closed.remove(name)) _closed.add(name);
|
||||||
}),
|
}),
|
||||||
trailing: [copy],
|
trailing: [copy],
|
||||||
body: lazy
|
body: sliver
|
||||||
? null
|
? null
|
||||||
: Padding(
|
: Padding(
|
||||||
padding: padding,
|
padding: padding,
|
||||||
child: RunFieldBody(value: value, empty: empty),
|
child: check != null
|
||||||
|
? RunCheckOutputView(output: check)
|
||||||
|
: RunFieldBody(value: value, empty: empty),
|
||||||
),
|
),
|
||||||
sliverBody: lazy
|
sliverBody: sliver
|
||||||
? SliverPadding(
|
? SliverPadding(
|
||||||
padding: padding,
|
padding: padding,
|
||||||
sliver: RunFieldSliver(value: value, empty: empty),
|
sliver: RunFieldSliver(value: value, empty: empty),
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import '../../../core/api_gateway.dart';
|
import '../../../core/api_gateway.dart';
|
||||||
|
import '../domain/check_step_output.dart';
|
||||||
import 'run_detail_visit_export.dart';
|
import 'run_detail_visit_export.dart';
|
||||||
import 'run_detail_visit_recorded.dart';
|
import 'run_detail_visit_recorded.dart';
|
||||||
|
|
||||||
@@ -18,6 +19,10 @@ const String visitSessionNoIdentity =
|
|||||||
'Runtime error: this model stage has no recorded session identity.';
|
'Runtime error: this model stage has no recorded session identity.';
|
||||||
const String visitSessionNone = 'This visit has no harness session.';
|
const String visitSessionNone = 'This visit has no harness session.';
|
||||||
|
|
||||||
|
/// A check stage runs commands, never a model, so it has no session at all.
|
||||||
|
const String visitSessionCheck =
|
||||||
|
'A check stage runs commands without a model; it has no harness session.';
|
||||||
|
|
||||||
/// An export that exists but cannot be resolved through the configured server.
|
/// An export that exists but cannot be resolved through the configured server.
|
||||||
const String visitSessionEndpointMissing =
|
const String visitSessionEndpointMissing =
|
||||||
'Set the server URL in Settings to open the session.';
|
'Set the server URL in Settings to open the session.';
|
||||||
@@ -94,6 +99,7 @@ String _noSessionMessage(JsonMap step) {
|
|||||||
if (status == 'canceled' || status == 'interrupted') {
|
if (status == 'canceled' || status == 'interrupted') {
|
||||||
return visitSessionStopped;
|
return visitSessionStopped;
|
||||||
}
|
}
|
||||||
|
if (checkStepOutput(step['output']) != null) return visitSessionCheck;
|
||||||
final model =
|
final model =
|
||||||
recordedText(step['provider']) != null ||
|
recordedText(step['provider']) != null ||
|
||||||
recordedText(step['model']) != null;
|
recordedText(step['model']) != null;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart';
|
|||||||
import '../chat/workspace/chat_center_stage_controller.dart';
|
import '../chat/workspace/chat_center_stage_controller.dart';
|
||||||
import '../chat/workspace/chat_float_shortcut.dart';
|
import '../chat/workspace/chat_float_shortcut.dart';
|
||||||
import '../terminal/terminal_shortcuts.dart';
|
import '../terminal/terminal_shortcuts.dart';
|
||||||
|
import '../../shell/detached/detached_window_scope.dart';
|
||||||
import '../../shell/windows/window_shortcuts.dart';
|
import '../../shell/windows/window_shortcuts.dart';
|
||||||
import '../../shell/shell_chat_actions_shortcut.dart';
|
import '../../shell/shell_chat_actions_shortcut.dart';
|
||||||
import '../../shell/shell_chat_shortcut.dart';
|
import '../../shell/shell_chat_shortcut.dart';
|
||||||
@@ -221,6 +222,18 @@ class KeyboardShortcutRegistry {
|
|||||||
action: 'Cycle floating windows',
|
action: 'Cycle floating windows',
|
||||||
keys: _cycleKeys,
|
keys: _cycleKeys,
|
||||||
),
|
),
|
||||||
|
// A phone has no windows of its own to send a chat to.
|
||||||
|
if (web ||
|
||||||
|
platform == TargetPlatform.linux ||
|
||||||
|
platform == TargetPlatform.macOS)
|
||||||
|
KeyboardShortcutEntry(
|
||||||
|
group: KeyboardShortcutGroup.windows,
|
||||||
|
action: 'Open the chat in a new window',
|
||||||
|
keys: detachedWindowShortcutLabel(platform),
|
||||||
|
caveat:
|
||||||
|
'Moves the chat that has the keyboard to a browser or app '
|
||||||
|
'window of its own; its "Bring back to main window" returns it.',
|
||||||
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
/// Alt+` (Option+` on macOS) and the same chord with Shift, backwards.
|
/// Alt+` (Option+` on macOS) and the same chord with Shift, backwards.
|
||||||
|
|||||||
@@ -132,6 +132,10 @@ class TerminalLayout extends ChangeNotifier {
|
|||||||
/// Whether the last change could not be saved.
|
/// Whether the last change could not be saved.
|
||||||
bool saveFailed = false;
|
bool saveFailed = false;
|
||||||
|
|
||||||
|
/// Whether changes are saved. A detached window reads the device's layout
|
||||||
|
/// but never writes it: the main window owns it.
|
||||||
|
bool persist = true;
|
||||||
|
|
||||||
Future<void> restore() async {
|
Future<void> restore() async {
|
||||||
final revision = _revision;
|
final revision = _revision;
|
||||||
final raw = await _store.load();
|
final raw = await _store.load();
|
||||||
@@ -196,6 +200,7 @@ class TerminalLayout extends ChangeNotifier {
|
|||||||
|
|
||||||
/// Saves the current layout (a drag saves once, when it ends).
|
/// Saves the current layout (a drag saves once, when it ends).
|
||||||
Future<void> save() async {
|
Future<void> save() async {
|
||||||
|
if (!persist) return;
|
||||||
final revision = _revision;
|
final revision = _revision;
|
||||||
final saved = await _store.save(
|
final saved = await _store.save(
|
||||||
jsonEncode({
|
jsonEncode({
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import 'dart:async';
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
import '../../shell/detached/detached_window_scope.dart';
|
||||||
import 'terminal_browser_keys.dart';
|
import 'terminal_browser_keys.dart';
|
||||||
import 'terminal_hub.dart';
|
import 'terminal_hub.dart';
|
||||||
import 'terminal_layout.dart';
|
import 'terminal_layout.dart';
|
||||||
@@ -67,43 +68,67 @@ class TerminalTabStrip extends StatelessWidget {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The options menu: the modes, the browser keys capture (on a browser
|
/// The options menu: the modes, Open in new window (where the platform
|
||||||
/// that can) and Hide terminal, with the shortcuts under them.
|
/// has windows), the browser keys capture (on a browser that can) and
|
||||||
Widget _options(BuildContext context) => TerminalMenuButton<_Option>(
|
/// Hide terminal, with the shortcuts under them.
|
||||||
label: 'Terminal options',
|
Widget _options(BuildContext context) {
|
||||||
info: TerminalShortcutLabels.current().summary,
|
final opener = DetachedWindowScope.maybeOf(context);
|
||||||
icon: Icons.more_vert,
|
return TerminalMenuButton<_Option>(
|
||||||
choices: [
|
label: 'Terminal options',
|
||||||
for (final mode in TerminalMode.values)
|
info: TerminalShortcutLabels.current().summary,
|
||||||
TerminalChoice(
|
icon: Icons.more_vert,
|
||||||
_Option(mode),
|
choices: [
|
||||||
mode.label,
|
for (final mode in TerminalMode.values)
|
||||||
checked: layout.mode == mode,
|
TerminalChoice(
|
||||||
key: ValueKey('terminal-mode-${mode.name}'),
|
_Option(mode),
|
||||||
|
mode.label,
|
||||||
|
checked: layout.mode == mode,
|
||||||
|
key: ValueKey('terminal-mode-${mode.name}'),
|
||||||
|
),
|
||||||
|
if (opener != null)
|
||||||
|
const TerminalChoice(
|
||||||
|
_Option(null, newWindow: true),
|
||||||
|
detachedWindowLabel,
|
||||||
|
key: ValueKey('terminal-new-window'),
|
||||||
|
),
|
||||||
|
if (browserKeys.supported)
|
||||||
|
TerminalChoice(
|
||||||
|
const _Option(null, browserKeys: true),
|
||||||
|
'Capture browser keys',
|
||||||
|
checked: browserKeys.active,
|
||||||
|
key: const ValueKey('terminal-browser-keys'),
|
||||||
|
),
|
||||||
|
const TerminalChoice(
|
||||||
|
_Option(null),
|
||||||
|
'Hide terminal',
|
||||||
|
key: ValueKey('terminal-hide'),
|
||||||
),
|
),
|
||||||
if (browserKeys.supported)
|
],
|
||||||
TerminalChoice(
|
onSelected: (option) {
|
||||||
const _Option(null, browserKeys: true),
|
if (option.newWindow) {
|
||||||
'Capture browser keys',
|
_openInNewWindow(opener!);
|
||||||
checked: browserKeys.active,
|
} else if (option.browserKeys) {
|
||||||
key: const ValueKey('terminal-browser-keys'),
|
unawaited(toggleTerminalBrowserKeys(context, browserKeys));
|
||||||
),
|
} else if (option.mode == null) {
|
||||||
const TerminalChoice(
|
layout.hide();
|
||||||
_Option(null),
|
} else {
|
||||||
'Hide terminal',
|
layout.setMode(option.mode!);
|
||||||
key: ValueKey('terminal-hide'),
|
}
|
||||||
),
|
},
|
||||||
],
|
);
|
||||||
onSelected: (option) {
|
}
|
||||||
if (option.browserKeys) {
|
|
||||||
unawaited(toggleTerminalBrowserKeys(context, browserKeys));
|
/// The terminal moves to a window of its own, on the selected tab; this
|
||||||
} else if (option.mode == null) {
|
/// one hides it once that window is open. The terminals keep running on
|
||||||
layout.hide();
|
/// the machines, so both windows reach the same shells.
|
||||||
} else {
|
void _openInNewWindow(DetachedWindowOpener opener) {
|
||||||
layout.setMode(option.mode!);
|
final tab = hub.selected;
|
||||||
}
|
opener.openTerminal(
|
||||||
},
|
tabKey: tab?.key ?? '',
|
||||||
);
|
title: tab == null ? 'Terminal' : 'Terminal: ${tab.title}',
|
||||||
|
onOpened: layout.hide,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
String _label(TerminalTab tab) =>
|
String _label(TerminalTab tab) =>
|
||||||
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
|
hub.multiMachine ? '${tab.title} · ${tab.machineName}' : tab.title;
|
||||||
@@ -152,7 +177,8 @@ class TerminalTabStrip extends StatelessWidget {
|
|||||||
/// A mode to switch to, (null) hiding the terminal, or the browser keys
|
/// A mode to switch to, (null) hiding the terminal, or the browser keys
|
||||||
/// capture.
|
/// capture.
|
||||||
class _Option {
|
class _Option {
|
||||||
const _Option(this.mode, {this.browserKeys = false});
|
const _Option(this.mode, {this.browserKeys = false, this.newWindow = false});
|
||||||
final TerminalMode? mode;
|
final TerminalMode? mode;
|
||||||
final bool browserKeys;
|
final bool browserKeys;
|
||||||
|
final bool newWindow;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -4,4 +4,4 @@ export 'application/app.dart' show MyApp;
|
|||||||
export 'shell/adaptive_shell.dart';
|
export 'shell/adaptive_shell.dart';
|
||||||
export 'shell/destination.dart';
|
export 'shell/destination.dart';
|
||||||
|
|
||||||
void main() => runPipelinesApp();
|
void main(List<String> args) => runPipelinesApp(args: args);
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
/// Opens an item of the app in a window of its own: a browser window on the
|
||||||
|
/// web, a second app process on a desktop (see `notes/detached-windows.md`).
|
||||||
|
///
|
||||||
|
/// Each call removes nothing itself: [onOpened] runs once the window really
|
||||||
|
/// opened (at once, or after the operator allowed a blocked popup), and the
|
||||||
|
/// caller then takes the item out of the main window.
|
||||||
|
abstract interface class DetachedWindowOpener {
|
||||||
|
void openChat(
|
||||||
|
String sessionId, {
|
||||||
|
required String title,
|
||||||
|
VoidCallback? onOpened,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The terminal on [tabKey] (empty: whichever tab it selects).
|
||||||
|
void openTerminal({
|
||||||
|
String tabKey = '',
|
||||||
|
required String title,
|
||||||
|
VoidCallback? onOpened,
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A diff's files, as the server's `file_changes.files[]` entries.
|
||||||
|
void openDiff(
|
||||||
|
List<Map<String, Object?>> files, {
|
||||||
|
int initialIndex = 0,
|
||||||
|
required String title,
|
||||||
|
VoidCallback? onOpened,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands the app's [DetachedWindowOpener] to the screens that offer
|
||||||
|
/// "Open in new window". Absent where the platform has no windows (Android,
|
||||||
|
/// iOS) and inside a detached window itself.
|
||||||
|
class DetachedWindowScope extends InheritedWidget {
|
||||||
|
const DetachedWindowScope({
|
||||||
|
super.key,
|
||||||
|
required this.opener,
|
||||||
|
required super.child,
|
||||||
|
});
|
||||||
|
|
||||||
|
final DetachedWindowOpener opener;
|
||||||
|
|
||||||
|
static DetachedWindowOpener? maybeOf(BuildContext context) =>
|
||||||
|
context.getInheritedWidgetOfExactType<DetachedWindowScope>()?.opener;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool updateShouldNotify(DetachedWindowScope oldWidget) =>
|
||||||
|
opener != oldWidget.opener;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The menus' label for the action.
|
||||||
|
const detachedWindowLabel = 'Open in new window';
|
||||||
|
|
||||||
|
/// Whether [event] sends the chat with the keyboard to a new window:
|
||||||
|
/// Alt+Shift+Y (Option+Shift+Y). Alt+Y alone is Float.
|
||||||
|
bool detachedWindowShortcut(KeyEvent event, HardwareKeyboard keyboard) {
|
||||||
|
if (event is KeyUpEvent || !keyboard.isAltPressed) return false;
|
||||||
|
if (!keyboard.isShiftPressed) return false;
|
||||||
|
if (keyboard.isControlPressed || keyboard.isMetaPressed) return false;
|
||||||
|
// Option+Shift+Y types a symbol on a Mac: match the key's position too.
|
||||||
|
return event.logicalKey == LogicalKeyboardKey.keyY ||
|
||||||
|
event.physicalKey == PhysicalKeyboardKey.keyY;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shortcut as it reads on this platform.
|
||||||
|
String detachedWindowShortcutLabel([TargetPlatform? platform]) =>
|
||||||
|
switch (platform ?? defaultTargetPlatform) {
|
||||||
|
TargetPlatform.macOS || TargetPlatform.iOS => 'Option+Shift+Y',
|
||||||
|
_ => 'Alt+Shift+Y',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The label with the shortcut, for the chat menus.
|
||||||
|
String detachedChatWindowLabel() =>
|
||||||
|
'$detachedWindowLabel (${detachedWindowShortcutLabel()})';
|
||||||
@@ -97,6 +97,11 @@ install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
|
|||||||
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
COMPONENT Runtime)
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
# The window icon (runner/my_application.cc); the installer also puts it in
|
||||||
|
# the icon theme for the desktop entry.
|
||||||
|
install(FILES "runner/resources/app_icon.png" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
|
||||||
|
COMPONENT Runtime)
|
||||||
|
|
||||||
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
|
||||||
COMPONENT Runtime)
|
COMPONENT Runtime)
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ project(runner LANGUAGES CXX)
|
|||||||
add_executable(${BINARY_NAME}
|
add_executable(${BINARY_NAME}
|
||||||
"main.cc"
|
"main.cc"
|
||||||
"my_application.cc"
|
"my_application.cc"
|
||||||
|
"clipboard_files.cc"
|
||||||
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
#include "clipboard_files.h"
|
||||||
|
|
||||||
|
#include <gio/gio.h>
|
||||||
|
#include <gtk/gtk.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
FlMethodChannel* channel = nullptr;
|
||||||
|
|
||||||
|
// The MIME type of [path] from its name and contents, or "".
|
||||||
|
gchar* mime_of(const gchar* path, const guchar* data, gsize length) {
|
||||||
|
gboolean uncertain = FALSE;
|
||||||
|
g_autofree gchar* type =
|
||||||
|
g_content_type_guess(path, data, MIN(length, (gsize)4096), &uncertain);
|
||||||
|
gchar* mime = type == nullptr ? nullptr : g_content_type_get_mime_type(type);
|
||||||
|
return mime == nullptr ? g_strdup("") : mime;
|
||||||
|
}
|
||||||
|
|
||||||
|
FlValue* file_entry(const gchar* name, const gchar* mime, const guchar* data,
|
||||||
|
gsize length) {
|
||||||
|
FlValue* entry = fl_value_new_map();
|
||||||
|
fl_value_set_string_take(entry, "name", fl_value_new_string(name));
|
||||||
|
fl_value_set_string_take(entry, "mime", fl_value_new_string(mime));
|
||||||
|
fl_value_set_string_take(entry, "bytes",
|
||||||
|
fl_value_new_uint8_list(data, length));
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adds each copied local file; folders and unreadable files become errors.
|
||||||
|
gboolean add_uris(GtkClipboard* clipboard, FlValue* files, FlValue* errors) {
|
||||||
|
g_auto(GStrv) uris = gtk_clipboard_wait_for_uris(clipboard);
|
||||||
|
if (uris == nullptr || uris[0] == nullptr) return FALSE;
|
||||||
|
gboolean any = FALSE;
|
||||||
|
for (gchar** uri = uris; *uri != nullptr; uri++) {
|
||||||
|
g_autofree gchar* path = g_filename_from_uri(*uri, nullptr, nullptr);
|
||||||
|
if (path == nullptr) continue;
|
||||||
|
any = TRUE;
|
||||||
|
g_autofree gchar* name = g_path_get_basename(path);
|
||||||
|
if (g_file_test(path, G_FILE_TEST_IS_DIR)) {
|
||||||
|
g_autofree gchar* message =
|
||||||
|
g_strdup_printf("%s is a folder; paste its files instead.", name);
|
||||||
|
fl_value_append_take(errors, fl_value_new_string(message));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
g_autofree gchar* contents = nullptr;
|
||||||
|
gsize length = 0;
|
||||||
|
g_autoptr(GError) error = nullptr;
|
||||||
|
if (!g_file_get_contents(path, &contents, &length, &error)) {
|
||||||
|
g_autofree gchar* message =
|
||||||
|
g_strdup_printf("Could not read %s: %s", name, error->message);
|
||||||
|
fl_value_append_take(errors, fl_value_new_string(message));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
g_autofree gchar* mime =
|
||||||
|
mime_of(path, reinterpret_cast<const guchar*>(contents), length);
|
||||||
|
fl_value_append_take(
|
||||||
|
files, file_entry(name, mime,
|
||||||
|
reinterpret_cast<const guchar*>(contents), length));
|
||||||
|
}
|
||||||
|
return any;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The clipboard's own PNG (a screenshot tool's), else any image GTK can read
|
||||||
|
// converted to PNG.
|
||||||
|
void add_image(GtkClipboard* clipboard, FlValue* files) {
|
||||||
|
g_autoptr(GtkSelectionData) png = gtk_clipboard_wait_for_contents(
|
||||||
|
clipboard, gdk_atom_intern_static_string("image/png"));
|
||||||
|
if (png != nullptr && gtk_selection_data_get_length(png) > 0) {
|
||||||
|
fl_value_append_take(
|
||||||
|
files, file_entry("", "image/png", gtk_selection_data_get_data(png),
|
||||||
|
gtk_selection_data_get_length(png)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
g_autoptr(GdkPixbuf) image = gtk_clipboard_wait_for_image(clipboard);
|
||||||
|
if (image == nullptr) return;
|
||||||
|
g_autofree gchar* buffer = nullptr;
|
||||||
|
gsize length = 0;
|
||||||
|
if (gdk_pixbuf_save_to_buffer(image, &buffer, &length, "png", nullptr,
|
||||||
|
nullptr)) {
|
||||||
|
fl_value_append_take(
|
||||||
|
files, file_entry("", "image/png",
|
||||||
|
reinterpret_cast<const guchar*>(buffer), length));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
FlValue* read_clipboard() {
|
||||||
|
GtkClipboard* clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
|
||||||
|
FlValue* files = fl_value_new_list();
|
||||||
|
FlValue* errors = fl_value_new_list();
|
||||||
|
FlValue* types = fl_value_new_list();
|
||||||
|
GdkAtom* targets = nullptr;
|
||||||
|
gint count = 0;
|
||||||
|
if (gtk_clipboard_wait_for_targets(clipboard, &targets, &count)) {
|
||||||
|
for (gint i = 0; i < count; i++) {
|
||||||
|
g_autofree gchar* name = gdk_atom_name(targets[i]);
|
||||||
|
fl_value_append_take(types, fl_value_new_string(name));
|
||||||
|
}
|
||||||
|
g_free(targets);
|
||||||
|
}
|
||||||
|
if (!add_uris(clipboard, files, errors)) add_image(clipboard, files);
|
||||||
|
FlValue* reply = fl_value_new_map();
|
||||||
|
fl_value_set_string_take(reply, "files", files);
|
||||||
|
fl_value_set_string_take(reply, "errors", errors);
|
||||||
|
fl_value_set_string_take(reply, "types", types);
|
||||||
|
return reply;
|
||||||
|
}
|
||||||
|
|
||||||
|
void method_call_cb(FlMethodChannel* channel, FlMethodCall* call,
|
||||||
|
gpointer user_data) {
|
||||||
|
g_autoptr(FlMethodResponse) response = nullptr;
|
||||||
|
if (g_strcmp0(fl_method_call_get_name(call), "read") == 0) {
|
||||||
|
g_autoptr(FlValue) reply = read_clipboard();
|
||||||
|
response = FL_METHOD_RESPONSE(fl_method_success_response_new(reply));
|
||||||
|
} else {
|
||||||
|
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
|
||||||
|
}
|
||||||
|
g_autoptr(GError) error = nullptr;
|
||||||
|
if (!fl_method_call_respond(call, response, &error)) {
|
||||||
|
g_warning("Failed to answer a clipboard read: %s", error->message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void clipboard_files_register(FlPluginRegistry* registry) {
|
||||||
|
g_autoptr(FlPluginRegistrar) registrar =
|
||||||
|
fl_plugin_registry_get_registrar_for_plugin(registry, "ClipboardFiles");
|
||||||
|
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
|
||||||
|
g_clear_object(&channel);
|
||||||
|
channel = fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar),
|
||||||
|
"pipelines/clipboard_files",
|
||||||
|
FL_METHOD_CODEC(codec));
|
||||||
|
fl_method_channel_set_method_call_handler(channel, method_call_cb, nullptr,
|
||||||
|
nullptr);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#ifndef RUNNER_CLIPBOARD_FILES_H_
|
||||||
|
#define RUNNER_CLIPBOARD_FILES_H_
|
||||||
|
|
||||||
|
#include <flutter_linux/flutter_linux.h>
|
||||||
|
|
||||||
|
// Answers `read` on the `pipelines/clipboard_files` channel with the
|
||||||
|
// clipboard's files (a file manager's copied URIs), else its image as PNG,
|
||||||
|
// plus the clipboard's target names; the same reply shape as the macOS
|
||||||
|
// Runner (lib/features/chat/domain/chat_clipboard_paste_native.dart).
|
||||||
|
void clipboard_files_register(FlPluginRegistry* registry);
|
||||||
|
|
||||||
|
#endif // RUNNER_CLIPBOARD_FILES_H_
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
#include "my_application.h"
|
#include "my_application.h"
|
||||||
|
|
||||||
#include <flutter_linux/flutter_linux.h>
|
#include <flutter_linux/flutter_linux.h>
|
||||||
|
#include <stdio.h>
|
||||||
#ifdef GDK_WINDOWING_X11
|
#ifdef GDK_WINDOWING_X11
|
||||||
#include <gdk/gdkx.h>
|
#include <gdk/gdkx.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#include "clipboard_files.h"
|
||||||
#include "flutter/generated_plugin_registrant.h"
|
#include "flutter/generated_plugin_registrant.h"
|
||||||
|
|
||||||
struct _MyApplication {
|
struct _MyApplication {
|
||||||
@@ -14,6 +16,18 @@ struct _MyApplication {
|
|||||||
|
|
||||||
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
|
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
|
||||||
|
|
||||||
|
// The bundle's icon (data/app_icon.png beside the executable) for X11 window
|
||||||
|
// managers and task bars. Wayland compositors take the icon from the desktop
|
||||||
|
// entry named by the application id instead.
|
||||||
|
static void set_window_icon(GtkWindow* window) {
|
||||||
|
g_autofree gchar* executable = g_file_read_link("/proc/self/exe", nullptr);
|
||||||
|
if (executable == nullptr) return;
|
||||||
|
g_autofree gchar* directory = g_path_get_dirname(executable);
|
||||||
|
g_autofree gchar* icon =
|
||||||
|
g_build_filename(directory, "data", "app_icon.png", nullptr);
|
||||||
|
gtk_window_set_icon_from_file(window, icon, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
// Called when first Flutter frame received.
|
// Called when first Flutter frame received.
|
||||||
static void first_frame_cb(MyApplication* self, FlView* view) {
|
static void first_frame_cb(MyApplication* self, FlView* view) {
|
||||||
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
|
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
|
||||||
@@ -25,34 +39,48 @@ static void my_application_activate(GApplication* application) {
|
|||||||
GtkWindow* window =
|
GtkWindow* window =
|
||||||
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
|
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
|
||||||
|
|
||||||
// Use a header bar when running in GNOME as this is the common style used
|
// A detached window (a chat, the terminal or a diff sent to a window of
|
||||||
// by applications and is the setup most users will be using (e.g. Ubuntu
|
// its own) is named after its item and sized for it by the main process.
|
||||||
// desktop).
|
const gchar* detached_title = g_getenv("PIPELINES_WINDOW_TITLE");
|
||||||
// If running on X and not using GNOME then just use a traditional title bar
|
const gchar* title = detached_title != nullptr && detached_title[0] != '\0'
|
||||||
// in case the window manager does more exotic layout, e.g. tiling.
|
? detached_title
|
||||||
// If running on Wayland assume the header bar will work (may need changing
|
: "Pipelines";
|
||||||
// if future cases occur).
|
|
||||||
gboolean use_header_bar = TRUE;
|
// A GTK header bar only on GNOME, whose shell expects client-side title
|
||||||
|
// bars. Elsewhere (Hyprland, Sway, KDE, any X11 window manager) the window
|
||||||
|
// takes the compositor's own decorations, or none on a tiling compositor,
|
||||||
|
// instead of drawing a second title bar inside the tile.
|
||||||
|
const gchar* desktop = g_getenv("XDG_CURRENT_DESKTOP");
|
||||||
|
gboolean use_header_bar =
|
||||||
|
desktop != nullptr && g_strrstr(desktop, "GNOME") != nullptr;
|
||||||
#ifdef GDK_WINDOWING_X11
|
#ifdef GDK_WINDOWING_X11
|
||||||
GdkScreen* screen = gtk_window_get_screen(window);
|
GdkScreen* screen = gtk_window_get_screen(window);
|
||||||
if (GDK_IS_X11_SCREEN(screen)) {
|
if (GDK_IS_X11_SCREEN(screen)) {
|
||||||
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
|
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
|
||||||
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
|
use_header_bar = g_strcmp0(wm_name, "GNOME Shell") == 0;
|
||||||
use_header_bar = FALSE;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
if (use_header_bar) {
|
if (use_header_bar) {
|
||||||
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
|
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
|
||||||
gtk_widget_show(GTK_WIDGET(header_bar));
|
gtk_widget_show(GTK_WIDGET(header_bar));
|
||||||
gtk_header_bar_set_title(header_bar, "Pipelines");
|
gtk_header_bar_set_title(header_bar, title);
|
||||||
gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
gtk_header_bar_set_show_close_button(header_bar, TRUE);
|
||||||
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
|
||||||
} else {
|
} else {
|
||||||
gtk_window_set_title(window, "Pipelines");
|
gtk_window_set_title(window, title);
|
||||||
}
|
}
|
||||||
|
set_window_icon(window);
|
||||||
|
|
||||||
gtk_window_set_default_size(window, 1280, 720);
|
gint width = 1280, height = 720;
|
||||||
|
const gchar* detached_size = g_getenv("PIPELINES_WINDOW_SIZE");
|
||||||
|
if (detached_size != nullptr) {
|
||||||
|
gint w = 0, h = 0;
|
||||||
|
if (sscanf(detached_size, "%dx%d", &w, &h) == 2 && w > 0 && h > 0) {
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
gtk_window_set_default_size(window, width, height);
|
||||||
|
|
||||||
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
g_autoptr(FlDartProject) project = fl_dart_project_new();
|
||||||
fl_dart_project_set_dart_entrypoint_arguments(
|
fl_dart_project_set_dart_entrypoint_arguments(
|
||||||
@@ -74,6 +102,7 @@ static void my_application_activate(GApplication* application) {
|
|||||||
gtk_widget_realize(GTK_WIDGET(view));
|
gtk_widget_realize(GTK_WIDGET(view));
|
||||||
|
|
||||||
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
|
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
|
||||||
|
clipboard_files_register(FL_PLUGIN_REGISTRY(view));
|
||||||
|
|
||||||
gtk_widget_grab_focus(GTK_WIDGET(view));
|
gtk_widget_grab_focus(GTK_WIDGET(view));
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,75 @@
|
|||||||
|
# Detached windows (Open in new window)
|
||||||
|
|
||||||
|
Besides floating inside the app (`notes/floating-windows.md`), a chat, the
|
||||||
|
terminal or a diff can go to a window of its own, so the app becomes
|
||||||
|
multi-window.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
|
||||||
|
- **Entry points** (only where the platform has windows, see below):
|
||||||
|
- chat pane More menu and chat list row menu: `Open in new window
|
||||||
|
(Alt+Shift+Y)`, after Float;
|
||||||
|
- a floating chat window's title bar: the same action beside Dock;
|
||||||
|
- terminal options (⋮) menu: `Open in new window`, on the selected tab;
|
||||||
|
- diff page and floating diff window bar: `Open in new window` button.
|
||||||
|
- **Shortcut**: Alt+Shift+Y (Option+Shift+Y) sends the chat with the keyboard
|
||||||
|
(a floating chat window's, else the active tiled pane's). Alt+Y stays Float.
|
||||||
|
Listed in the shortcut help under Windows.
|
||||||
|
- Once the new window is open the item leaves the main window, as Float takes
|
||||||
|
a pane out of the tiling: a tiled chat's panes close (the server-synced
|
||||||
|
open-chat workspace is written by the main window without it), its floating
|
||||||
|
window closes, the terminal hides, a diff page pops or its floating window
|
||||||
|
closes. If the window did not open, nothing moves.
|
||||||
|
- **Detached window**: route `/window/chat/<id>`, `/window/terminal?tab=<key>`
|
||||||
|
or `/window/diff/<token>` (`lib/application/detached/detached_route.dart`).
|
||||||
|
It renders only the item: the chat pane with header, find, files and
|
||||||
|
composer; the terminal's tab strip and body (no panel/float modes); or the
|
||||||
|
diff page. Its title names the item (`Chat title · Pipelines`).
|
||||||
|
`Bring back to main window` (chat More menu, terminal strip and diff bar
|
||||||
|
button) hands it back: the chat docks into the tiling (or opens in Chat),
|
||||||
|
the terminal shows on that tab, the diff opens in a floating window; then
|
||||||
|
the detached window closes. With no main window left, a chat or the terminal
|
||||||
|
turns the detached window into the full app (web) or starts a new main
|
||||||
|
process (desktop); a diff says so and stays.
|
||||||
|
- Closing a detached window just closes it.
|
||||||
|
- A detached window has its own connection and runtime and never writes the
|
||||||
|
shared layout: no Chat destination (so no `chat_open_workspace` write), no
|
||||||
|
window manager (no `pipelines.windows.v1`), and `TerminalLayout.persist` is
|
||||||
|
off. It builds no notification, attention or update machinery, so system
|
||||||
|
notifications and badges come only from the main window (per origin on the
|
||||||
|
web, the main process on a desktop).
|
||||||
|
|
||||||
|
## Platforms
|
||||||
|
|
||||||
|
- **Web**: `window.open(url, name, 'popup,width=…,height=…')`, one window name
|
||||||
|
per item (opening it again focuses that window). A blocked popup shows a
|
||||||
|
SnackBar explaining it, with `Open in tab` (a fresh click, so allowed).
|
||||||
|
Same origin: the session cookie and local preferences are shared. Bring back
|
||||||
|
posts a marked message to `window.opener` (same origin only). A diff's files
|
||||||
|
are handed over in `localStorage` under a one-time token, then kept in the
|
||||||
|
window's `sessionStorage` for reloads. The page keeps its `/window/…` URL
|
||||||
|
(the MaterialApp's only route is named by it), so a reload reopens it.
|
||||||
|
- **Linux, macOS**: Flutter 3.44's multi-window API is still experimental, so
|
||||||
|
a second process of the same executable starts with `--detached <path>`
|
||||||
|
and `PIPELINES_DETACHED=<path>` (the macOS runner does not pass arguments to
|
||||||
|
Dart). The Linux runner reads `PIPELINES_WINDOW_TITLE` and
|
||||||
|
`PIPELINES_WINDOW_SIZE` for the GTK title and default size. The child writes
|
||||||
|
Bring back as a marked line on stdout, which the parent reads; the diff
|
||||||
|
hand-over is a temp file.
|
||||||
|
- **Android, iOS**: no action (the opener scope is absent).
|
||||||
|
|
||||||
|
## Checks
|
||||||
|
|
||||||
|
- Tests: `test/application/detached/` (route parsing, opener, detached app,
|
||||||
|
no shared writes, main-window integration), `test/features/chat/
|
||||||
|
chat_new_window_test.dart`, `test/features/terminal/
|
||||||
|
terminal_new_window_test.dart`, `test/features/changes/
|
||||||
|
diff_new_window_test.dart`, `test/shell/detached/`.
|
||||||
|
- Captures (web, 2026-12-03, 1400x900, light and dark):
|
||||||
|
`tool/capture/examples/detached-chat-window.json` (pane menu, the detached
|
||||||
|
chat, its menu, the main window after, Bring back) and
|
||||||
|
`detached-terminal-window.json`. The kit's `follow=<url part|main>` step
|
||||||
|
moves to a window the page opened.
|
||||||
|
- Not verified: the native Linux/macOS processes (no CMake on the review host,
|
||||||
|
no Mac); the runner change was only syntax-checked. Installed-PWA window
|
||||||
|
behaviour was not captured (headless Chrome).
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Linux desktop: optimized build, Linux gaps, bench
|
||||||
|
|
||||||
|
Flutter 3.44.6, Docker build image (`app/docker`), tank (Ryzen, RTX 2080 Ti,
|
||||||
|
Omarchy/Hyprland). Measured 2026-12-03.
|
||||||
|
|
||||||
|
## Build flags
|
||||||
|
|
||||||
|
- `flutter build linux --release --split-debug-info` (symbols kept in the
|
||||||
|
build cache as `.debug-info/`, not archived): libapp.so 13.96 MB -> 11.27 MB.
|
||||||
|
- Icon tree shaking was silently off: Flutter's CMake backend
|
||||||
|
(`tool_backend.dart`) passes `-dTreeShakeIcons="true"` with literal quotes.
|
||||||
|
The Linux build image patches its own SDK copy (grep-guarded).
|
||||||
|
MaterialIcons-Regular.otf 1,645,184 -> 24,952 bytes.
|
||||||
|
- Bundle 37.1 MiB -> 33.1 MiB; archive 16.1 MB -> 14.3 MB.
|
||||||
|
- Not used: `--obfuscate` (no speed gain, breaks symbol names in errors);
|
||||||
|
Impeller (below).
|
||||||
|
|
||||||
|
## Impeller
|
||||||
|
|
||||||
|
The Linux release engine ignores engine switches (`FLUTTER_ENGINE_SWITCHES`
|
||||||
|
is read only in debug/profile builds) and `FlDartProject` has no Impeller
|
||||||
|
setter, so a release Linux build cannot opt in. Measured in a profile build
|
||||||
|
on Xvfb/llvmpipe (`tool/perf/linux_desktop_bench.py`, 3 runs, medians):
|
||||||
|
|
||||||
|
| renderer | startup | scroll frames | raster sum | raster median | worst frame |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| Skia (default) | 1553 ms | 31 | 1141 ms | 29.4 ms | 168 ms |
|
||||||
|
| Impeller GL | 1919 ms | 14 | 1600 ms | 103.5 ms | 302 ms |
|
||||||
|
|
||||||
|
Impeller was slower and dropped frames on the CPU rasteriser; no GPU numbers
|
||||||
|
(see below). Skia stays.
|
||||||
|
|
||||||
|
## Linux vs web (same fixture, same 30-notch wheel scroll of a rich chat)
|
||||||
|
|
||||||
|
| build | startup / first frame | frames | build sum | build max | raster sum | raster max |
|
||||||
|
|---|---|---|---|---|---|---|
|
||||||
|
| Linux release, Xvfb + llvmpipe (CPU), 1280x720 | 1241 ms (process launch) | 43 | 59 ms | 11.0 ms | 1031 ms | 105 ms |
|
||||||
|
| Web wasm, headless Chromium, no GPU, 1280x800 | 896 ms (navigation) | 57 | 126 ms | 18.3 ms | 2485 ms | 130 ms |
|
||||||
|
| Web wasm, headless Chromium, GPU, 1280x800 | 278 ms (navigation) | 69 | 128 ms | 10.6 ms | 174 ms | 8.9 ms |
|
||||||
|
|
||||||
|
Medians of 5 runs. Build (UI thread) time is GPU-independent: native
|
||||||
|
~1.4 ms/frame vs web ~1.9-2.2 ms/frame. Raster on the CPU: native 21 ms median
|
||||||
|
vs web ~44 ms mean. Native startup counts process launch, GTK, engine and
|
||||||
|
llvmpipe shader setup; the web figure starts at navigation in a running
|
||||||
|
browser, so the two are not like for like.
|
||||||
|
No Linux GPU raster or Wayland numbers: nothing here runs a GPU-backed
|
||||||
|
headless Wayland or X server (no cage/weston; Xvfb is software only), and the
|
||||||
|
operator's Hyprland session was not used.
|
||||||
|
|
||||||
|
## Linux gaps fixed
|
||||||
|
|
||||||
|
- Notifications: the bridge reported Linux unsupported; now uses
|
||||||
|
flutter_local_notifications' D-Bus implementation with the bundle icon.
|
||||||
|
- HTML artifacts: `WebViewController()` throws on Linux (no webview
|
||||||
|
implementation); the view now explains and points at Download.
|
||||||
|
- Share: share_plus throws for files on Linux; Share is no longer offered.
|
||||||
|
- Clipboard paste of files/screenshots: new GTK reader
|
||||||
|
(`linux/runner/clipboard_files.cc`) answers `pipelines/clipboard_files`;
|
||||||
|
Ctrl+V (also Omarchy's Super+V) in the composer. Compiled and contract-
|
||||||
|
tested in Dart; not exercised against a real clipboard here.
|
||||||
|
- Window: GTK header bar only on GNOME (no second title bar in a Hyprland
|
||||||
|
tile); window icon on X11; installer desktop entry `com.pipelines.app.desktop`
|
||||||
|
= GTK application id = Wayland app id.
|
||||||
|
|
||||||
|
Unchanged and already native: url_launcher (xdg-open plugin), file_picker
|
||||||
|
(xdg-desktop-portal FileChooser), keyboard shortcuts (Ctrl on non-Apple),
|
||||||
|
terminal (Dart xterm). The session cookie is stored by shared_preferences
|
||||||
|
(`~/.local/share/com.pipelines.app/shared_preferences.json`) as on the other
|
||||||
|
native platforms; there is no keyring-backed storage in the app.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_app.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||||
|
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import '../../core/transport/pipelines_client_test.dart' show FakeChannel;
|
||||||
|
import '../chat_registration_test.dart' show webServer;
|
||||||
|
import 'detached_fixtures.dart';
|
||||||
|
|
||||||
|
Future<void> _run(WidgetTester tester, ChatServer server, Duration d) async {
|
||||||
|
for (var t = 0; t < d.inMilliseconds; t += 16) {
|
||||||
|
server.answer();
|
||||||
|
await tester.pump(const Duration(milliseconds: 16));
|
||||||
|
}
|
||||||
|
server.answer();
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late FakeDetachedPlatform platform;
|
||||||
|
late ChatServer server;
|
||||||
|
|
||||||
|
Future<void> pumpChat(WidgetTester tester) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(720, 860);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
addTearDown(() => TerminalLayout.instance.persist = true);
|
||||||
|
platform = FakeDetachedPlatform();
|
||||||
|
final channel = FakeChannel()..readyCompleter.complete();
|
||||||
|
server = ChatServer(channel);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
DetachedWindowApp(
|
||||||
|
route: DetachedRoute.chat('a')!,
|
||||||
|
server: webServer(),
|
||||||
|
client: PipelinesClient(channelFactory: (_) => channel),
|
||||||
|
platform: platform,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await _run(tester, server, const Duration(milliseconds: 900));
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('a detached chat is the chat pane alone, named after it', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpChat(tester);
|
||||||
|
expect(find.byType(ChatThreadView), findsOneWidget);
|
||||||
|
expect(find.text('Hello from chat'), findsOneWidget);
|
||||||
|
// No shell: no navigation, no chat list, no other chat.
|
||||||
|
expect(find.byType(NavigationRail), findsNothing);
|
||||||
|
expect(find.byType(NavigationBar), findsNothing);
|
||||||
|
expect(find.text('Chat b'), findsNothing);
|
||||||
|
final app = tester.widget<MaterialApp>(find.byType(MaterialApp));
|
||||||
|
expect(app.title, 'Chat a · Pipelines');
|
||||||
|
// Inside a detached window there is nothing to send to another one.
|
||||||
|
final context = tester.element(find.byType(ChatThreadView));
|
||||||
|
expect(DetachedWindowScope.maybeOf(context), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a detached window writes no shared layout', (tester) async {
|
||||||
|
await pumpChat(tester);
|
||||||
|
expect(server.workspaceWrites, isEmpty);
|
||||||
|
expect(
|
||||||
|
server.requests.where((r) => r['type'] == 'chat_open_workspace'),
|
||||||
|
isEmpty,
|
||||||
|
reason: 'the open-chat workspace is the main window\'s',
|
||||||
|
);
|
||||||
|
expect(TerminalLayout.instance.persist, isFalse);
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
expect(prefs.getKeys().where((k) => k.contains('window')), isEmpty);
|
||||||
|
expect(prefs.getString(terminalLayoutKey), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Bring back hands the chat to the main window and closes', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpChat(tester);
|
||||||
|
await tester.tap(find.byTooltip('More actions').hitTestable().first);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('Bring back to main window'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(platform.sent.single, {
|
||||||
|
'type': 'bring-back',
|
||||||
|
'kind': 'chat',
|
||||||
|
'id': 'a',
|
||||||
|
});
|
||||||
|
expect(platform.closed, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('with no main window, Bring back opens the full app here', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await pumpChat(tester);
|
||||||
|
platform.mainOpen = false;
|
||||||
|
await tester.tap(find.byTooltip('More actions').hitTestable().first);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('Bring back to main window'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(platform.sent, isEmpty);
|
||||||
|
expect(platform.becameMain, '/chat/a');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:ui';
|
||||||
|
|
||||||
|
import 'package:pipelines_app/application/detached/detached_platform.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
|
||||||
|
import '../../core/transport/pipelines_client_test.dart' show FakeChannel;
|
||||||
|
|
||||||
|
/// A platform that records what it was asked to open and send.
|
||||||
|
class FakeDetachedPlatform extends DetachedPlatform {
|
||||||
|
DetachedLaunch result = DetachedLaunch.opened;
|
||||||
|
final launches = <({DetachedRoute route, String title, bool tab})>[];
|
||||||
|
final stored = <String, String>{};
|
||||||
|
final sent = <DetachedMessage>[];
|
||||||
|
bool mainOpen = true;
|
||||||
|
bool closed = false;
|
||||||
|
String? becameMain;
|
||||||
|
final incoming = StreamController<DetachedMessage>.broadcast();
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get supported => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<DetachedLaunch> launch(
|
||||||
|
DetachedRoute route, {
|
||||||
|
required String title,
|
||||||
|
required Size size,
|
||||||
|
bool tab = false,
|
||||||
|
}) async {
|
||||||
|
launches.add((route: route, title: title, tab: tab));
|
||||||
|
return tab ? DetachedLaunch.opened : result;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<DetachedMessage> get messages => incoming.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> put(String token, String json) async => stored[token] = json;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> take(String token) async => stored[token];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> sendToMain(DetachedMessage message) async {
|
||||||
|
if (!mainOpen) return false;
|
||||||
|
sent.add(message);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> closeSelf() async => closed = true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> becomeMain(String appPath) async {
|
||||||
|
becameMain = appPath;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An opener that records the items and opens them at once.
|
||||||
|
class FakeOpener implements DetachedWindowOpener {
|
||||||
|
final chats = <String>[];
|
||||||
|
final terminals = <String>[];
|
||||||
|
final diffs = <List<Map<String, Object?>>>[];
|
||||||
|
bool opens = true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void openChat(
|
||||||
|
String sessionId, {
|
||||||
|
required String title,
|
||||||
|
void Function()? onOpened,
|
||||||
|
}) {
|
||||||
|
chats.add(sessionId);
|
||||||
|
if (opens) onOpened?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void openTerminal({
|
||||||
|
String tabKey = '',
|
||||||
|
required String title,
|
||||||
|
void Function()? onOpened,
|
||||||
|
}) {
|
||||||
|
terminals.add(tabKey);
|
||||||
|
if (opens) onOpened?.call();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void openDiff(
|
||||||
|
List<Map<String, Object?>> files, {
|
||||||
|
int initialIndex = 0,
|
||||||
|
required String title,
|
||||||
|
void Function()? onOpened,
|
||||||
|
}) {
|
||||||
|
diffs.add(files);
|
||||||
|
if (opens) onOpened?.call();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers a chat app's requests over [channel] like a server with chats
|
||||||
|
/// a, b and c, recording each request (type and body).
|
||||||
|
class ChatServer {
|
||||||
|
ChatServer(this.channel, {List<Object?> openChats = const []})
|
||||||
|
: _entries = openChats;
|
||||||
|
|
||||||
|
final FakeChannel channel;
|
||||||
|
final _answered = <Object?>{};
|
||||||
|
final requests = <Map<String, dynamic>>[];
|
||||||
|
List<Object?> _entries;
|
||||||
|
int _revision = 1;
|
||||||
|
|
||||||
|
/// The open-chat writes the app sent (`chat_open_workspace_request`).
|
||||||
|
List<Map<String, dynamic>> get workspaceWrites => [
|
||||||
|
for (final request in requests)
|
||||||
|
if (request['type'] == 'chat_open_workspace' &&
|
||||||
|
request['chat_open_workspace_request'] != null)
|
||||||
|
request,
|
||||||
|
];
|
||||||
|
|
||||||
|
void answer() {
|
||||||
|
for (final raw in channel.outgoing.toList()) {
|
||||||
|
final m = jsonDecode(raw as String) as Map<String, dynamic>;
|
||||||
|
final id = m['id'];
|
||||||
|
if (id == null || !_answered.add(id)) continue;
|
||||||
|
requests.add(m);
|
||||||
|
channel.incoming.add(jsonEncode(_reply('${m['type']}', id, m)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object?> _reply(String type, Object? id, Map<String, dynamic> m) {
|
||||||
|
switch (type) {
|
||||||
|
case 'chat_sessions':
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'type': type,
|
||||||
|
'chat_sessions': [
|
||||||
|
for (final s in const ['a', 'b', 'c'])
|
||||||
|
{
|
||||||
|
'id': s,
|
||||||
|
'title': 'Chat $s',
|
||||||
|
'directory': '/workspace/demo',
|
||||||
|
'updated_at': '2026-11-12T10:00:00Z',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
case 'chat_messages':
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'type': 'chat_history',
|
||||||
|
'chat_history': {
|
||||||
|
'messages': [
|
||||||
|
{
|
||||||
|
'id': 'm0',
|
||||||
|
'role': 'user',
|
||||||
|
'parts': [
|
||||||
|
{'type': 'text', 'text': 'Hello from chat'},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'next_cursor': '',
|
||||||
|
'has_more': false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
case 'chat_open_workspace':
|
||||||
|
final write = m['chat_open_workspace_request'] as Map?;
|
||||||
|
if (write != null) {
|
||||||
|
_revision++;
|
||||||
|
_entries = write['entries'] as List<Object?>;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
'id': id,
|
||||||
|
'type': type,
|
||||||
|
'chat_open_workspace': {'revision': _revision, 'entries': _entries},
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return {'id': id, 'type': type};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_windows.dart';
|
||||||
|
import 'package:pipelines_app/application/pipelines_app.dart';
|
||||||
|
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
import '../../core/transport/pipelines_client_test.dart' show FakeChannel;
|
||||||
|
import '../chat_registration_test.dart' show webServer;
|
||||||
|
import 'detached_fixtures.dart';
|
||||||
|
|
||||||
|
Future<void> _run(WidgetTester tester, ChatServer server, Duration d) async {
|
||||||
|
for (var t = 0; t < d.inMilliseconds; t += 16) {
|
||||||
|
server.answer();
|
||||||
|
await tester.pump(const Duration(milliseconds: 16));
|
||||||
|
}
|
||||||
|
server.answer();
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
Future<(ChatServer, FakeDetachedPlatform)> pump(
|
||||||
|
WidgetTester tester, {
|
||||||
|
String route = '/chat/a',
|
||||||
|
}) async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
tester.view.physicalSize = const Size(1600, 1000);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
final platform = FakeDetachedPlatform();
|
||||||
|
final channel = FakeChannel()..readyCompleter.complete();
|
||||||
|
final server = ChatServer(
|
||||||
|
channel,
|
||||||
|
openChats: [
|
||||||
|
{'session_id': 'a'},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
final provider = PlatformRouteInformationProvider(
|
||||||
|
initialRouteInformation: RouteInformation(uri: Uri.parse(route)),
|
||||||
|
);
|
||||||
|
addTearDown(provider.dispose);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
PipelinesApp(
|
||||||
|
androidSupported: false,
|
||||||
|
server: webServer(),
|
||||||
|
client: PipelinesClient(channelFactory: (_) => channel),
|
||||||
|
routeInformationProvider: provider,
|
||||||
|
detachedPlatform: platform,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await _run(tester, server, const Duration(milliseconds: 1200));
|
||||||
|
return (server, platform);
|
||||||
|
}
|
||||||
|
|
||||||
|
testWidgets('the main window offers new windows and sends the chat out of '
|
||||||
|
'its workspace', (tester) async {
|
||||||
|
final (server, platform) = await pump(tester);
|
||||||
|
final thread = find.byType(ChatThreadView);
|
||||||
|
expect(thread, findsOneWidget);
|
||||||
|
expect(DetachedWindowScope.maybeOf(tester.element(thread)), isNotNull);
|
||||||
|
await tester.tap(
|
||||||
|
find
|
||||||
|
.descendant(of: thread, matching: find.byTooltip('More actions'))
|
||||||
|
.hitTestable(),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.text('Open in new window (Alt+Shift+Y)'));
|
||||||
|
await _run(tester, server, const Duration(milliseconds: 600));
|
||||||
|
expect(platform.launches.single.route, DetachedRoute.chat('a'));
|
||||||
|
expect(platform.launches.single.title, 'Chat a');
|
||||||
|
expect(find.byType(ChatThreadView), findsNothing);
|
||||||
|
// The main window's own workspace is written without the chat.
|
||||||
|
final write = server.workspaceWrites.last['chat_open_workspace_request'];
|
||||||
|
expect((write as Map)['entries'], isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a chat brought back opens in the main window', (tester) async {
|
||||||
|
final (server, platform) = await pump(tester, route: '/runs');
|
||||||
|
expect(find.byType(ChatThreadView), findsNothing);
|
||||||
|
platform.incoming.add(
|
||||||
|
const DetachedReturn(DetachedKind.chat, 'b').toMessage(),
|
||||||
|
);
|
||||||
|
await _run(tester, server, const Duration(milliseconds: 900));
|
||||||
|
final thread = tester.widget<ChatThreadView>(find.byType(ChatThreadView));
|
||||||
|
expect(thread.sessionId, 'b');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_platform.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('each kind round-trips through its path', () {
|
||||||
|
final routes = [
|
||||||
|
DetachedRoute.chat('sess_01-A')!,
|
||||||
|
DetachedRoute.terminal(),
|
||||||
|
DetachedRoute.terminal('mac/term 1'),
|
||||||
|
DetachedRoute.diff('Tok_en-9')!,
|
||||||
|
];
|
||||||
|
for (final route in routes) {
|
||||||
|
expect(DetachedRoute.parse(route.path), route, reason: route.path);
|
||||||
|
}
|
||||||
|
expect(DetachedRoute.chat('a')!.path, '/window/chat/a');
|
||||||
|
expect(DetachedRoute.terminal().path, '/window/terminal');
|
||||||
|
expect(
|
||||||
|
DetachedRoute.terminal('server/t1').path,
|
||||||
|
'/window/terminal?tab=server%2Ft1',
|
||||||
|
);
|
||||||
|
expect(DetachedRoute.diff('abc')!.path, '/window/diff/abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a full URL with an origin and fixture parameters parses', () {
|
||||||
|
final route = DetachedRoute.parse(
|
||||||
|
'https://tank.example.ts.net/window/chat/perf-chat-0?chats=2&theme=dark',
|
||||||
|
);
|
||||||
|
expect(route, DetachedRoute.chat('perf-chat-0'));
|
||||||
|
expect(
|
||||||
|
DetachedRoute.parse('http://x/window/terminal?tab=s%2F7&theme=dark'),
|
||||||
|
DetachedRoute.terminal('s/7'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ordinary app locations and malformed windows are not detached', () {
|
||||||
|
for (final location in [
|
||||||
|
'/',
|
||||||
|
'/chat/a',
|
||||||
|
'/runs/7',
|
||||||
|
'/window',
|
||||||
|
'/window/chat',
|
||||||
|
'/window/chat/a/b',
|
||||||
|
'/window/chat/not%20valid',
|
||||||
|
'/window/diff/has.dot',
|
||||||
|
'/window/diff/${'x' * 65}',
|
||||||
|
'/window/pipelines/3',
|
||||||
|
'/windows/chat/a',
|
||||||
|
'',
|
||||||
|
]) {
|
||||||
|
expect(DetachedRoute.parse(location), isNull, reason: location);
|
||||||
|
}
|
||||||
|
expect(DetachedRoute.chat('no spaces'), isNull);
|
||||||
|
expect(DetachedRoute.diff(''), isNull);
|
||||||
|
expect(DetachedRoute.terminal('k' * 600).id, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a native launch names its window by argument or environment', () {
|
||||||
|
final chat = DetachedRoute.chat('a');
|
||||||
|
expect(DetachedRoute.fromLaunch(['--detached', '/window/chat/a']), chat);
|
||||||
|
expect(DetachedRoute.fromLaunch(['--detached=/window/chat/a']), chat);
|
||||||
|
expect(
|
||||||
|
DetachedRoute.fromLaunch(const [], {
|
||||||
|
'PIPELINES_DETACHED': '/window/terminal',
|
||||||
|
}),
|
||||||
|
DetachedRoute.terminal(),
|
||||||
|
);
|
||||||
|
expect(DetachedRoute.fromLaunch(const []), isNull);
|
||||||
|
expect(
|
||||||
|
DetachedRoute.fromLaunch(const [], {'PIPELINES_DETACHED': ''}),
|
||||||
|
isNull,
|
||||||
|
);
|
||||||
|
expect(DetachedRoute.fromLaunch(['--detached']), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('messages carry a marker; anything else is ignored', () {
|
||||||
|
final text = encodeDetachedMessage({'type': 'bring-back', 'id': 'a'});
|
||||||
|
expect(decodeDetachedMessage(text), {'type': 'bring-back', 'id': 'a'});
|
||||||
|
expect(decodeDetachedMessage('{"type":"bring-back"}'), isNull);
|
||||||
|
expect(decodeDetachedMessage('not json'), isNull);
|
||||||
|
expect(decodeDetachedMessage('[1]'), isNull);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_platform.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_windows.dart';
|
||||||
|
|
||||||
|
import 'detached_fixtures.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
late FakeDetachedPlatform platform;
|
||||||
|
late List<DetachedReturn> returned;
|
||||||
|
late GlobalKey<ScaffoldMessengerState> messenger;
|
||||||
|
late DetachedWindows windows;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
platform = FakeDetachedPlatform();
|
||||||
|
returned = [];
|
||||||
|
messenger = GlobalKey<ScaffoldMessengerState>();
|
||||||
|
windows = DetachedWindows(
|
||||||
|
platform: platform,
|
||||||
|
onReturn: returned.add,
|
||||||
|
messenger: messenger,
|
||||||
|
)..start();
|
||||||
|
});
|
||||||
|
tearDown(() => windows.dispose());
|
||||||
|
|
||||||
|
Future<void> host(WidgetTester tester) => tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
scaffoldMessengerKey: messenger,
|
||||||
|
home: const Scaffold(body: SizedBox()),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('an opened window runs onOpened; the item leaves after', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await host(tester);
|
||||||
|
var opened = 0;
|
||||||
|
windows.openChat('a', title: 'Chat a', onOpened: () => opened++);
|
||||||
|
await tester.pump();
|
||||||
|
expect(platform.launches.single.route, DetachedRoute.chat('a'));
|
||||||
|
expect(platform.launches.single.title, 'Chat a');
|
||||||
|
expect(opened, 1);
|
||||||
|
|
||||||
|
windows.openTerminal(tabKey: 's/1', title: 'Terminal: zsh');
|
||||||
|
await tester.pump();
|
||||||
|
expect(platform.launches.last.route, DetachedRoute.terminal('s/1'));
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a blocked popup says so and offers a tab, which opens it', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await host(tester);
|
||||||
|
platform.result = DetachedLaunch.blocked;
|
||||||
|
var opened = 0;
|
||||||
|
windows.openChat('a', title: 'Chat a', onOpened: () => opened++);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(opened, 0, reason: 'nothing leaves the main window yet');
|
||||||
|
expect(find.textContaining('blocked the new window'), findsOneWidget);
|
||||||
|
await tester.tap(find.text('Open in tab'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(platform.launches.last.tab, isTrue);
|
||||||
|
expect(opened, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a failure is reported and the item stays', (tester) async {
|
||||||
|
await host(tester);
|
||||||
|
platform.result = DetachedLaunch.failed;
|
||||||
|
var opened = 0;
|
||||||
|
windows.openChat('a', title: 'Chat a', onOpened: () => opened++);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('Could not open a new window.'), findsOneWidget);
|
||||||
|
expect(opened, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a diff is handed over under its token before it opens', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await host(tester);
|
||||||
|
windows.openDiff(
|
||||||
|
[
|
||||||
|
{'path': 'lib/a.dart', 'kind': 'modified'},
|
||||||
|
],
|
||||||
|
initialIndex: 0,
|
||||||
|
title: 'a.dart',
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
final route = platform.launches.single.route;
|
||||||
|
expect(route.kind, DetachedKind.diff);
|
||||||
|
final stored = jsonDecode(platform.stored[route.id]!) as Map;
|
||||||
|
expect((stored['files'] as List).single['path'], 'lib/a.dart');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('items a detached window gives back reach the main window', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await host(tester);
|
||||||
|
const diff = DetachedReturn(
|
||||||
|
DetachedKind.diff,
|
||||||
|
'tok',
|
||||||
|
files: [
|
||||||
|
{'path': 'a', 'kind': 'added'},
|
||||||
|
],
|
||||||
|
initialIndex: 0,
|
||||||
|
);
|
||||||
|
platform.incoming
|
||||||
|
..add(const DetachedReturn(DetachedKind.chat, 'a').toMessage())
|
||||||
|
..add(diff.toMessage())
|
||||||
|
..add({'type': 'something else'});
|
||||||
|
await tester.pump();
|
||||||
|
expect(returned.map((r) => (r.kind, r.id)), [
|
||||||
|
(DetachedKind.chat, 'a'),
|
||||||
|
(DetachedKind.diff, 'tok'),
|
||||||
|
]);
|
||||||
|
expect(returned.last.files.single['path'], 'a');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer_io.dart'
|
||||||
|
as transfer;
|
||||||
|
import 'package:pipelines_app/features/artifacts/ui/artifact_html_view_native.dart';
|
||||||
|
|
||||||
|
final _linux = TargetPlatformVariant.only(TargetPlatform.linux);
|
||||||
|
|
||||||
|
/// The Linux app has no web view and no file share sheet: it says so rather
|
||||||
|
/// than failing to create the web view or throwing from Share.
|
||||||
|
void main() {
|
||||||
|
test('only Android, iOS and macOS have the HTML web view', () {
|
||||||
|
for (final platform in TargetPlatform.values) {
|
||||||
|
expect(
|
||||||
|
inertHtmlViewSupported(platform),
|
||||||
|
platform == TargetPlatform.android ||
|
||||||
|
platform == TargetPlatform.iOS ||
|
||||||
|
platform == TargetPlatform.macOS,
|
||||||
|
reason: '$platform',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('an HTML artifact on Linux explains why it is not previewed', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(body: InertHtmlView(html: '<p>report</p>')),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(find.text(inertHtmlUnsupportedMessage), findsOneWidget);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
// A new document does not reach for a web view either.
|
||||||
|
await tester.pumpWidget(
|
||||||
|
const MaterialApp(
|
||||||
|
home: Scaffold(body: InertHtmlView(html: '<p>next</p>')),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
}, variant: _linux);
|
||||||
|
|
||||||
|
testWidgets('Linux offers Download but not Share', (tester) async {
|
||||||
|
expect(transfer.artifactDownloadSupported, isTrue);
|
||||||
|
expect(transfer.artifactShareSupported, isFalse);
|
||||||
|
expect(transfer.artifactShareUnsupportedMessage, contains('Download'));
|
||||||
|
}, variant: _linux);
|
||||||
|
|
||||||
|
test('other native platforms keep Share', () {
|
||||||
|
expect(transfer.artifactShareSupported, isTrue);
|
||||||
|
expect(transfer.artifactShareUnsupportedMessage, isEmpty);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_diff.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_window_body.dart';
|
||||||
|
import 'package:pipelines_app/features/changes/changes.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
|
||||||
|
import '../../application/detached/detached_fixtures.dart';
|
||||||
|
|
||||||
|
FileChange _file(String path) => FileChange(
|
||||||
|
path: path,
|
||||||
|
kind: ChangeKind.modified,
|
||||||
|
patch: '--- a/$path\n+++ b/$path\n@@ -0,0 +1,1 @@\n+line of $path\n',
|
||||||
|
beforeMode: '100644',
|
||||||
|
afterMode: '100755',
|
||||||
|
).withSteps(const ['build']);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
setUp(() => diffShowsAllFiles.value = false);
|
||||||
|
|
||||||
|
test('a file change survives the hand-over to another window', () {
|
||||||
|
final file = _file('lib/a.dart');
|
||||||
|
final back = FileChange.fromHandover(
|
||||||
|
jsonDecode(jsonEncode(file.toJson())),
|
||||||
|
)!;
|
||||||
|
expect(back.path, file.path);
|
||||||
|
expect(back.kind, file.kind);
|
||||||
|
expect(back.patch, file.patch);
|
||||||
|
expect(back.beforeMode, '100644');
|
||||||
|
expect(back.afterMode, '100755');
|
||||||
|
expect(back.steps, ['build']);
|
||||||
|
expect(back.added, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a diff page offers Open in new window and closes once open', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
tester.view.physicalSize = const Size(1000, 700);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
final opener = FakeOpener();
|
||||||
|
final files = [_file('lib/a.dart'), _file('lib/b.dart')];
|
||||||
|
await tester.pumpWidget(
|
||||||
|
DetachedWindowScope(
|
||||||
|
opener: opener,
|
||||||
|
child: MaterialApp(
|
||||||
|
home: Builder(
|
||||||
|
builder: (context) => Scaffold(
|
||||||
|
body: TextButton(
|
||||||
|
onPressed: () =>
|
||||||
|
showFileDiffViewer(context, files[1], files: files),
|
||||||
|
child: const Text('open'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.tap(find.text('open'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(FileDiffPage), findsOneWidget);
|
||||||
|
await tester.tap(find.byTooltip('Open in new window'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(opener.diffs.single.map((f) => f['path']), [
|
||||||
|
'lib/a.dart',
|
||||||
|
'lib/b.dart',
|
||||||
|
]);
|
||||||
|
expect(find.byType(FileDiffPage), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('without platform windows the diff page has no such button', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(home: FileDiffPage(files: [_file('a')])),
|
||||||
|
);
|
||||||
|
expect(find.byTooltip('Open in new window'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a detached diff shows the handed files and gives them back', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
tester.view.physicalSize = const Size(1000, 820);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
final platform = FakeDetachedPlatform();
|
||||||
|
platform.stored['tok'] = jsonEncode({
|
||||||
|
'files': [_file('lib/a.dart').toJson(), _file('lib/b.dart').toJson()],
|
||||||
|
'index': 1,
|
||||||
|
});
|
||||||
|
final titles = <String>[];
|
||||||
|
final back = <(DetachedKind, String, int, int)>[];
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: DetachedDiff(
|
||||||
|
token: 'tok',
|
||||||
|
platform: platform,
|
||||||
|
window: DetachedWindowControls(
|
||||||
|
ready: ValueNotifier(true),
|
||||||
|
sync: ValueNotifier(0),
|
||||||
|
setTitle: titles.add,
|
||||||
|
close: () {},
|
||||||
|
bringBackItem: (kind, id, files, index) =>
|
||||||
|
back.add((kind, id, files.length, index)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(FileDiffPage), findsOneWidget);
|
||||||
|
expect(titles.last, '2 files changed');
|
||||||
|
expect(find.text('b.dart'), findsWidgets);
|
||||||
|
// No Back in a window of its own, and no window to open from it.
|
||||||
|
expect(find.byType(BackButton), findsNothing);
|
||||||
|
expect(find.byTooltip('Open in new window'), findsNothing);
|
||||||
|
await tester.tap(find.byTooltip('Bring back to main window'));
|
||||||
|
expect(back, [(DetachedKind.diff, 'tok', 2, 1)]);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a diff handed over to nobody says it is gone', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: DetachedDiff(
|
||||||
|
token: 'missing',
|
||||||
|
platform: FakeDetachedPlatform(),
|
||||||
|
window: DetachedWindowControls(
|
||||||
|
ready: ValueNotifier(true),
|
||||||
|
sync: ValueNotifier(0),
|
||||||
|
setTitle: (_) {},
|
||||||
|
close: () {},
|
||||||
|
bringBackItem: (_, _, _, _) {},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('This diff is no longer available.'), findsOneWidget);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ const _expected = {
|
|||||||
'budget':
|
'budget':
|
||||||
'The workspace snapshot ran out of text budget, so no diff text was '
|
'The workspace snapshot ran out of text budget, so no diff text was '
|
||||||
'recorded.',
|
'recorded.',
|
||||||
'lines': 'The change is over 5,000 lines, so no diff text was recorded.',
|
'lines': 'The change is over 20,000 lines, so no diff text was recorded.',
|
||||||
'evidence_size':
|
'evidence_size':
|
||||||
"This visit's recorded changes reached their size limit, so this patch "
|
"This visit's recorded changes reached their size limit, so this patch "
|
||||||
'was dropped.',
|
'was dropped.',
|
||||||
@@ -24,6 +24,15 @@ const _expected = {
|
|||||||
"The file's content at stage start couldn't be recovered from Git, so no "
|
"The file's content at stage start couldn't be recovered from Git, so no "
|
||||||
'diff was recorded.',
|
'diff was recorded.',
|
||||||
'binary': 'Binary file; only its metadata was recorded.',
|
'binary': 'Binary file; only its metadata was recorded.',
|
||||||
|
'symlink': 'Symbolic link; only the change to its target was recorded.',
|
||||||
|
'protected':
|
||||||
|
'A protected file (secrets, credentials or a database); its content is '
|
||||||
|
'never read, only that it changed.',
|
||||||
|
'generated':
|
||||||
|
'A lockfile, minified or generated file; it is listed without a diff.',
|
||||||
|
'large':
|
||||||
|
'This file is too large to hash, so it was compared by size and '
|
||||||
|
'modification time only.',
|
||||||
};
|
};
|
||||||
|
|
||||||
FileChange _noPatch(Object? reason, {bool binary = false}) =>
|
FileChange _noPatch(Object? reason, {bool binary = false}) =>
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
import 'package:pipelines_app/core/api_gateway.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/screen.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/windows/chat_windows.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/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 '../../application/detached/detached_fixtures.dart';
|
||||||
|
import 'conversation/chat_thread_fixtures.dart';
|
||||||
|
|
||||||
|
class _Gateway extends FakeChatGateway {
|
||||||
|
@override
|
||||||
|
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
|
||||||
|
if (type == 'chat_sessions') {
|
||||||
|
return Future.value({
|
||||||
|
'chat_sessions': [
|
||||||
|
for (final id in ['a', 'b', 'c'])
|
||||||
|
{'id': id, 'title': 'Chat $id', 'directory': '/home/$id'},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (type == 'chat_shells') return Future.value({'chat_shells': []});
|
||||||
|
return super.call(type, fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const _label = 'Open in new window (Alt+Shift+Y)';
|
||||||
|
|
||||||
|
Finder _thread(String id) => find.byWidgetPredicate(
|
||||||
|
(widget) => widget is ChatThreadView && widget.sessionId == id,
|
||||||
|
skipOffstage: false,
|
||||||
|
);
|
||||||
|
|
||||||
|
List<String> _tiled(WidgetTester tester) => [
|
||||||
|
for (final pane
|
||||||
|
in tester
|
||||||
|
.widget<ChatWorkspace>(
|
||||||
|
find.byType(ChatWorkspace, skipOffstage: false),
|
||||||
|
)
|
||||||
|
.controller
|
||||||
|
.panes)
|
||||||
|
pane.sessionId,
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The Chat destination with its floating windows, as the app hosts them,
|
||||||
|
/// with [opener] as the platform's new windows (none when null).
|
||||||
|
class _App {
|
||||||
|
final gateway = _Gateway()..history = (_) async => chatPage([]);
|
||||||
|
final opener = FakeOpener();
|
||||||
|
late final ChatRuntime runtime;
|
||||||
|
late final WindowManager manager;
|
||||||
|
late final ChatWindows windows;
|
||||||
|
|
||||||
|
Future<void> start(WidgetTester tester, {bool detached = true}) async {
|
||||||
|
tester.view.physicalSize = const Size(1800, 1000);
|
||||||
|
tester.view.devicePixelRatio = 1;
|
||||||
|
addTearDown(tester.view.reset);
|
||||||
|
final layout = ChatWorkspaceController()
|
||||||
|
..open('a')
|
||||||
|
..splitActive('b', ChatSplitAxis.horizontal);
|
||||||
|
SharedPreferences.setMockInitialValues({
|
||||||
|
scopedServerKey(chatWorkspacePreferenceKey, 'server-a'): layout
|
||||||
|
.snapshot()!
|
||||||
|
.encode(),
|
||||||
|
});
|
||||||
|
bindServerIdentity(gateway, 'server-a');
|
||||||
|
runtime = ChatRuntime(gateway: gateway, serverKey: 'server-a');
|
||||||
|
manager = WindowManager(kinds: WindowKinds(), server: 'server-a');
|
||||||
|
windows = ChatWindows(
|
||||||
|
manager: manager,
|
||||||
|
runtime: runtime,
|
||||||
|
openInChat: (_) {},
|
||||||
|
)..start();
|
||||||
|
if (detached) windows.detached = opener;
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: Stack(
|
||||||
|
fit: StackFit.expand,
|
||||||
|
children: [
|
||||||
|
ChatScreen(
|
||||||
|
gateway: gateway,
|
||||||
|
persistWorkspace: true,
|
||||||
|
runtime: runtime,
|
||||||
|
windows: windows,
|
||||||
|
),
|
||||||
|
Positioned.fill(child: WindowHost(manager: manager)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
addTearDown(() async {
|
||||||
|
await tester.pumpWidget(const SizedBox.shrink());
|
||||||
|
windows.dispose();
|
||||||
|
runtime.dispose();
|
||||||
|
manager.dispose();
|
||||||
|
gateway.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
List<String> get floating => [for (final w in windows.windows) w.contentId];
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _paneMenu(WidgetTester tester, String session) async {
|
||||||
|
await tester.tap(
|
||||||
|
find
|
||||||
|
.descendant(
|
||||||
|
of: _thread(session),
|
||||||
|
matching: find.byTooltip('More actions'),
|
||||||
|
)
|
||||||
|
.hitTestable(),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _rowMenu(WidgetTester tester, String id) async {
|
||||||
|
await tester.tap(find.byTooltip('Chat actions for Chat $id').first);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('the pane menu sends a tiled chat to a new window', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
expect(_tiled(tester), ['a', 'b']);
|
||||||
|
await _paneMenu(tester, 'b');
|
||||||
|
expect(find.text('Float (Alt+Y)'), findsOneWidget);
|
||||||
|
await tester.tap(find.text(_label));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.opener.chats, ['b']);
|
||||||
|
// It left the tiling, as Float takes it out, and no floating window.
|
||||||
|
expect(_tiled(tester), ['a']);
|
||||||
|
expect(app.floating, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a chat whose window did not open stays where it was', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
app.opener.opens = false;
|
||||||
|
await _paneMenu(tester, 'b');
|
||||||
|
await tester.tap(find.text(_label));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.opener.chats, ['b']);
|
||||||
|
expect(_tiled(tester), ['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('without platform windows the action is not offered', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester, detached: false);
|
||||||
|
await _paneMenu(tester, 'b');
|
||||||
|
expect(find.text('Float (Alt+Y)'), findsOneWidget);
|
||||||
|
expect(find.textContaining('new window'), findsNothing);
|
||||||
|
await tester.tapAt(const Offset(5, 995));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await _rowMenu(tester, 'c');
|
||||||
|
expect(find.textContaining('new window'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the row menu offers it after Float, for any chat', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
await _rowMenu(tester, 'c');
|
||||||
|
final float = tester.getTopLeft(find.text('Float (Alt+Y)').last);
|
||||||
|
final open = tester.getTopLeft(find.text(_label).last);
|
||||||
|
expect(open.dy, greaterThan(float.dy));
|
||||||
|
await tester.tap(find.text(_label).last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.opener.chats, ['c']);
|
||||||
|
expect(_tiled(tester), ['a', 'b']);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a floating chat goes to a new window from its title bar', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
await _rowMenu(tester, 'c');
|
||||||
|
await tester.tap(find.text('Float (Alt+Y)').last);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.floating, ['c']);
|
||||||
|
final window = find.ancestor(
|
||||||
|
of: find.text('Chat c'),
|
||||||
|
matching: find.byType(WindowFrame),
|
||||||
|
);
|
||||||
|
await tester.tap(
|
||||||
|
find.descendant(of: window, matching: find.byTooltip(_label)).first,
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.opener.chats, ['c']);
|
||||||
|
expect(app.floating, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Alt+Shift+Y sends the active pane; Alt+Y still floats', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
// The keyboard is in chat b's composer, the active pane.
|
||||||
|
await tester.tap(
|
||||||
|
find
|
||||||
|
.descendant(
|
||||||
|
of: find.byKey(const ValueKey('chat-composer-b')),
|
||||||
|
matching: find.byType(EditableText),
|
||||||
|
)
|
||||||
|
.first,
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
|
||||||
|
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
|
||||||
|
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
|
||||||
|
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
|
||||||
|
await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(app.opener.chats, ['b']);
|
||||||
|
expect(_tiled(tester), ['a']);
|
||||||
|
expect(app.floating, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a chat brought back from its window joins the tiling', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final app = _App();
|
||||||
|
await app.start(tester);
|
||||||
|
app.windows.bringBack('c');
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(_tiled(tester), ['a', 'b', 'c']);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart';
|
|||||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
|
import 'package:pipelines_app/features/chat/conversation/chat_composer_bar.dart';
|
||||||
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
|
import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart';
|
||||||
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste_native.dart';
|
||||||
|
|
||||||
import '../../../core/keyboard/browser_keys.dart';
|
import '../../../core/keyboard/browser_keys.dart';
|
||||||
import 'chat_composer_bar_fixtures.dart';
|
import 'chat_composer_bar_fixtures.dart';
|
||||||
@@ -32,6 +33,12 @@ void main() {
|
|||||||
if (call.method == 'Clipboard.hasStrings') return {'value': true};
|
if (call.method == 'Clipboard.hasStrings') return {'value': true};
|
||||||
return null;
|
return null;
|
||||||
});
|
});
|
||||||
|
// The Linux Runner's clipboard reader: no files, so the text is pasted.
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(
|
||||||
|
chatClipboardFilesChannel,
|
||||||
|
(call) async => {'files': const [], 'errors': const []},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
tearDown(() {
|
tearDown(() {
|
||||||
@@ -39,6 +46,8 @@ void main() {
|
|||||||
gateway.close();
|
gateway.close();
|
||||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
.setMockMethodCallHandler(SystemChannels.platform, null);
|
.setMockMethodCallHandler(SystemChannels.platform, null);
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(chatClipboardFilesChannel, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
for (final merged in [false, true]) {
|
for (final merged in [false, true]) {
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste_native.d
|
|||||||
import '../conversation/chat_composer_bar_fixtures.dart';
|
import '../conversation/chat_composer_bar_fixtures.dart';
|
||||||
|
|
||||||
final _macOS = TargetPlatformVariant.only(TargetPlatform.macOS);
|
final _macOS = TargetPlatformVariant.only(TargetPlatform.macOS);
|
||||||
|
final _linux = TargetPlatformVariant.only(TargetPlatform.linux);
|
||||||
|
|
||||||
Finder get _field => find.byKey(const Key('chat-composer-field'));
|
Finder get _field => find.byKey(const Key('chat-composer-field'));
|
||||||
|
|
||||||
@@ -77,10 +78,10 @@ void main() {
|
|||||||
|
|
||||||
Future<void> done(WidgetTester tester) => tester.pumpWidget(const SizedBox());
|
Future<void> done(WidgetTester tester) => tester.pumpWidget(const SizedBox());
|
||||||
|
|
||||||
test('only the macOS host reads clipboard files natively', () {
|
test('the macOS and Linux hosts read clipboard files natively', () {
|
||||||
expect(chatHostReadsClipboardFiles(TargetPlatform.macOS), isTrue);
|
expect(chatHostReadsClipboardFiles(TargetPlatform.macOS), isTrue);
|
||||||
|
expect(chatHostReadsClipboardFiles(TargetPlatform.linux), isTrue);
|
||||||
for (final platform in [
|
for (final platform in [
|
||||||
TargetPlatform.linux,
|
|
||||||
TargetPlatform.windows,
|
TargetPlatform.windows,
|
||||||
TargetPlatform.android,
|
TargetPlatform.android,
|
||||||
TargetPlatform.iOS,
|
TargetPlatform.iOS,
|
||||||
@@ -228,4 +229,47 @@ void main() {
|
|||||||
expect(composer.draft, isEmpty);
|
expect(composer.draft, isEmpty);
|
||||||
await done(tester);
|
await done(tester);
|
||||||
}, variant: _macOS);
|
}, variant: _macOS);
|
||||||
|
|
||||||
|
testWidgets('Ctrl+V attaches a copied screenshot on Linux', (tester) async {
|
||||||
|
pasteboard = {
|
||||||
|
'files': [
|
||||||
|
{
|
||||||
|
'name': '',
|
||||||
|
'mime': 'image/png',
|
||||||
|
'bytes': Uint8List.fromList([3]),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'errors': const [],
|
||||||
|
};
|
||||||
|
expect(hostChatClipboardPaste.isSupported, isTrue);
|
||||||
|
await mount(tester);
|
||||||
|
await tester.showKeyboard(_field);
|
||||||
|
await tester.pump();
|
||||||
|
await paste(tester, modifier: LogicalKeyboardKey.controlLeft);
|
||||||
|
|
||||||
|
expect(fileReads, 1);
|
||||||
|
expect(find.text('pasted-1.png'), findsOneWidget);
|
||||||
|
expect(textReads, 0);
|
||||||
|
await done(tester);
|
||||||
|
}, variant: _linux);
|
||||||
|
|
||||||
|
testWidgets('Ctrl+V of plain text on Linux pastes it once', (tester) async {
|
||||||
|
await mount(tester);
|
||||||
|
await tester.showKeyboard(_field);
|
||||||
|
await paste(tester, modifier: LogicalKeyboardKey.controlLeft);
|
||||||
|
|
||||||
|
expect(fileReads, 1);
|
||||||
|
expect(composer.draft, 'copied text');
|
||||||
|
await done(tester);
|
||||||
|
}, variant: _linux);
|
||||||
|
|
||||||
|
testWidgets('the Super key is not the Linux paste shortcut', (tester) async {
|
||||||
|
await mount(tester);
|
||||||
|
FocusManager.instance.primaryFocus?.unfocus();
|
||||||
|
await tester.pump();
|
||||||
|
await paste(tester);
|
||||||
|
|
||||||
|
expect(fileReads, 0);
|
||||||
|
await done(tester);
|
||||||
|
}, variant: _linux);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
import 'package:pipelines_app/features/graph/domain/check_stage.dart';
|
||||||
|
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||||
|
import 'package:pipelines_app/features/graph/domain/stage_definition.dart';
|
||||||
|
|
||||||
|
Map<String, dynamic> _verify({Map<String, dynamic>? configs}) => {
|
||||||
|
'key': 'verify',
|
||||||
|
'type': 'check',
|
||||||
|
'configs':
|
||||||
|
configs ??
|
||||||
|
{
|
||||||
|
'command_timeout': '15m',
|
||||||
|
'timeout': '1h',
|
||||||
|
'keep_going': 'true',
|
||||||
|
'delivery': 'true',
|
||||||
|
},
|
||||||
|
'edges': {'pass': 'review', 'fail': 'implement', 'error': '#failure'},
|
||||||
|
'blocks': {'commands': 'go vet ./...\n\ngo test ./...\n'},
|
||||||
|
'prompt': '',
|
||||||
|
'output': '',
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a check stage reads its commands, one per non-blank line', () {
|
||||||
|
expect(isCheckStage(_verify()), isTrue);
|
||||||
|
expect(checkCommands(_verify()), ['go vet ./...', 'go test ./...']);
|
||||||
|
expect(isCheckStage({'type': 'model'}), isFalse);
|
||||||
|
expect(isCheckStage({'key': 'x'}), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the delivery config marks the gate, and only on a check stage', () {
|
||||||
|
expect(isDeliveryGate(_verify()), isTrue);
|
||||||
|
expect(isDeliveryGate(_verify(configs: {'delivery': 'false'})), isFalse);
|
||||||
|
expect(isDeliveryGate(_verify(configs: {})), isFalse);
|
||||||
|
expect(
|
||||||
|
isDeliveryGate({
|
||||||
|
'type': 'model',
|
||||||
|
'configs': {'delivery': 'true'},
|
||||||
|
}),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('graph nodes carry the stage type and the gate caption', () {
|
||||||
|
final nodes = graphNodes({
|
||||||
|
'stages': [
|
||||||
|
_verify(),
|
||||||
|
{
|
||||||
|
..._verify(configs: {}),
|
||||||
|
'key': 'lint',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'key': 'review',
|
||||||
|
'edges': {'success': '#'},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
final byKey = {for (final node in nodes) node.key: node};
|
||||||
|
expect(byKey['verify']!.kindCaption, 'Delivery gate');
|
||||||
|
expect(byKey['lint']!.kindCaption, 'Check');
|
||||||
|
expect(byKey['review']!.kindCaption, isNull);
|
||||||
|
expect(byKey['#success']!.kindCaption, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a check definition lists its commands in place of a prompt', () {
|
||||||
|
final fields = stageDefinitionFields(_verify());
|
||||||
|
final byLabel = {for (final field in fields) field.label: field};
|
||||||
|
expect(byLabel['Type']!.value, 'check (delivery gate)');
|
||||||
|
final commands = byLabel['Commands']!;
|
||||||
|
expect(commands.value, 'go vet ./...\ngo test ./...');
|
||||||
|
expect(commands.monospace, isTrue);
|
||||||
|
expect(byLabel.containsKey('Prompt'), isFalse);
|
||||||
|
expect(byLabel['Command timeout']!.value, '15m');
|
||||||
|
expect(byLabel['Keep going']!.value, 'true');
|
||||||
|
expect(byLabel['Delivery gate']!.value, 'true');
|
||||||
|
expect(byLabel['Outcomes']!.value, contains('pass → review'));
|
||||||
|
expect(byLabel['Outcomes']!.value, contains('fail → implement'));
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
import 'package:pipelines_app/features/graph/domain/graph_definition.dart';
|
||||||
|
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
|
||||||
|
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
|
||||||
|
import 'package:pipelines_app/ui/text/monospace.dart';
|
||||||
|
|
||||||
|
Map<String, dynamic> _graph() => {
|
||||||
|
'stages': [
|
||||||
|
{
|
||||||
|
'key': 'verify',
|
||||||
|
'type': 'check',
|
||||||
|
'configs': {'delivery': 'true'},
|
||||||
|
'edges': {'pass': '#', 'fail': 'fix'},
|
||||||
|
'blocks': {'commands': 'go vet ./...\ngo test ./...'},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'key': 'fix',
|
||||||
|
'type': 'model',
|
||||||
|
'prompt': 'Fix it.',
|
||||||
|
'edges': {'success': 'verify'},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
Widget _host(Widget child) => MaterialApp(
|
||||||
|
home: Scaffold(body: Center(child: child)),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('a check node shows its kind under its name', (tester) async {
|
||||||
|
final nodes = {for (final node in graphNodes(_graph())) node.key: node};
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_host(
|
||||||
|
Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
GraphStageNode(node: nodes['verify']!, onSelected: (_) {}),
|
||||||
|
GraphStageNode(node: nodes['fix']!, onSelected: (_) {}),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(find.byKey(const ValueKey('graph-node-kind-verify')), findsOne);
|
||||||
|
expect(find.byKey(const ValueKey('graph-node-kind-fix')), findsNothing);
|
||||||
|
expect(find.text('Delivery gate'), findsOne);
|
||||||
|
expect(find.byIcon(Icons.verified_outlined), findsOne);
|
||||||
|
expect(find.bySemanticsLabel('verify\nDelivery gate'), findsOne);
|
||||||
|
expect(find.bySemanticsLabel('fix'), findsOne);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a check definition lists its commands in monospace', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: StageDefinitionView(
|
||||||
|
graph: _graph(),
|
||||||
|
stageKey: 'verify',
|
||||||
|
pipelineId: 1,
|
||||||
|
pipelineName: 'Demo',
|
||||||
|
version: 3,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final commands = tester.widget<SelectableText>(
|
||||||
|
find.descendant(
|
||||||
|
of: find.byKey(const ValueKey('stage-definition-Commands')),
|
||||||
|
matching: find.byType(SelectableText),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(commands.data, 'go vet ./...\ngo test ./...');
|
||||||
|
expect(commands.style?.fontFamily, appMonospaceFamily);
|
||||||
|
expect(find.text('check (delivery gate)'), findsOne);
|
||||||
|
expect(find.text('Prompt'), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
|
||||||
|
import 'package:pipelines_app/features/runs/domain/check_step_output.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('a check output reads each command result', () {
|
||||||
|
final output = checkStepOutput({
|
||||||
|
'markdown': '# outcome\n\nfail\n',
|
||||||
|
'summary': '1 of 2 checks failed: go test ./...',
|
||||||
|
'delivery': true,
|
||||||
|
'checks': [
|
||||||
|
{
|
||||||
|
'command': 'go vet ./...',
|
||||||
|
'status': 'passed',
|
||||||
|
'exit_code': 0,
|
||||||
|
'duration_ms': 2100,
|
||||||
|
'output': '',
|
||||||
|
'truncated': false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'command': 'go test ./...',
|
||||||
|
'status': 'failed',
|
||||||
|
'exit_code': 1,
|
||||||
|
'duration_ms': 51000,
|
||||||
|
'output': '--- FAIL',
|
||||||
|
'truncated': true,
|
||||||
|
},
|
||||||
|
{'command': 'make lint', 'status': 'not_run'},
|
||||||
|
'not a map',
|
||||||
|
],
|
||||||
|
})!;
|
||||||
|
expect(output.delivery, isTrue);
|
||||||
|
expect(output.summary, '1 of 2 checks failed: go test ./...');
|
||||||
|
expect(output.markdown, startsWith('# outcome'));
|
||||||
|
expect(output.checks, hasLength(3));
|
||||||
|
final [vet, test, lint] = output.checks;
|
||||||
|
expect(vet.status, CheckCommandStatus.passed);
|
||||||
|
expect(vet.meta, 'exit 0 · 2.1s');
|
||||||
|
expect(test.status, CheckCommandStatus.failed);
|
||||||
|
expect(test.meta, 'exit 1 · 51s');
|
||||||
|
expect(test.truncated, isTrue);
|
||||||
|
expect(lint.status, CheckCommandStatus.notRun);
|
||||||
|
expect(lint.meta, '');
|
||||||
|
expect(checkStatusLabel(lint), 'Not run');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('statuses this client does not know keep their own word', () {
|
||||||
|
final output = checkStepOutput({
|
||||||
|
'checks': [
|
||||||
|
{'command': 'x', 'status': 'skipped_by_policy'},
|
||||||
|
{'command': 'y'},
|
||||||
|
{'command': 'z', 'status': 'timed_out'},
|
||||||
|
],
|
||||||
|
})!;
|
||||||
|
expect(output.checks[0].status, CheckCommandStatus.unknown);
|
||||||
|
expect(checkStatusLabel(output.checks[0]), 'skipped_by_policy');
|
||||||
|
expect(checkStatusLabel(output.checks[1]), 'Unknown status');
|
||||||
|
expect(checkStatusLabel(output.checks[2]), 'Timed out');
|
||||||
|
expect(output.delivery, isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('outputs without a checks list are not check outputs', () {
|
||||||
|
expect(checkStepOutput(null), isNull);
|
||||||
|
expect(checkStepOutput('text'), isNull);
|
||||||
|
expect(checkStepOutput({'markdown': '# outcome'}), isNull);
|
||||||
|
expect(checkStepOutput({'checks': 'go test'}), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('durations read compactly', () {
|
||||||
|
expect(formatCheckDuration(850), '850ms');
|
||||||
|
expect(formatCheckDuration(2000), '2s');
|
||||||
|
expect(formatCheckDuration(2100), '2.1s');
|
||||||
|
expect(formatCheckDuration(51000), '51s');
|
||||||
|
expect(formatCheckDuration(185000), '3m 05s');
|
||||||
|
expect(formatCheckDuration(3720000), '1h 02m');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/run_check_output_view.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart';
|
||||||
|
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
|
||||||
|
import 'package:pipelines_app/ui/text/monospace.dart';
|
||||||
|
|
||||||
|
import 'run_detail_graph_support.dart';
|
||||||
|
import 'run_detail_visit_support.dart';
|
||||||
|
|
||||||
|
/// verify (a delivery check) -> review, with one failed check visit.
|
||||||
|
JsonMap _checkRun({int repairs = 0}) => <String, dynamic>{
|
||||||
|
'id': 78,
|
||||||
|
'title': 'Check run',
|
||||||
|
'name': 'release',
|
||||||
|
'pipeline_id': 7,
|
||||||
|
'version': 4,
|
||||||
|
'status': 'succeeded',
|
||||||
|
'graph': <String, dynamic>{
|
||||||
|
'stages': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'key': 'verify',
|
||||||
|
'type': 'check',
|
||||||
|
'configs': <String, dynamic>{'delivery': 'true'},
|
||||||
|
'edges': <String, String?>{'pass': '#', 'fail': 'verify'},
|
||||||
|
'blocks': <String, dynamic>{'commands': 'go vet ./...\ngo test ./...'},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
'steps': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'stage': 'verify',
|
||||||
|
'sequence': 1,
|
||||||
|
'status': 'completed',
|
||||||
|
'outcome': 'fail',
|
||||||
|
'target': 'verify',
|
||||||
|
'started_at': '2026-10-22T00:00:00Z',
|
||||||
|
'finished_at': '2026-10-22T00:01:00Z',
|
||||||
|
if (repairs > 0)
|
||||||
|
'control': <String, dynamic>{'visit': 1, 'outcome_repairs': repairs},
|
||||||
|
'output': <String, dynamic>{
|
||||||
|
'markdown': '# outcome\n\nfail\n\n# handoff\n\nFix the test.',
|
||||||
|
'summary': '1 of 2 checks failed: go test ./...',
|
||||||
|
'delivery': true,
|
||||||
|
'checks': <dynamic>[
|
||||||
|
<String, dynamic>{
|
||||||
|
'command': 'go vet ./...',
|
||||||
|
'status': 'passed',
|
||||||
|
'exit_code': 0,
|
||||||
|
'duration_ms': 2100,
|
||||||
|
'output': 'vet ok',
|
||||||
|
'truncated': false,
|
||||||
|
},
|
||||||
|
<String, dynamic>{
|
||||||
|
'command': 'go test ./...',
|
||||||
|
'status': 'failed',
|
||||||
|
'exit_code': 1,
|
||||||
|
'duration_ms': 51000,
|
||||||
|
'output': '--- FAIL: TestX',
|
||||||
|
'truncated': true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
const platform = RunDetailTestPlatform.material;
|
||||||
|
|
||||||
|
testWidgets('a check visit shows one row per command with its output', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await openVisit(tester, platform, run: _checkRun());
|
||||||
|
|
||||||
|
expect(find.byKey(const Key('run-check-output')), findsOneWidget);
|
||||||
|
expect(find.byKey(const Key('run-check-delivery')), findsOneWidget);
|
||||||
|
expect(find.text('1 of 2 checks failed: go test ./...'), findsOneWidget);
|
||||||
|
expect(find.text('go vet ./...'), findsOneWidget);
|
||||||
|
expect(find.text('Passed · exit 0 · 2.1s'), findsOneWidget);
|
||||||
|
expect(find.text('Failed · exit 1 · 51s'), findsOneWidget);
|
||||||
|
// The raw checks list is never shown as a `key=value` field dump.
|
||||||
|
expect(find.text('checks'), findsNothing);
|
||||||
|
|
||||||
|
// Output is collapsed until the row is expanded; then it is selectable
|
||||||
|
// monospace with the truncation note.
|
||||||
|
expect(find.text('--- FAIL: TestX'), findsNothing);
|
||||||
|
final row = find.byKey(const ValueKey('run-check-command-1'));
|
||||||
|
await tester.ensureVisible(row);
|
||||||
|
await tester.tap(find.text('go test ./...'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
final output = tester.widget<SelectableText>(
|
||||||
|
find.widgetWithText(SelectableText, '--- FAIL: TestX'),
|
||||||
|
);
|
||||||
|
expect(output.style?.fontFamily, appMonospaceFamily);
|
||||||
|
expect(find.text(checkOutputTruncated), findsOneWidget);
|
||||||
|
expect(tester.takeException(), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a check visit has no model row and an honest session note', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await openVisit(tester, platform, run: _checkRun());
|
||||||
|
expect(find.text('Provider/model'), findsNothing);
|
||||||
|
expect(find.text('fail'), findsWidgets);
|
||||||
|
await openVisitTab(tester, RunVisitSection.session);
|
||||||
|
expect(find.text(visitSessionCheck), findsOneWidget);
|
||||||
|
expect(find.text(visitSessionNoIdentity), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a repaired outcome is noted on the visit', (tester) async {
|
||||||
|
await openVisit(tester, platform, run: _checkRun(repairs: 1));
|
||||||
|
expect(find.byKey(const Key('run-visit-outcome-repaired')), findsOne);
|
||||||
|
expect(find.text('Outcome repaired by follow-up'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('an unrepaired visit shows no repair note', (tester) async {
|
||||||
|
await openVisit(tester, platform, run: _checkRun());
|
||||||
|
expect(find.byKey(const Key('run-visit-outcome-repaired')), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('outcome repairs read from control, absent meaning none', () {
|
||||||
|
expect(detailVisitOutcomeRepairs({}), 0);
|
||||||
|
expect(detailVisitOutcomeRepairs({'control': 'x'}), 0);
|
||||||
|
expect(
|
||||||
|
detailVisitOutcomeRepairs({
|
||||||
|
'control': {'visit': 2},
|
||||||
|
}),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
detailVisitOutcomeRepairs({
|
||||||
|
'control': {'outcome_repairs': 2},
|
||||||
|
}),
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
expect(outcomeRepairNote(2), 'Outcome repaired by follow-up (2 times)');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/application/app_terminals.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_terminal.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_window_body.dart';
|
||||||
|
import 'package:pipelines_app/features/terminal/terminal_hub.dart';
|
||||||
|
import 'package:pipelines_app/features/terminal/terminal_layout.dart';
|
||||||
|
import 'package:pipelines_app/features/terminal/terminal_tab_strip.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
|
||||||
|
import '../../application/detached/detached_fixtures.dart';
|
||||||
|
import 'terminal_fixtures.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('the options menu sends the terminal to a new window', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final mac = TerminalGateway()..add('t1', text: 'hello\r\n');
|
||||||
|
addTearDown(mac.close);
|
||||||
|
final hub = TerminalHub(TestMachines([machine('mac', mac)]))..activate();
|
||||||
|
addTearDown(hub.dispose);
|
||||||
|
await tester.runAsync(hub.listed);
|
||||||
|
final layout = TerminalLayout(store: MemoryLayoutStore())..show();
|
||||||
|
final opener = FakeOpener();
|
||||||
|
await tester.pumpWidget(
|
||||||
|
DetachedWindowScope(
|
||||||
|
opener: opener,
|
||||||
|
child: MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: TerminalTabStrip(hub: hub, layout: layout),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.tap(find.byTooltip('Terminal options'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
await tester.tap(find.byKey(const ValueKey('terminal-new-window')));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(opener.terminals, ['mac/t1']);
|
||||||
|
expect(layout.visible, isFalse, reason: 'it leaves the main window');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('without platform windows the menu has no such choice', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final hub = TerminalHub(TestMachines([]));
|
||||||
|
addTearDown(hub.dispose);
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: TerminalTabStrip(
|
||||||
|
hub: hub,
|
||||||
|
layout: TerminalLayout(store: MemoryLayoutStore()),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.tap(find.byTooltip('Terminal options'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byKey(const ValueKey('terminal-new-window')), findsNothing);
|
||||||
|
expect(find.text('Floating window'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a layout that does not persist never saves', () async {
|
||||||
|
final store = MemoryLayoutStore();
|
||||||
|
final layout = TerminalLayout(store: store)..persist = false;
|
||||||
|
layout
|
||||||
|
..setFontSize(18)
|
||||||
|
..show();
|
||||||
|
await layout.save();
|
||||||
|
expect(store.saves, 0);
|
||||||
|
expect(layout.fontSize, 18, reason: 'the window still follows it');
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('a detached terminal opens on its tab, without modes, and '
|
||||||
|
'gives it back', (tester) async {
|
||||||
|
final mac = TerminalGateway()
|
||||||
|
..add('t1', text: 'one\r\n')
|
||||||
|
..add('t2', text: 'two\r\n');
|
||||||
|
addTearDown(mac.close);
|
||||||
|
final connection = ValueNotifier(0);
|
||||||
|
final terminals = AppTerminals(
|
||||||
|
pool: null,
|
||||||
|
connection: connection,
|
||||||
|
connected: () => true,
|
||||||
|
gateway: mac,
|
||||||
|
machineId: 'mac',
|
||||||
|
machineName: () => 'Mac',
|
||||||
|
layout: TerminalLayout(store: MemoryLayoutStore()),
|
||||||
|
);
|
||||||
|
addTearDown(terminals.dispose);
|
||||||
|
final back = <(DetachedKind, String)>[];
|
||||||
|
final titles = <String>[];
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
home: DetachedTerminal(
|
||||||
|
terminals: terminals,
|
||||||
|
tabKey: 'mac/t2',
|
||||||
|
window: DetachedWindowControls(
|
||||||
|
ready: ValueNotifier(true),
|
||||||
|
sync: ValueNotifier(0),
|
||||||
|
setTitle: titles.add,
|
||||||
|
close: () {},
|
||||||
|
bringBackItem: (kind, id, _, _) => back.add((kind, id)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.runAsync(terminals.hub.listed);
|
||||||
|
await tester.pump();
|
||||||
|
expect(terminals.hub.selected?.key, 'mac/t2');
|
||||||
|
expect(titles.last, startsWith('Terminal'));
|
||||||
|
// There is no panel or floating mode to choose in a window of its own.
|
||||||
|
expect(find.byTooltip('Terminal options'), findsNothing);
|
||||||
|
await tester.tap(find.byTooltip('Bring back to main window'));
|
||||||
|
expect(back, [(DetachedKind.terminal, 'mac/t2')]);
|
||||||
|
await tester.pumpWidget(const SizedBox());
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:pipelines_app/features/chat/workspace/chat_float_shortcut.dart';
|
||||||
|
import 'package:pipelines_app/features/settings/keyboard_shortcuts_registry.dart';
|
||||||
|
import 'package:pipelines_app/shell/detached/detached_window_scope.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
testWidgets('Alt+Shift+Y is the new-window chord, never Float', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final seen = <(bool detach, bool float)>[];
|
||||||
|
bool handler(KeyEvent event) {
|
||||||
|
if (event is KeyDownEvent &&
|
||||||
|
event.logicalKey == LogicalKeyboardKey.keyY) {
|
||||||
|
final keyboard = HardwareKeyboard.instance;
|
||||||
|
seen.add((
|
||||||
|
detachedWindowShortcut(event, keyboard),
|
||||||
|
chatFloatShortcut(event, keyboard),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
HardwareKeyboard.instance.addHandler(handler);
|
||||||
|
addTearDown(() => HardwareKeyboard.instance.removeHandler(handler));
|
||||||
|
|
||||||
|
Future<void> chord(List<LogicalKeyboardKey> modifiers) async {
|
||||||
|
for (final key in modifiers) {
|
||||||
|
await tester.sendKeyDownEvent(key);
|
||||||
|
}
|
||||||
|
await tester.sendKeyEvent(LogicalKeyboardKey.keyY);
|
||||||
|
for (final key in modifiers.reversed) {
|
||||||
|
await tester.sendKeyUpEvent(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await chord([LogicalKeyboardKey.altLeft, LogicalKeyboardKey.shiftLeft]);
|
||||||
|
await chord([LogicalKeyboardKey.altLeft]);
|
||||||
|
await chord([LogicalKeyboardKey.shiftLeft]);
|
||||||
|
await chord([
|
||||||
|
LogicalKeyboardKey.controlLeft,
|
||||||
|
LogicalKeyboardKey.altLeft,
|
||||||
|
LogicalKeyboardKey.shiftLeft,
|
||||||
|
]);
|
||||||
|
expect(seen, [
|
||||||
|
(true, false),
|
||||||
|
(false, true),
|
||||||
|
(false, false),
|
||||||
|
(false, false),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the shortcut help lists it where windows exist', () {
|
||||||
|
String? keysOn(TargetPlatform platform, {bool web = false}) =>
|
||||||
|
KeyboardShortcutRegistry(platform: platform, web: web).entries
|
||||||
|
.where((e) => e.action == 'Open the chat in a new window')
|
||||||
|
.map((e) => e.keys)
|
||||||
|
.firstOrNull;
|
||||||
|
expect(keysOn(TargetPlatform.linux), 'Alt+Shift+Y');
|
||||||
|
expect(keysOn(TargetPlatform.macOS), 'Option+Shift+Y');
|
||||||
|
expect(keysOn(TargetPlatform.windows, web: true), 'Alt+Shift+Y');
|
||||||
|
expect(keysOn(TargetPlatform.android), isNull);
|
||||||
|
expect(keysOn(TargetPlatform.iOS), isNull);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -88,6 +88,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`.
|
|||||||
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) |
|
| `swipe=<target>>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) |
|
||||||
| `pinch=<target>>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) |
|
| `pinch=<target>>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) |
|
||||||
| `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab |
|
| `tabs=name` | write the open tabs (`{url, type}`) to JSON, e.g. to see a link open a new tab |
|
||||||
|
| `follow=/window/chat/` | move the following steps to the page whose URL contains the text (a window the app opened with `window.open`, at its own size, semantics on); `follow=main` returns to the page the kit opened (`examples/detached-chat-window.json`) |
|
||||||
| `eval=<js>` | evaluate an expression in the page and log/record its value |
|
| `eval=<js>` | evaluate an expression in the page and log/record its value |
|
||||||
| `expect=<js>` | fail the run (status 1) unless the expression is truthy; JSON `name` labels the check |
|
| `expect=<js>` | fail the run (status 1) unless the expression is truthy; JSON `name` labels the check |
|
||||||
|
|
||||||
|
|||||||
@@ -88,6 +88,7 @@ export async function openBrowser({ cdp, gpu = false, args = [], chromePath = pr
|
|||||||
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
|
ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }));
|
||||||
});
|
});
|
||||||
let targetId;
|
let targetId;
|
||||||
|
let main;
|
||||||
try {
|
try {
|
||||||
({ targetId } = await raw('Target.createTarget', { url: 'about:blank' }));
|
({ targetId } = await raw('Target.createTarget', { url: 'about:blank' }));
|
||||||
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
||||||
@@ -114,6 +115,33 @@ export async function openBrowser({ cdp, gpu = false, args = [], chromePath = pr
|
|||||||
},
|
},
|
||||||
/** Brings the kit's own page to the front again (after a scratch page). */
|
/** Brings the kit's own page to the front again (after a scratch page). */
|
||||||
front: () => raw('Target.activateTarget', { targetId }),
|
front: () => raw('Target.activateTarget', { targetId }),
|
||||||
|
/**
|
||||||
|
* Moves the kit's page session to another page target: the first one
|
||||||
|
* whose URL contains [match] (a window the page opened with
|
||||||
|
* `window.open`), waited for up to [timeout] ms; `main` returns to the
|
||||||
|
* page the kit opened. Resolves to the target's URL.
|
||||||
|
*/
|
||||||
|
follow: async (match, timeout = 10000) => {
|
||||||
|
main ??= { targetId, sessionId };
|
||||||
|
if (match === 'main') {
|
||||||
|
({ targetId, sessionId } = main);
|
||||||
|
await raw('Target.activateTarget', { targetId });
|
||||||
|
return (await raw('Target.getTargets')).targetInfos.find((t) => t.targetId === targetId)?.url;
|
||||||
|
}
|
||||||
|
const end = Date.now() + timeout;
|
||||||
|
for (;;) {
|
||||||
|
const hit = (await raw('Target.getTargets')).targetInfos
|
||||||
|
.find((t) => t.type === 'page' && t.targetId !== main.targetId && t.url.includes(match));
|
||||||
|
if (hit) {
|
||||||
|
targetId = hit.targetId;
|
||||||
|
({ sessionId } = await raw('Target.attachToTarget', { targetId, flatten: true }));
|
||||||
|
await raw('Target.activateTarget', { targetId });
|
||||||
|
return hit.url;
|
||||||
|
}
|
||||||
|
if (Date.now() > end) throw new Error(`no page whose URL contains ${JSON.stringify(match)} within ${timeout} ms`);
|
||||||
|
await new Promise((ok) => setTimeout(ok, 100));
|
||||||
|
}
|
||||||
|
},
|
||||||
close: async () => {
|
close: async () => {
|
||||||
await raw('Target.closeTarget', { targetId }).catch(() => {});
|
await raw('Target.closeTarget', { targetId }).catch(() => {});
|
||||||
ws.close();
|
ws.close();
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ options: --script <steps.json> --size WxH (880x1000)
|
|||||||
steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target>
|
steps: open=<route>[@WxH] wait=<ms> shot=<name> click=<target> waitfor=<target>
|
||||||
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
|
type=<text> press=<Enter|Escape|Tab|...> scroll=<dy> size=WxH
|
||||||
files=<path>[,<path>] (answers the next file chooser)
|
files=<path>[,<path>] (answers the next file chooser)
|
||||||
film=<target> labels=<name> tabs=<name> eval=<js> expect=<js> hover=<target>
|
film=<target> labels=<name> tabs=<name> follow=<url part|main> eval=<js> expect=<js> hover=<target>
|
||||||
keys=<json events> grant=clipboard
|
keys=<json events> grant=clipboard
|
||||||
clipboard=read|write:<text> (the browser's clipboard, from a scratch
|
clipboard=read|write:<text> (the browser's clipboard, from a scratch
|
||||||
page on the loopback origin, so it works for an --insecure page)
|
page on the loopback origin, so it works for an --insecure page)
|
||||||
@@ -246,6 +246,15 @@ try {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break;
|
case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break;
|
||||||
|
case 'follow': {
|
||||||
|
// follow=<url part>: the steps after it act on that window (one the
|
||||||
|
// page opened); follow=main returns to the page the kit opened.
|
||||||
|
const url = await browser.follow(String(value), step.timeout);
|
||||||
|
log(` now on ${url}`);
|
||||||
|
if (value !== 'main') await page.adopt();
|
||||||
|
await delay(step.wait ?? settle);
|
||||||
|
break;
|
||||||
|
}
|
||||||
case 'labels': await save(file(value || 'labels', 'json'), JSON.stringify(await page.labels(), null, 2)); break;
|
case 'labels': await save(file(value || 'labels', 'json'), JSON.stringify(await page.labels(), null, 2)); break;
|
||||||
case 'film': {
|
case 'film': {
|
||||||
const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value));
|
const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value));
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{ "size": "1400x900", "params": "chats=2",
|
||||||
|
"steps": [
|
||||||
|
{ "open": "/chat/perf-chat-0" },
|
||||||
|
{ "wait": 1500 },
|
||||||
|
{ "shot": "main-before" },
|
||||||
|
{ "click": "More actions" },
|
||||||
|
{ "shot": "pane-menu" },
|
||||||
|
{ "click": "Open in new window (Alt+Shift+Y)", "wait": 1500 },
|
||||||
|
{ "tabs": "tabs" },
|
||||||
|
{ "follow": "/window/chat/", "wait": 2500 },
|
||||||
|
{ "shot": "detached-chat" },
|
||||||
|
{ "eval": "document.title" },
|
||||||
|
{ "expect": "document.title === 'Fixture chat 1 · Pipelines'", "name": "the window is named after its chat" },
|
||||||
|
{ "expect": "location.pathname === '/window/chat/perf-chat-0'", "name": "the window keeps its location" },
|
||||||
|
{ "follow": "main", "wait": 800 },
|
||||||
|
{ "shot": "main-after" },
|
||||||
|
{ "follow": "/window/chat/", "wait": 500 },
|
||||||
|
{ "click": "More actions" },
|
||||||
|
{ "shot": "detached-menu" },
|
||||||
|
{ "click": "Bring back to main window", "wait": 1500 },
|
||||||
|
{ "follow": "main", "wait": 1200 },
|
||||||
|
{ "tabs": "tabs-after-return" },
|
||||||
|
{ "shot": "main-returned" }
|
||||||
|
] }
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{ "size": "1400x900", "params": "chats=2&terminals=1&terminal=panel",
|
||||||
|
"steps": [
|
||||||
|
{ "open": "/chat/perf-chat-0" },
|
||||||
|
{ "wait": 2000 },
|
||||||
|
{ "click": "Terminal options" },
|
||||||
|
{ "shot": "terminal-menu" },
|
||||||
|
{ "click": "Open in new window", "wait": 1500 },
|
||||||
|
{ "shot": "main-after" },
|
||||||
|
{ "follow": "/window/terminal", "wait": 3000 },
|
||||||
|
{ "shot": "detached-terminal" },
|
||||||
|
{ "eval": "document.title" },
|
||||||
|
{ "expect": "document.title.startsWith('Terminal')", "name": "the window is named after its terminal" }
|
||||||
|
] }
|
||||||
@@ -125,6 +125,21 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use
|
|||||||
if (touch) await enableTouch(send, viewport);
|
if (touch) await enableTouch(send, viewport);
|
||||||
await delay(800);
|
await delay(800);
|
||||||
},
|
},
|
||||||
|
/**
|
||||||
|
* Takes over a page that is already loading (a window the app opened)
|
||||||
|
* at its own size: waits for Flutter and turns semantics on.
|
||||||
|
*/
|
||||||
|
async adopt() {
|
||||||
|
await send('Page.enable');
|
||||||
|
await send('Runtime.enable');
|
||||||
|
// A window followed before already has its semantics tree.
|
||||||
|
const started = "Boolean(document.querySelector('flt-semantics-placeholder, flt-semantics'))";
|
||||||
|
await until(() => evaluate(started), 'Flutter to start', 30000);
|
||||||
|
if (!semantics) return;
|
||||||
|
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||||
|
await until(() => evaluate("document.querySelectorAll('flt-semantics').length > 0"), 'the semantics tree', 15000);
|
||||||
|
await delay(800);
|
||||||
|
},
|
||||||
async click(target, timeout) {
|
async click(target, timeout) {
|
||||||
const point = await locate(target, timeout);
|
const point = await locate(target, timeout);
|
||||||
await tap(point);
|
await tap(point);
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'package:flutter/services.dart';
|
|||||||
import 'package:flutter/widgets.dart';
|
import 'package:flutter/widgets.dart';
|
||||||
import 'package:pipelines_app/application/server_endpoint.dart';
|
import 'package:pipelines_app/application/server_endpoint.dart';
|
||||||
|
|
||||||
|
import '../perf/frame_log_native.dart';
|
||||||
import 'fixture_steps.dart';
|
import 'fixture_steps.dart';
|
||||||
import 'narrow_view.dart';
|
import 'narrow_view.dart';
|
||||||
|
|
||||||
@@ -31,8 +32,10 @@ Map<String, String> fixtureParams() {
|
|||||||
return raw.isEmpty ? const {} : Uri.splitQueryString(raw);
|
return raw.isEmpty ? const {} : Uri.splitQueryString(raw);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The DevTools probes are browser-only.
|
/// The DevTools probes are browser-only; `perf=1` prints frame timings to
|
||||||
void installHostProbes(Map<String, String> params) {}
|
/// stdout (tool/perf/frame_log_native.dart).
|
||||||
|
void installHostProbes(Map<String, String> params) =>
|
||||||
|
installNativeFrameLog(params);
|
||||||
|
|
||||||
/// The route goes through [fixtureRouteProvider] instead.
|
/// The route goes through [fixtureRouteProvider] instead.
|
||||||
void openFixtureRoute(String route) {}
|
void openFixtureRoute(String route) {}
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ import 'package:flutter/services.dart';
|
|||||||
/// [script] is `;`-separated steps run after the first frame, 700 ms apart:
|
/// [script] is `;`-separated steps run after the first frame, 700 ms apart:
|
||||||
/// `wait:<ms>`, `tap:<label>` (a Text, Tooltip, Semantics label or field
|
/// `wait:<ms>`, `tap:<label>` (a Text, Tooltip, Semantics label or field
|
||||||
/// hint; `tap:<label>#<n>` picks the n-th match), `tapxy:<x>,<y>`,
|
/// hint; `tap:<label>#<n>` picks the n-th match), `tapxy:<x>,<y>`,
|
||||||
/// `drag:<x>,<y>,<dx>,<dy>`, `type:<text>` (into the focused field; `\n`
|
/// `drag:<x>,<y>,<dx>,<dy>`, `wheel:<x>,<y>,<dy>,<count>` (mouse-wheel
|
||||||
|
/// notches 16 ms apart, as the web interaction bench sends), `mark:<name>`
|
||||||
|
/// (prints `FIXTURE_MARK <name>`, so a bench can tell its phases apart),
|
||||||
|
/// `type:<text>` (into the focused field; `\n`
|
||||||
/// is a newline), `orient:landscape|portrait` and `labels` (prints the
|
/// is a newline), `orient:landscape|portrait` and `labels` (prints the
|
||||||
/// visible labels with their centres to the device log).
|
/// visible labels with their centres to the device log).
|
||||||
void runFixtureSteps(String script) {
|
void runFixtureSteps(String script) {
|
||||||
@@ -54,6 +57,12 @@ Future<void> _run(String verb, String value) async {
|
|||||||
case 'drag':
|
case 'drag':
|
||||||
final p = value.split(',').map(double.parse).toList();
|
final p = value.split(',').map(double.parse).toList();
|
||||||
await _drag(Offset(p[0], p[1]), Offset(p[2], p[3]));
|
await _drag(Offset(p[0], p[1]), Offset(p[2], p[3]));
|
||||||
|
case 'mark':
|
||||||
|
// ignore: avoid_print
|
||||||
|
print('FIXTURE_MARK $value');
|
||||||
|
case 'wheel':
|
||||||
|
final p = value.split(',').map(double.parse).toList();
|
||||||
|
await _wheel(Offset(p[0], p[1]), p[2], p[3].toInt());
|
||||||
case 'type':
|
case 'type':
|
||||||
_type(value.replaceAll(r'\n', '\n'));
|
_type(value.replaceAll(r'\n', '\n'));
|
||||||
case 'orient':
|
case 'orient':
|
||||||
@@ -141,6 +150,20 @@ Future<void> _drag(Offset from, Offset by) async {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _wheel(Offset at, double dy, int count) async {
|
||||||
|
final binding = GestureBinding.instance;
|
||||||
|
for (var i = 0; i < count; i++) {
|
||||||
|
binding.handlePointerEvent(
|
||||||
|
PointerScrollEvent(
|
||||||
|
kind: PointerDeviceKind.mouse,
|
||||||
|
position: at,
|
||||||
|
scrollDelta: Offset(0, dy),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 16));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void _type(String text) {
|
void _type(String text) {
|
||||||
EditableTextState? focused;
|
EditableTextState? focused;
|
||||||
void visit(Element element) {
|
void visit(Element element) {
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
// Frame report for native fixture builds (the Linux desktop bench,
|
||||||
|
// tool/perf/linux_desktop_bench.py), the native twin of frame_log.dart.
|
||||||
|
//
|
||||||
|
// With `perf=1` in FIXTURE_QUERY it prints every frame's Flutter timings as
|
||||||
|
// `PERF_FRAME <build us> <raster us> <total us>`, and the first rasterised
|
||||||
|
// frame as `PERF_FIRST_FRAME_EPOCH <ms since the Unix epoch>`, which the
|
||||||
|
// bench subtracts from its own launch time. Without the flag nothing is
|
||||||
|
// installed.
|
||||||
|
import 'package:flutter/widgets.dart';
|
||||||
|
|
||||||
|
void installNativeFrameLog(Map<String, String> params) {
|
||||||
|
if (params['perf'] != '1') return;
|
||||||
|
final binding = WidgetsFlutterBinding.ensureInitialized();
|
||||||
|
binding.addTimingsCallback((timings) {
|
||||||
|
for (final timing in timings) {
|
||||||
|
// ignore: avoid_print
|
||||||
|
print(
|
||||||
|
'PERF_FRAME ${timing.buildDuration.inMicroseconds} '
|
||||||
|
'${timing.rasterDuration.inMicroseconds} '
|
||||||
|
'${timing.totalSpan.inMicroseconds}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
binding.waitUntilFirstFrameRasterized.then((_) {
|
||||||
|
// ignore: avoid_print
|
||||||
|
print('PERF_FIRST_FRAME_EPOCH ${DateTime.now().millisecondsSinceEpoch}');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Startup and chat-scroll bench for the Linux desktop build of the full-app
|
||||||
|
fixture, the native counterpart of interaction_bench.mjs's `startup` and
|
||||||
|
`desktop: scroll a rich chat` scenarios.
|
||||||
|
|
||||||
|
Build the fixture as a Linux bundle (release, or profile for engine switches):
|
||||||
|
|
||||||
|
docker run ... pipelines-app-build linux --target tool/search_selection_probe_entry.dart
|
||||||
|
|
||||||
|
then:
|
||||||
|
|
||||||
|
python3 tool/perf/linux_desktop_bench.py --bundle <bundle dir> [--repeat 5]
|
||||||
|
[--switch enable-impeller=true] # profile builds only
|
||||||
|
|
||||||
|
Each run starts the bundle on a private Xvfb display (never the desktop
|
||||||
|
session) with an isolated HOME and its own D-Bus session, with FIXTURE_QUERY
|
||||||
|
`perf=1` (tool/perf/frame_log_native.dart). Startup is launch to the first
|
||||||
|
rasterised frame; the scroll is 30 mouse-wheel notches of -240 px over the
|
||||||
|
open rich chat. Xvfb has no GPU: Mesa's llvmpipe rasterises on the CPU, as
|
||||||
|
headless Chrome without --gpu does, so compare builds and engines with each
|
||||||
|
other rather than predicting a desktop with a GPU.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import statistics
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
QUERY = ("route=/chat/perf-chat-0&chats=2&header=1&rich=1&perf=1"
|
||||||
|
"&do=wait:500;tap:Later;wait:800;mark:scroll;wheel:860,400,-240,30;wait:1500;mark:end")
|
||||||
|
|
||||||
|
|
||||||
|
def run_once(bundle, display, switches, timeout, extra_env=()):
|
||||||
|
root = Path(tempfile.mkdtemp(prefix="linux-bench-"))
|
||||||
|
runtime = root / "run"
|
||||||
|
runtime.mkdir(mode=0o700)
|
||||||
|
env = {"HOME": str(root / "home"), "XDG_RUNTIME_DIR": str(runtime), "DISPLAY": f":{display}",
|
||||||
|
"GDK_BACKEND": "x11", "PATH": "/usr/bin:/bin", "FIXTURE_QUERY": QUERY,
|
||||||
|
**dict(e.split("=", 1) for e in extra_env)}
|
||||||
|
if switches:
|
||||||
|
env["FLUTTER_ENGINE_SWITCHES"] = str(len(switches))
|
||||||
|
for index, switch in enumerate(switches, 1):
|
||||||
|
env[f"FLUTTER_ENGINE_SWITCH_{index}"] = switch
|
||||||
|
xvfb = subprocess.Popen(["Xvfb", f":{display}", "-screen", "0", "1280x800x24", "-nolisten", "tcp"],
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
lines = []
|
||||||
|
try:
|
||||||
|
time.sleep(1)
|
||||||
|
launched = time.time() * 1000
|
||||||
|
app = subprocess.Popen(["dbus-run-session", "--", str(Path(bundle) / "pipelines-app")], env=env,
|
||||||
|
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||||
|
start_new_session=True)
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
try:
|
||||||
|
for line in app.stdout:
|
||||||
|
lines.append(line.strip())
|
||||||
|
if line.startswith("FIXTURE_MARK end") or time.time() > deadline:
|
||||||
|
break
|
||||||
|
finally:
|
||||||
|
os.killpg(app.pid, 15)
|
||||||
|
app.wait(timeout=10)
|
||||||
|
finally:
|
||||||
|
xvfb.terminate()
|
||||||
|
xvfb.wait(timeout=10)
|
||||||
|
shutil.rmtree(root, ignore_errors=True)
|
||||||
|
first = next((int(l.split()[1]) for l in lines if l.startswith("PERF_FIRST_FRAME_EPOCH ")), None)
|
||||||
|
phase, scroll = None, []
|
||||||
|
for line in lines:
|
||||||
|
if line.startswith("FIXTURE_MARK "):
|
||||||
|
phase = line.split()[1]
|
||||||
|
elif line.startswith("PERF_FRAME ") and phase == "scroll":
|
||||||
|
build, raster, total = (int(v) for v in line.split()[1:4])
|
||||||
|
scroll.append((build, raster, total))
|
||||||
|
if first is None or not scroll:
|
||||||
|
raise RuntimeError("the run reported no first frame or no scroll frames:\n" + "\n".join(lines[-20:]))
|
||||||
|
return {"startupMs": first - launched, "frames": len(scroll),
|
||||||
|
"buildSumMs": sum(f[0] for f in scroll) / 1000, "buildMaxMs": max(f[0] for f in scroll) / 1000,
|
||||||
|
"rasterSumMs": sum(f[1] for f in scroll) / 1000, "rasterMaxMs": max(f[1] for f in scroll) / 1000,
|
||||||
|
"rasterMedianMs": statistics.median(f[1] for f in scroll) / 1000,
|
||||||
|
"worstFrameMs": max(f[2] for f in scroll) / 1000}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||||
|
parser.add_argument("--bundle", required=True)
|
||||||
|
parser.add_argument("--repeat", type=int, default=5)
|
||||||
|
parser.add_argument("--display", type=int, default=97)
|
||||||
|
parser.add_argument("--switch", action="append", default=[], help="engine switch (profile builds)")
|
||||||
|
parser.add_argument("--timeout", type=float, default=60)
|
||||||
|
parser.add_argument("--env", action="append", default=[], help="extra VAR=value for the app")
|
||||||
|
args = parser.parse_args()
|
||||||
|
runs = [run_once(args.bundle, args.display, args.switch, args.timeout, args.env) for _ in range(args.repeat)]
|
||||||
|
median = {key: round(statistics.median(r[key] for r in runs), 1) for key in runs[0]}
|
||||||
|
print(json.dumps({"bundle": args.bundle, "switches": args.switch, "runs": len(runs), "median": median}, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -28,6 +28,9 @@ import 'dart:convert';
|
|||||||
|
|
||||||
import 'package:pipelines_app/application/app_url_strategy.dart';
|
import 'package:pipelines_app/application/app_url_strategy.dart';
|
||||||
import 'package:pipelines_app/application/pipelines_app.dart';
|
import 'package:pipelines_app/application/pipelines_app.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_app.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_platform.dart';
|
||||||
|
import 'package:pipelines_app/application/detached/detached_route.dart';
|
||||||
import 'package:pipelines_app/application/bootstrap.dart';
|
import 'package:pipelines_app/application/bootstrap.dart';
|
||||||
import 'package:pipelines_app/core/api_gateway.dart';
|
import 'package:pipelines_app/core/api_gateway.dart';
|
||||||
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||||
@@ -1080,25 +1083,43 @@ Future<void> main() async {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
final app = PipelinesApp(
|
// A detached window (`/window/chat/<id>`, opened by Open in new window)
|
||||||
serverId: machines?.catalog.active?.id,
|
// runs on the same fixture: its URL carries this page's parameters.
|
||||||
servers: machines,
|
DetachedPlatform.extraQuery = () => {
|
||||||
chatPool: pool,
|
for (final entry in params.entries)
|
||||||
server: fixtureServer(params),
|
if (entry.key != 'route' && entry.key != 'q') entry.key: entry.value,
|
||||||
webPlatform: params['nativeUpdate'] == null ? kIsWeb : false,
|
};
|
||||||
androidSupported: params['nativeUpdate'] == null ? null : true,
|
final detached = kIsWeb ? DetachedRoute.parse(Uri.base.toString()) : null;
|
||||||
installedVersionReader: () async => 1,
|
final app = detached != null
|
||||||
androidFeedReader: (base) async => AppUpdate(
|
? DetachedWindowApp(
|
||||||
versionCode: 2,
|
route: detached,
|
||||||
versionName: '0.1.2',
|
server: fixtureServer(params),
|
||||||
apk: base.resolve('Pipelines.zip'),
|
serverId: machines?.catalog.active?.id,
|
||||||
platform: params['nativeUpdate'] ?? 'android',
|
servers: machines,
|
||||||
sourceName: 'Home Linux',
|
chatPool: pool,
|
||||||
),
|
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
|
||||||
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
|
)
|
||||||
routeInformationProvider: fixtureRouteProvider(opensRoute ? route : null),
|
: PipelinesApp(
|
||||||
windows: probeWindows(params),
|
serverId: machines?.catalog.active?.id,
|
||||||
);
|
servers: machines,
|
||||||
|
chatPool: pool,
|
||||||
|
server: fixtureServer(params),
|
||||||
|
webPlatform: params['nativeUpdate'] == null ? kIsWeb : false,
|
||||||
|
androidSupported: params['nativeUpdate'] == null ? null : true,
|
||||||
|
installedVersionReader: () async => 1,
|
||||||
|
androidFeedReader: (base) async => AppUpdate(
|
||||||
|
versionCode: 2,
|
||||||
|
versionName: '0.1.2',
|
||||||
|
apk: base.resolve('Pipelines.zip'),
|
||||||
|
platform: params['nativeUpdate'] ?? 'android',
|
||||||
|
sourceName: 'Home Linux',
|
||||||
|
),
|
||||||
|
client: PipelinesClient(channelFactory: (_) => _FixtureChannel()),
|
||||||
|
routeInformationProvider: fixtureRouteProvider(
|
||||||
|
opensRoute ? route : null,
|
||||||
|
),
|
||||||
|
windows: probeWindows(params),
|
||||||
|
);
|
||||||
final brightness = switch (params['theme']) {
|
final brightness = switch (params['theme']) {
|
||||||
'dark' => Brightness.dark,
|
'dark' => Brightness.dark,
|
||||||
'light' => Brightness.light,
|
'light' => Brightness.light,
|
||||||
|
|||||||
+5
-2
@@ -194,8 +194,11 @@ Every submission, including agent-issued `submit`/`rpc`, still uses server valid
|
|||||||
## Drafts in the TUI
|
## Drafts in the TUI
|
||||||
|
|
||||||
The server runs one active run per resolved workspace, including overlapping
|
The server runs one active run per resolved workspace, including overlapping
|
||||||
parent/descendant directories (and symlink aliases). Separate sibling worktrees
|
parent/descendant directories of one repository (and symlink aliases). Separate
|
||||||
remain independent. A new request key in a
|
sibling worktrees, and separate repositories nested in one another, remain
|
||||||
|
independent. Two folders outside any repository overlap only when they are the
|
||||||
|
same folder or one lies within the other run's declared write paths. A new
|
||||||
|
request key in a
|
||||||
different workspace is admitted immediately and executes concurrently; a second
|
different workspace is admitted immediately and executes concurrently; a second
|
||||||
run in a workspace an active run is already changing is refused, naming the
|
run in a workspace an active run is already changing is refused, naming the
|
||||||
conflicting run and advising you to wait or use a different workspace (for
|
conflicting run and advising you to wait or use a different workspace (for
|
||||||
|
|||||||
+7
-2
@@ -309,8 +309,13 @@ directory that chooses its own account keeps it).
|
|||||||
- **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit
|
- **Failures.** Diagnostics are fixed text. A billing, quota or rate-limit
|
||||||
refusal stops the run without retries; a missing sign-in says so. The CLI's
|
refusal stops the run without retries; a missing sign-in says so. The CLI's
|
||||||
redacted stream is kept as the session export and evidence.
|
redacted stream is kept as the session export and evidence.
|
||||||
- **Recovery.** A server restart during a Claude Code stage stops that process
|
- **Recovery.** The CLI runs in its own session, writing its stream-json to a
|
||||||
and fails the visit; it is not reattached.
|
file in the stage's evidence directory, so a restart of the installed server
|
||||||
|
does not stop it. The next server re-adopts the visit: it keeps reading the
|
||||||
|
CLI's output, waits for it to finish and continues the run. A CLI that
|
||||||
|
finished while the server was down is read back from that file; one that
|
||||||
|
ended without a result marks the run interrupted, saying so (its prompt is
|
||||||
|
never sent again). An interrupted outcome repair follow-up is asked again.
|
||||||
- **Overrides.** `--model` and `--stage-model` must give an
|
- **Overrides.** `--model` and `--stage-model` must give an
|
||||||
`anthropic/<model>` for these stages; the launch is refused otherwise.
|
`anthropic/<model>` for these stages; the launch is refused otherwise.
|
||||||
|
|
||||||
|
|||||||
@@ -182,6 +182,7 @@ Options: `--server-url ws(s)://host:port/connect`, `--notes TEXT`, `--prefix`.
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
./install --linux --output ./dist
|
./install --linux --output ./dist
|
||||||
|
./install --linux --install # also install it for this user (launcher, icon)
|
||||||
./install --macos --flutter /path/to/flutter --output ./dist
|
./install --macos --flutter /path/to/flutter --output ./dist
|
||||||
# Offer this desktop build through an installed server's update feed:
|
# Offer this desktop build through an installed server's update feed:
|
||||||
./install --linux --publish --notes "Release notes"
|
./install --linux --publish --notes "Release notes"
|
||||||
@@ -195,6 +196,25 @@ from the `pipelines` server CLI. The target Linux desktop needs GTK 3 and its
|
|||||||
runtime libraries (Debian/Ubuntu: `libgtk-3-0`, `libstdc++6`, `liblzma5`). This is a
|
runtime libraries (Debian/Ubuntu: `libgtk-3-0`, `libstdc++6`, `liblzma5`). This is a
|
||||||
portable bundle, not a package-manager installation or a server installation.
|
portable bundle, not a package-manager installation or a server installation.
|
||||||
|
|
||||||
|
`./install --linux --install` also installs it for the current user:
|
||||||
|
the bundle goes to `<prefix>/lib/app-linux` (default
|
||||||
|
`~/.local/share/pipelines/lib/app-linux`; the previous one is kept as
|
||||||
|
`app-linux.previous`), with `~/.local/share/applications/com.pipelines.app.desktop`,
|
||||||
|
its icon in `~/.local/share/icons/hicolor` and a `~/.local/bin/pipelines-app`
|
||||||
|
link. `scripts/install-linux-app.sh <archive>` installs a downloaded archive the
|
||||||
|
same way. The desktop entry is named after the GTK application id, which is
|
||||||
|
also the Wayland app id (Hyprland's window class), so launchers, docks and
|
||||||
|
window rules match the window. The app runs as a native Wayland client (GTK
|
||||||
|
picks Wayland when `WAYLAND_DISPLAY` is set and `GDK_BACKEND` is not forced to
|
||||||
|
`x11`); it draws a GTK header bar only on GNOME.
|
||||||
|
|
||||||
|
Release builds are size-optimised: Dart debug symbols are split out
|
||||||
|
(`--split-debug-info`, kept in the build cache under `.debug-info/` for
|
||||||
|
`flutter symbolize`) and the icon fonts are tree-shaken (the build image fixes
|
||||||
|
Flutter 3.44's Linux backend, which otherwise ships the full MaterialIcons
|
||||||
|
font). The Linux app has no web view or file share sheet, so HTML artifacts
|
||||||
|
show an explanation instead of a preview and Share is not offered (Download is).
|
||||||
|
|
||||||
macOS 12 or newer is required. macOS builds run natively with Xcode and the pinned Flutter version from
|
macOS 12 or newer is required. macOS builds run natively with Xcode and the pinned Flutter version from
|
||||||
`app/.flutter-version`; they do not require Docker. The build targets the build
|
`app/.flutter-version`; they do not require Docker. The build targets the build
|
||||||
machine's architecture and records the actual executable architecture in the
|
machine's architecture and records the actual executable architecture in the
|
||||||
|
|||||||
+8
-3
@@ -42,9 +42,14 @@ Edit that schedule explicitly when you want it to use a newer version.
|
|||||||
never guesses from workflow Markdown or a current pipeline's schedule state.
|
never guesses from workflow Markdown or a current pipeline's schedule state.
|
||||||
|
|
||||||
Each dispatch is claimed once. Missed occurrences after downtime are skipped,
|
Each dispatch is claimed once. Missed occurrences after downtime are skipped,
|
||||||
not replayed. Workspace conflicts are refused and journaled, not silently run
|
not replayed. A scheduled run whose workspace another run holds is delayed,
|
||||||
concurrently or retried as agent work. Use separate workspaces for truly
|
never run concurrently: it is recorded as `delayed` in the schedule's history
|
||||||
independent concurrent execution. **Refresh** in Schedules reloads its latest
|
and tried again every 5 minutes for up to 2 hours (set
|
||||||
|
`PIPELINES_SCHEDULE_BUSY_RETRY_EVERY` / `PIPELINES_SCHEDULE_BUSY_RETRY_FOR` on
|
||||||
|
the server, as Go durations; `0` for FOR skips at once), then recorded as
|
||||||
|
`started` or `skipped` with the reason. The operator gets a low-priority
|
||||||
|
notification when a scheduled run is delayed or skipped. Use separate
|
||||||
|
workspaces for truly independent concurrent execution. **Refresh** in Schedules reloads its latest
|
||||||
configuration and next due times.
|
configuration and next due times.
|
||||||
|
|
||||||
## JSON API / CLI automation
|
## JSON API / CLI automation
|
||||||
|
|||||||
+27
-12
@@ -30,15 +30,26 @@ includes the same evidence under each step's `file_changes` field.
|
|||||||
conversion, `assume-unchanged`) is listed with `no_patch_reason: "baseline"`.
|
conversion, `assume-unchanged`) is listed with `no_patch_reason: "baseline"`.
|
||||||
- Added/deleted files and permission changes are recorded. Renames appear as
|
- Added/deleted files and permission changes are recorded. Renames appear as
|
||||||
deletion/addition. Binary changes retain metadata, not binary contents.
|
deletion/addition. Binary changes retain metadata, not binary contents.
|
||||||
- Symlinks, special files, common credential/environment/key/database paths,
|
- Common credential/environment/key/database paths and `secrets/` are protected:
|
||||||
`secrets/`, Git internals and `node_modules/` are excluded. This is a path-based
|
never opened or listed. They are fingerprinted by metadata (size, mtime, mode)
|
||||||
|
only, so an untouched `.env` no longer makes a capture partial; a change to one
|
||||||
|
makes the visit `partial` (counted in `skipped`). This is a path-based
|
||||||
precaution, **not secret-content scanning**; ordinary source patches may contain
|
precaution, **not secret-content scanning**; ordinary source patches may contain
|
||||||
sensitive text and become part of retained history.
|
sensitive text and become part of retained history.
|
||||||
- Limits: 10,000 inventoried entries, 1 MiB per file and 32 MiB per snapshot of
|
- Tool output is not stage work: untracked files below cache and dependency
|
||||||
retained text, 256 MiB per hashed file, five seconds per snapshot, 5,000
|
directories (`node_modules/`, `.git/`, `__pycache__/`, `.venv/`, `.mypy_cache/`,
|
||||||
combined lines per textual comparison, 64 KiB per patch and 128 KiB serialized
|
`.pytest_cache/`, `.ruff_cache/`, `.next/`, `.dart_tool/`, `.gradle/`, ...),
|
||||||
file evidence per visit. Oversized, unreadable, omitted or truncated evidence
|
untracked `*.pyc`, and untracked files below `build/`, `dist/`, `out/`,
|
||||||
is explicitly flagged partial.
|
`target/` or `coverage/` where Git tracks nothing are left out of the
|
||||||
|
inventory entirely. Outside Git the cache directories are not walked.
|
||||||
|
- Symlinks are compared by their target (never followed) and listed with
|
||||||
|
`no_patch_reason: "symlink"`; a path through a symlinked directory is skipped.
|
||||||
|
- Limits: 20,000 inventoried entries, 1 MiB per file and 32 MiB per snapshot of
|
||||||
|
retained text, five seconds per snapshot, 20,000 combined lines per textual
|
||||||
|
comparison, 128 KiB per patch and 512 KiB serialized file evidence per visit.
|
||||||
|
Files over 256 MiB are compared by size, mtime and mode
|
||||||
|
(`no_patch_reason: "large"`). Unreadable, omitted or truncated evidence is
|
||||||
|
explicitly flagged partial.
|
||||||
- Over-budget content degrades to a listing, not silence: a text file over 1 MiB,
|
- Over-budget content degrades to a listing, not silence: a text file over 1 MiB,
|
||||||
or beyond the 32 MiB snapshot budget, is still compared by SHA-256 and a change
|
or beyond the 32 MiB snapshot budget, is still compared by SHA-256 and a change
|
||||||
is listed with `no_patch: true` (and `truncated`) but no patch. In a Git working
|
is listed with `no_patch: true` (and `truncated`) but no patch. In a Git working
|
||||||
@@ -46,12 +57,16 @@ includes the same evidence under each step's `file_changes` field.
|
|||||||
or past the time/file limit) is listed the same way when its
|
or past the time/file limit) is listed the same way when its
|
||||||
`git status --porcelain` entry changed during the visit; a path dirty with the
|
`git status --porcelain` entry changed during the visit; a path dirty with the
|
||||||
same status before and after cannot be proven changed and stays in `skipped`.
|
same status before and after cannot be proven changed and stays in `skipped`.
|
||||||
Git is only read (`--no-optional-locks`); protected paths are never listed.
|
Git is only read (`--no-optional-locks`); protected and excluded paths are
|
||||||
|
never listed.
|
||||||
- Each content change without a (complete) patch carries `no_patch_reason`:
|
- Each content change without a (complete) patch carries `no_patch_reason`:
|
||||||
`binary`, `file_size` (text over 1 MiB), `budget` (32 MiB snapshot text
|
`binary`, `symlink`, `large`, `generated` (lockfiles such as `go.sum` or
|
||||||
budget), `lines` (over 5,000 combined lines), `evidence_size` (per-visit
|
`package-lock.json`, `*.min.js`, source maps, files below a cache directory),
|
||||||
retained evidence limit), `git_status` (seen only in Git status) or `baseline`.
|
`file_size` (text over 1 MiB), `budget` (32 MiB snapshot text budget), `lines`
|
||||||
Binary changes stay `complete`; the others make the visit `partial`.
|
(over 20,000 combined lines), `evidence_size` (per-visit retained evidence
|
||||||
|
limit), `git_status` (seen only in Git status) or `baseline`. `binary`,
|
||||||
|
`symlink`, `large` and `generated` changes are listed completely and stay
|
||||||
|
`complete`; the others make the visit `partial`.
|
||||||
- `pipelines inspect RUN_ID --json` carries a top-level `warnings` list (also
|
- `pipelines inspect RUN_ID --json` carries a top-level `warnings` list (also
|
||||||
printed to stderr) naming every visit whose capture was partial or unavailable.
|
printed to stderr) naming every visit whose capture was partial or unavailable.
|
||||||
- Failed/canceled stages still retain changes when execution returns. Unconfirmed
|
- Failed/canceled stages still retain changes when execution returns. Unconfirmed
|
||||||
|
|||||||
@@ -64,7 +64,12 @@ Start from `pipelines templates` and `pipelines new NAME --template KEY`
|
|||||||
(`research`, `task`); these fill in
|
(`research`, `task`); these fill in
|
||||||
the server's provider/model. Read `references/format.md` and
|
the server's provider/model. Read `references/format.md` and
|
||||||
`references/practices.md` before writing prompts. Stage names: `plan` ·
|
`references/practices.md` before writing prompts. Stage names: `plan` ·
|
||||||
`implement` · `review` · `ui-review` · `decide` (human) · `land`.
|
`implement` · `verify` (check) · `review` · `ui-review` · `decide` (human) ·
|
||||||
|
`land`. A `type=check` stage runs listed shell commands on the server, no
|
||||||
|
model, and routes on `pass`/`fail`: put one before review and use one with
|
||||||
|
`delivery=true` as the landing gate rather than having a model run the suite.
|
||||||
|
Stages with `shell` but no `edit` must not change the workspace (the server fails the
|
||||||
|
visit); give reviewers a `permissions.shell` allow-list.
|
||||||
|
|
||||||
Keep prompts short and objective: what the stage should produce and any real
|
Keep prompts short and objective: what the stage should produce and any real
|
||||||
constraints. The runner enforces turns, tools and limits and explains the output
|
constraints. The runner enforces turns, tools and limits and explains the output
|
||||||
|
|||||||
@@ -9,9 +9,9 @@ request does not authorize publication, execution or deployment.
|
|||||||
Inspect actual source and diffs, run relevant tests and record exact results.
|
Inspect actual source and diffs, run relevant tests and record exact results.
|
||||||
A model summary, committed branch or successful merge is not proof of runtime
|
A model summary, committed branch or successful merge is not proof of runtime
|
||||||
behavior. Missing or partial diff capture must be reported as incomplete.
|
behavior. Missing or partial diff capture must be reported as incomplete.
|
||||||
With delivery=true, the stage returns a clean candidate and the server checks and
|
With delivery=true (a model land stage on any harness, or a check stage), the
|
||||||
lands it, first merging a moved main and re-checking the merged tree; only a real
|
server checks and lands the candidate, first merging a moved main and
|
||||||
conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
|
re-checking the merged tree; only a real conflict fails. Direct recovery can complete a reviewed merge without another pipeline.
|
||||||
|
|
||||||
Keep artifacts under the supplied run/stage artifact directory. Mark unverified
|
Keep artifacts under the supplied run/stage artifact directory. Mark unverified
|
||||||
builds as WIP. Verify any download URL serves the real bytes before reporting it.
|
builds as WIP. Verify any download URL serves the real bytes before reporting it.
|
||||||
|
|||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
|
A definition is Markdown made only of `# stage KEY` headings and fenced blocks;
|
||||||
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
|
no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`,
|
||||||
`checks`, `limits` (`references/control.md`), `permissions` and `notify`
|
`checks`, `limits` (`references/control.md`), `permissions`, `notify`
|
||||||
(`references/notifications.md`). There are no memory, links, input or output
|
(`references/notifications.md`) and, on check stages, `commands`. There are no memory, links, input or output
|
||||||
blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
|
blocks; stages communicate through `output.md` (`# handoff`) and `public/`.
|
||||||
Schedules are saved run configurations, never definition blocks
|
Schedules are saved run configurations, never definition blocks
|
||||||
(`references/schedules.md`).
|
(`references/schedules.md`).
|
||||||
@@ -102,8 +102,9 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
|
|||||||
(`pipelines new NAME --template KEY`) fill them in; copy those IDs into a
|
(`pipelines new NAME --template KEY`) fill them in; copy those IDs into a
|
||||||
hand-written draft. Availability needs `pipelines provider-check`.
|
hand-written draft. Availability needs `pipelines provider-check`.
|
||||||
- `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`).
|
- `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`).
|
||||||
`claude` needs `provider=anthropic` and a Claude model ID, and accepts no
|
`claude` needs `provider=anthropic` and a Claude model ID; its `permissions`
|
||||||
`permissions` block, `delivery=true` or run write paths.
|
block may hold only a `shell` allow-list (no `edit` patterns or run write
|
||||||
|
paths).
|
||||||
- `retries` 0–100, default 2 (three attempts). Retries cover transport failures
|
- `retries` 0–100, default 2 (three attempts). Retries cover transport failures
|
||||||
and timeouts; a stage with `edit`/`shell` (or no tools block) never replays
|
and timeouts; a stage with `edit`/`shell` (or no tools block) never replays
|
||||||
admitted work.
|
admitted work.
|
||||||
@@ -114,7 +115,10 @@ evidence route to `blocked` when declared, else `error`; never fabricate a resul
|
|||||||
- `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across
|
- `budget_usd`, `budget_tokens`: positive caps on reported usage, shared across
|
||||||
attempts and visits of this stage; totals include cache reads and writes. Set
|
attempts and visits of this stage; totals include cache reads and writes. Set
|
||||||
only when the user asks or a measured visit exists (`references/practices.md`).
|
only when the user asks or a measured visit exists (`references/practices.md`).
|
||||||
- `delivery=true`: the landing stage's gate (below). OpenCode harness only.
|
- `delivery=true`: the landing stage's gate (below), on any harness, or on a
|
||||||
|
check stage.
|
||||||
|
- `allow_workspace_changes=true`: lets a stage with `shell` but no `edit` leave file changes
|
||||||
|
in the run directory (below).
|
||||||
- `auto_skip=false`: disable the server skip fallback for a stage that declares a
|
- `auto_skip=false`: disable the server skip fallback for a stage that declares a
|
||||||
`skipped` edge (`references/operations.md`, Server skip fallback).
|
`skipped` edge (`references/operations.md`, Server skip fallback).
|
||||||
|
|
||||||
@@ -134,6 +138,20 @@ patterns) and `shell` (exact commands) arrays. It narrows declared tools; it nev
|
|||||||
enables a missing one. Empty arrays deny; wildcards, chaining, redirects and
|
enables a missing one. Empty arrays deny; wildcards, chaining, redirects and
|
||||||
traversal are rejected. With restricted edits and shell enabled, list shell too:
|
traversal are rejected. With restricted edits and shell enabled, list shell too:
|
||||||
`{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`.
|
`{"edit":["README.md","plugin/*.qml"],"shell":["bash -n install.sh"]}`.
|
||||||
|
On `harness=claude` only `shell` is accepted; each entry becomes a Claude Code
|
||||||
|
rule (`go test ./...` -> `Bash(go test ./...)`) and an entry ending in ` *` is a
|
||||||
|
prefix (`git diff *` -> `Bash(git diff:*)`, any arguments; claude only). Claude
|
||||||
|
Code checks each part of a chained command, and every other command is
|
||||||
|
refused. A read-only reviewer: `{"shell":["git diff *","git log *","go test ./..."]}`.
|
||||||
|
|
||||||
|
A stage whose `tools` block has `shell` but not `edit` must leave the run directory as it
|
||||||
|
found it: the server compares the workspace before and after the visit and
|
||||||
|
fails the visit (`permission denied: ... changed the workspace (added x, ...)`,
|
||||||
|
following the `error` edge) when any file changed, outside the run's artifact
|
||||||
|
directories and a harness state directory inside the workspace. Committing is
|
||||||
|
not a change; merging or generating files is. Set
|
||||||
|
`allow_workspace_changes=true` on a stage that legitimately writes (for
|
||||||
|
example a land stage that merges main itself).
|
||||||
|
|
||||||
Named MCP entries are an explicit allowlist for unattended Claude stages:
|
Named MCP entries are an explicit allowlist for unattended Claude stages:
|
||||||
`mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues`
|
`mcp:ai-memory` allows that server's tools, while `mcp:linear/list_issues`
|
||||||
@@ -190,6 +208,56 @@ A check must fail when it cannot run: validation rejects `|| true`, `|| :`,
|
|||||||
`|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no
|
`|| exit 0`, `|| echo`, negated file tests, `! command -v tool ||`, an `if` with no
|
||||||
failing else, and `set +e`. Cover every language the run can change.
|
failing else, and `set +e`. Cover every language the run can change.
|
||||||
|
|
||||||
|
## Check stages
|
||||||
|
|
||||||
|
`type=check` runs shell commands on the server, without a model, and routes on
|
||||||
|
`pass` or `fail`. Use it before review, so a reviewer never sees a red tree, and
|
||||||
|
as the landing gate instead of a model stage that runs the suite itself.
|
||||||
|
|
||||||
|
````markdown
|
||||||
|
# stage verify
|
||||||
|
|
||||||
|
```configs
|
||||||
|
type=check
|
||||||
|
command_timeout=15m
|
||||||
|
```
|
||||||
|
|
||||||
|
```commands
|
||||||
|
uv run ruff check .
|
||||||
|
uv run ty check
|
||||||
|
uv run pytest -q
|
||||||
|
```
|
||||||
|
|
||||||
|
```edges
|
||||||
|
pass -> review
|
||||||
|
fail -> implement
|
||||||
|
```
|
||||||
|
|
||||||
|
```limits
|
||||||
|
{"max_visits":3}
|
||||||
|
```
|
||||||
|
````
|
||||||
|
|
||||||
|
- `commands` (required): 1-20 lines, one `sh -c` command each, run in order
|
||||||
|
from the run directory with its workspace environment; blank and `#` lines are
|
||||||
|
ignored. The first failure stops the rest (`not_run`) unless `keep_going=true`.
|
||||||
|
Lint rejects silent guards (`|| true`) as for `checks`.
|
||||||
|
- Configs: `command_timeout` (per command, default `30m`), `timeout` (the whole
|
||||||
|
stage, default `1h`), `keep_going=true|false`, `delivery=true`. No prompt,
|
||||||
|
tools, model or skills.
|
||||||
|
- Edges: `pass` and `fail` are required and are the only outcomes besides
|
||||||
|
`error` (an infrastructure failure). A `fail` loop back needs `limits`.
|
||||||
|
- Output: the step records each command's status (`passed`, `failed`,
|
||||||
|
`timed_out`, `not_run`), exit code, duration and output (64 KB per failing
|
||||||
|
command, head and tail kept), plus a one-line summary as its verdict. Its
|
||||||
|
`# handoff` names the failing commands with the tail of their output, and the
|
||||||
|
full outputs follow, so the next stage sees exactly what failed.
|
||||||
|
- `delivery=true` makes it the landing gate: the server commits what the run
|
||||||
|
left uncommitted (run worktrees), merges a moved `main`, runs the commands in
|
||||||
|
a fresh worktree of the commit and fast-forwards `main` on `pass`. A failing
|
||||||
|
command is `fail` with `main` untouched; a gate problem (dirty checkout,
|
||||||
|
conflict, refused fast-forward) is `error`.
|
||||||
|
|
||||||
## Human stages
|
## Human stages
|
||||||
|
|
||||||
`type=human` pauses the run until a person picks one of its non-`error` edges
|
`type=human` pauses the run until a person picks one of its non-`error` edges
|
||||||
@@ -201,14 +269,17 @@ wait survives restarts and is never killed by a stage timeout or `max_visits`.
|
|||||||
|
|
||||||
## Land stage and delivery gate
|
## Land stage and delivery gate
|
||||||
|
|
||||||
A workflow that commits its change ends in `land`: a model stage with
|
A workflow that commits its change ends in `land`: either a check stage with
|
||||||
`read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. Its prompt states:
|
`delivery=true` (above; no model, the server commits and lands), or a model
|
||||||
|
stage with `read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. A model
|
||||||
|
land stage's prompt states:
|
||||||
|
|
||||||
1. Commit only this run's changes (server list + git status).
|
1. Commit only this run's changes (server list + git status).
|
||||||
2. Check the staged diff for unrelated work and secrets.
|
2. Check the staged diff for unrelated work and secrets.
|
||||||
3. No empty commit, push, amend or rebase. Report the hash.
|
3. No empty commit, push, amend or rebase. Report the hash.
|
||||||
|
|
||||||
With `delivery=true` and `checks` commands, after `land` succeeds the server:
|
With `delivery=true` and `checks` commands (any harness), after `land` succeeds
|
||||||
|
the server:
|
||||||
commits whatever the run left uncommitted when the item is the run's own
|
commits whatever the run left uncommitted when the item is the run's own
|
||||||
worktree (see "Run worktrees" below); requires the item checkout to be clean,
|
worktree (see "Run worktrees" below); requires the item checkout to be clean,
|
||||||
untracked files included (the main checkout need not be: the final
|
untracked files included (the main checkout need not be: the final
|
||||||
|
|||||||
@@ -119,6 +119,25 @@ func TestInspectStepAndTranscriptsAndJSON(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestInspectStepListsCheckCommandsAndRepairs(t *testing.T) {
|
||||||
|
d := &protocol.RunDetail{ID: 7, Steps: []protocol.RunStep{{Sequence: 1, Stage: "verify", Status: "completed", Outcome: "fail",
|
||||||
|
Control: &protocol.ControlEvidence{OutcomeRepairs: 1},
|
||||||
|
Output: map[string]any{"markdown": "# outcome\n\nfail\n", "checks": []any{
|
||||||
|
map[string]any{"command": "go vet ./...", "status": "passed", "exit_code": float64(0), "duration_ms": float64(1200)},
|
||||||
|
map[string]any{"command": "go test ./...", "status": "failed", "exit_code": float64(1), "duration_ms": float64(51000)},
|
||||||
|
}}}}}
|
||||||
|
var out bytes.Buffer
|
||||||
|
if err := (App{Out: &out}).inspect(d, &options{step: 1}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
text := out.String()
|
||||||
|
for _, want := range []string{"outcome repair follow-ups: 1", "passed exit 0 1.2s go vet ./...", "failed exit 1 51.0s go test ./..."} {
|
||||||
|
if !strings.Contains(text, want) {
|
||||||
|
t.Fatalf("missing %q:\n%s", want, text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
|
func TestWaitLineNamesFailingStageAndDiagnostic(t *testing.T) {
|
||||||
line := waitLine(sampleRun())
|
line := waitLine(sampleRun())
|
||||||
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
|
if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") {
|
||||||
|
|||||||
@@ -93,9 +93,23 @@ func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string,
|
|||||||
if step.SessionID != "" {
|
if step.SessionID != "" {
|
||||||
b.WriteString("session: " + step.SessionID + "\n")
|
b.WriteString("session: " + step.SessionID + "\n")
|
||||||
}
|
}
|
||||||
|
if step.Control != nil && step.Control.OutcomeRepairs > 0 {
|
||||||
|
fmt.Fprintf(&b, "outcome repair follow-ups: %d\n", step.Control.OutcomeRepairs)
|
||||||
|
}
|
||||||
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
|
if diagnostic := strings.TrimSpace(step.Diagnostic); diagnostic != "" {
|
||||||
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
|
b.WriteString("\ndiagnostic:\n" + indent(diagnostic) + "\n")
|
||||||
}
|
}
|
||||||
|
if checks, ok := step.Output["checks"].([]any); ok && len(checks) > 0 {
|
||||||
|
b.WriteString("\nchecks:\n")
|
||||||
|
for _, entry := range checks {
|
||||||
|
check, _ := entry.(map[string]any)
|
||||||
|
command, _ := check["command"].(string)
|
||||||
|
status, _ := check["status"].(string)
|
||||||
|
exit, _ := check["exit_code"].(float64)
|
||||||
|
duration, _ := check["duration_ms"].(float64)
|
||||||
|
fmt.Fprintf(&b, " %-9s exit %-3d %6.1fs %s\n", status, int(exit), duration/1000, command)
|
||||||
|
}
|
||||||
|
}
|
||||||
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
|
if markdown, ok := step.Output["markdown"].(string); ok && strings.TrimSpace(markdown) != "" {
|
||||||
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
|
b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n")
|
||||||
} else if len(step.Output) > 0 {
|
} else if len(step.Output) > 0 {
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package filediff
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Policy no-patch reasons: the change is listed, completely, without a patch
|
||||||
|
// by design rather than because a capture limit ran out, so it never makes a
|
||||||
|
// capture partial.
|
||||||
|
const (
|
||||||
|
reasonSymlink = "symlink" // a symbolic link; its target is compared
|
||||||
|
reasonLarge = "large" // over the hash bound; compared by size, mtime and mode
|
||||||
|
reasonGenerated = "generated" // a lockfile, minified bundle or source map
|
||||||
|
)
|
||||||
|
|
||||||
|
// cacheDirs are tool caches, virtual environments and dependency trees. Their
|
||||||
|
// untracked files are left out of the inventory entirely (never "skipped"):
|
||||||
|
// they are regenerated by tools, not authored by a stage. Tracked files below
|
||||||
|
// them are still compared, without a patch.
|
||||||
|
var cacheDirs = map[string]bool{
|
||||||
|
"node_modules": true, "bower_components": true, ".git": true,
|
||||||
|
"__pycache__": true, ".venv": true, "venv": true, ".tox": true, ".nox": true,
|
||||||
|
".mypy_cache": true, ".pytest_cache": true, ".ruff_cache": true, ".hypothesis": true, ".eggs": true,
|
||||||
|
".next": true, ".nuxt": true, ".svelte-kit": true, ".turbo": true, ".parcel-cache": true, ".pnpm-store": true,
|
||||||
|
".dart_tool": true, ".gradle": true, ".terraform": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildDirs are conventional build output directories. Untracked files below
|
||||||
|
// one are left out only when Git tracks nothing there, so a new source file
|
||||||
|
// in a real `build/` source directory is still captured.
|
||||||
|
var buildDirs = map[string]bool{"build": true, "dist": true, "out": true, "target": true, "coverage": true}
|
||||||
|
|
||||||
|
// generatedNames are lockfiles: tool output whose diff is noise.
|
||||||
|
var generatedNames = map[string]bool{
|
||||||
|
"package-lock.json": true, "npm-shrinkwrap.json": true, "yarn.lock": true, "pnpm-lock.yaml": true,
|
||||||
|
"bun.lockb": true, "cargo.lock": true, "go.sum": true, "poetry.lock": true, "uv.lock": true,
|
||||||
|
"pipfile.lock": true, "gemfile.lock": true, "composer.lock": true, "pubspec.lock": true,
|
||||||
|
"flake.lock": true, "mix.lock": true, "podfile.lock": true, "packages.lock.json": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// inCacheDir reports whether any directory component of name is a cache dir.
|
||||||
|
func inCacheDir(name string) bool {
|
||||||
|
parts := strings.Split(name, "/")
|
||||||
|
for _, part := range parts[:len(parts)-1] {
|
||||||
|
if cacheDirs[part] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// generatedFile reports a file whose diff is tool output: a lockfile, a
|
||||||
|
// minified bundle, a source map, compiled Python, or anything below a cache
|
||||||
|
// directory.
|
||||||
|
func generatedFile(name string) bool {
|
||||||
|
base := strings.ToLower(path.Base(name))
|
||||||
|
if generatedNames[base] || strings.HasSuffix(base, ".min.js") || strings.HasSuffix(base, ".min.css") ||
|
||||||
|
strings.HasSuffix(base, ".map") || strings.HasSuffix(base, ".pyc") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return inCacheDir(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// excludedUntracked reports an untracked path that is tool output rather than
|
||||||
|
// stage work: below a cache directory, compiled Python, or below a build
|
||||||
|
// directory where Git tracks nothing (trackedDirs holds every directory that
|
||||||
|
// contains a tracked file).
|
||||||
|
func excludedUntracked(name string, trackedDirs map[string]bool) bool {
|
||||||
|
if inCacheDir(name) || strings.HasSuffix(name, ".pyc") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
parts := strings.Split(name, "/")
|
||||||
|
for i, part := range parts[:len(parts)-1] {
|
||||||
|
if buildDirs[part] && !trackedDirs[strings.Join(parts[:i+1], "/")] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// trackedDirectories returns every ancestor directory of the tracked names.
|
||||||
|
func trackedDirectories(names []string) map[string]bool {
|
||||||
|
dirs := map[string]bool{}
|
||||||
|
for _, name := range names {
|
||||||
|
for dir := path.Dir(name); dir != "." && dir != "/" && !dirs[dir]; dir = path.Dir(dir) {
|
||||||
|
dirs[dir] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dirs
|
||||||
|
}
|
||||||
|
|
||||||
|
// policyReason is the policy no-patch reason of a changed path, preferring
|
||||||
|
// the stage-end side (a file that became a symlink is a symlink change).
|
||||||
|
func policyReason(a file, aOK bool, b file, bOK bool) string {
|
||||||
|
if bOK && b.reason != "" {
|
||||||
|
return b.reason
|
||||||
|
}
|
||||||
|
if aOK && a.reason != "" {
|
||||||
|
return a.reason
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// metaHash fingerprints a file by its metadata alone, without reading it: a
|
||||||
|
// protected (secret) file is never opened, and a huge file is not hashed.
|
||||||
|
func metaHash(info fs.FileInfo) [32]byte {
|
||||||
|
return sha256.Sum256(fmt.Appendf(nil, "meta\x00%d\x00%d\x00%o", info.Size(), info.ModTime().UnixNano(), info.Mode()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// linkHash fingerprints a symbolic link by its target.
|
||||||
|
func linkHash(target string) [32]byte {
|
||||||
|
return sha256.Sum256([]byte("symlink\x00" + target))
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package filediff
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A committed symlink no longer makes every capture partial, and a symlink a
|
||||||
|
// stage creates (a read-only reviewer's stray link) is listed.
|
||||||
|
func TestSymlinksAreComparedByTarget(t *testing.T) {
|
||||||
|
dir, git := gitRepo(t)
|
||||||
|
put(t, dir, "real.md", "skill\n")
|
||||||
|
if err := os.Symlink("real.md", filepath.Join(dir, "linked")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
git("add", "real.md", "linked")
|
||||||
|
git("commit", "-qm", "init")
|
||||||
|
ctx := context.Background()
|
||||||
|
before := Capture(ctx, dir)
|
||||||
|
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 || len(quiet.Files) != 0 {
|
||||||
|
t.Fatalf("an untouched symlink: %+v", quiet)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("/etc", filepath.Join(dir, "stray")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
changes := Compare(before, Capture(ctx, dir, before))
|
||||||
|
if changes.Status != "complete" || len(changes.Files) != 1 {
|
||||||
|
t.Fatalf("%+v", changes)
|
||||||
|
}
|
||||||
|
if f := changes.Files[0]; f.Path != "stray" || f.Kind != "added" || f.NoPatchReason != reasonSymlink || f.Truncated {
|
||||||
|
t.Fatalf("%+v", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolOutputIsExcludedOrListedWithoutPatch(t *testing.T) {
|
||||||
|
dir, git := gitRepo(t)
|
||||||
|
for _, name := range []string{"build/keep.sh", "go.sum", "src/a.go"} {
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
put(t, dir, name, "v1\n")
|
||||||
|
}
|
||||||
|
git("add", ".")
|
||||||
|
git("commit", "-qm", "init")
|
||||||
|
ctx := context.Background()
|
||||||
|
before := Capture(ctx, dir)
|
||||||
|
for _, name := range []string{"node_modules/x/index.js", "dist/app.js", "src/__pycache__/a.pyc", "build/new.sh"} {
|
||||||
|
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
put(t, dir, name, "generated\n")
|
||||||
|
}
|
||||||
|
put(t, dir, "go.sum", "v2\n")
|
||||||
|
put(t, dir, "src/a.go", "v2\n")
|
||||||
|
changes := Compare(before, Capture(ctx, dir, before))
|
||||||
|
got := map[string]string{}
|
||||||
|
for _, f := range changes.Files {
|
||||||
|
got[f.Path] = f.NoPatchReason
|
||||||
|
}
|
||||||
|
// Untracked caches and an untracked build directory are left out; a new
|
||||||
|
// file in a tracked build directory is stage work; a lockfile has no patch.
|
||||||
|
want := map[string]string{"build/new.sh": "", "go.sum": reasonGenerated, "src/a.go": ""}
|
||||||
|
if len(got) != len(want) || changes.Status != "complete" {
|
||||||
|
t.Fatalf("got %v (%+v)", got, changes)
|
||||||
|
}
|
||||||
|
for name, reason := range want {
|
||||||
|
if r, ok := got[name]; !ok || r != reason {
|
||||||
|
t.Fatalf("%s: got %q (%v)", name, r, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+121
-21
@@ -26,12 +26,12 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
maxFiles = 10000
|
maxFiles = 20000
|
||||||
maxFileBytes = 1 << 20
|
maxFileBytes = 1 << 20
|
||||||
maxSnapshotBytes = 32 << 20
|
maxSnapshotBytes = 32 << 20
|
||||||
maxPatchBytes = 128 << 10
|
maxPatchBytes = 512 << 10
|
||||||
maxFilePatchBytes = 64 << 10
|
maxFilePatchBytes = 128 << 10
|
||||||
maxLines = 5000
|
maxLines = 20000
|
||||||
binarySniffBytes = 8 << 10
|
binarySniffBytes = 8 << 10
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -82,6 +82,12 @@ type file struct {
|
|||||||
// already holds it, and a later capture recovers it only if the file
|
// already holds it, and a later capture recovers it only if the file
|
||||||
// changed. This keeps the text budget for files Git has no baseline for.
|
// changed. This keeps the text budget for files Git has no baseline for.
|
||||||
blob string
|
blob string
|
||||||
|
// reason is a policy no-patch reason (symlink, large, generated): the
|
||||||
|
// change is listed completely, without a patch, and no content is kept.
|
||||||
|
reason string
|
||||||
|
// secret marks a protected file fingerprinted by metadata only. It is
|
||||||
|
// never read or listed; a change to it makes the capture partial.
|
||||||
|
secret bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// baseline is stage-start content recovered from Git for a changed file whose
|
// baseline is stage-start content recovered from Git for a changed file whose
|
||||||
@@ -108,6 +114,9 @@ type Snapshot struct {
|
|||||||
// the previous snapshot; missing records why one could not be recovered.
|
// the previous snapshot; missing records why one could not be recovered.
|
||||||
baselines map[string]baseline
|
baselines map[string]baseline
|
||||||
missing map[string]string
|
missing map[string]string
|
||||||
|
// excluded holds untracked tool output left out of the inventory, so
|
||||||
|
// the Git-status pass does not list it either.
|
||||||
|
excluded map[string]bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// gitCommand runs git for directory with the run's directory environment
|
// gitCommand runs git for directory with the run's directory environment
|
||||||
@@ -245,7 +254,7 @@ func protected(name string) bool {
|
|||||||
if template(part) {
|
if template(part) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" || part == "node_modules" {
|
if part == ".git" || part == "secrets" || part == ".ssh" || part == ".aws" || part == ".gnupg" || part == ".kube" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" {
|
if part == ".env" || strings.HasPrefix(part, ".env.") || strings.HasSuffix(part, ".env") || strings.HasSuffix(part, ".pem") || strings.HasSuffix(part, ".key") || strings.HasSuffix(part, ".db") || strings.HasSuffix(part, ".db-wal") || strings.HasSuffix(part, ".db-shm") || strings.HasSuffix(part, ".sqlite") || strings.HasSuffix(part, ".sqlite3") || part == "auth.json" || part == "credentials.json" {
|
||||||
@@ -278,16 +287,43 @@ func (b *boundedOutput) Write(p []byte) (int, error) {
|
|||||||
|
|
||||||
// inventory lists the files to snapshot. Git is only read, never altered;
|
// inventory lists the files to snapshot. Git is only read, never altered;
|
||||||
// the baseline is still stage-start content (see Capture and recoverBaselines).
|
// the baseline is still stage-start content (see Capture and recoverBaselines).
|
||||||
func inventory(ctx context.Context, directory string, root *os.Root) ([]string, bool, error) {
|
func inventory(ctx context.Context, directory string, root *os.Root, excluded map[string]bool) ([]string, bool, error) {
|
||||||
probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree")
|
probe := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "rev-parse", "--is-inside-work-tree")
|
||||||
if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" {
|
if data, err := probe.Output(); err == nil && strings.TrimSpace(string(data)) == "true" {
|
||||||
cmd := gitCommand(ctx, directory, "-c", "core.fsmonitor=false", "-C", directory, "ls-files", "--cached", "--others", "--exclude-standard", "--deduplicate", "-z", "--", ".")
|
list := func(args ...string) ([]string, error) {
|
||||||
out := &boundedOutput{limit: 2 << 20}
|
cmd := gitCommand(ctx, directory, append([]string{"-c", "core.fsmonitor=false", "-C", directory, "ls-files"}, append(args, "-z", "--", ".")...)...)
|
||||||
cmd.Stdout = out
|
out := &boundedOutput{limit: 2 << 20}
|
||||||
if err := cmd.Run(); err != nil {
|
cmd.Stdout = out
|
||||||
return nil, true, fmt.Errorf("Git file inventory unavailable")
|
if err := cmd.Run(); err != nil {
|
||||||
|
return nil, fmt.Errorf("Git file inventory unavailable")
|
||||||
|
}
|
||||||
|
text := strings.TrimSuffix(out.String(), "\x00")
|
||||||
|
if text == "" {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return strings.Split(text, "\x00"), nil
|
||||||
}
|
}
|
||||||
return strings.Split(strings.TrimSuffix(out.String(), "\x00"), "\x00"), true, nil
|
tracked, err := list("--cached", "--deduplicate")
|
||||||
|
if err != nil {
|
||||||
|
return nil, true, err
|
||||||
|
}
|
||||||
|
untracked, err := list("--others", "--exclude-standard")
|
||||||
|
if err != nil {
|
||||||
|
return nil, true, err
|
||||||
|
}
|
||||||
|
// Untracked tool output (caches, dependency trees, untracked build
|
||||||
|
// directories) is not stage work: leave it out instead of letting it
|
||||||
|
// crowd the inventory and the budgets.
|
||||||
|
trackedDirs := trackedDirectories(tracked)
|
||||||
|
names := tracked
|
||||||
|
for _, name := range untracked {
|
||||||
|
if excludedUntracked(name, trackedDirs) {
|
||||||
|
excluded[name] = true
|
||||||
|
} else {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names, true, nil
|
||||||
}
|
}
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
return nil, false, ctx.Err()
|
return nil, false, ctx.Err()
|
||||||
@@ -300,6 +336,9 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if name != "." && entry.IsDir() && cacheDirs[entry.Name()] {
|
||||||
|
return fs.SkipDir // tool output, not stage work
|
||||||
|
}
|
||||||
if name != "." && protected(name) {
|
if name != "." && protected(name) {
|
||||||
names = append(names, name)
|
names = append(names, name)
|
||||||
if entry.IsDir() {
|
if entry.IsDir() {
|
||||||
@@ -319,7 +358,7 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot {
|
func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snapshot {
|
||||||
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}}
|
s := &Snapshot{files: map[string]file{}, skipped: map[string]bool{}, excluded: map[string]bool{}}
|
||||||
root, err := os.OpenRoot(directory)
|
root, err := os.OpenRoot(directory)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.diagnostic = "Workspace snapshot unavailable."
|
s.diagnostic = "Workspace snapshot unavailable."
|
||||||
@@ -327,7 +366,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
}
|
}
|
||||||
defer root.Close()
|
defer root.Close()
|
||||||
s.available = true
|
s.available = true
|
||||||
names, git, err := inventory(ctx, directory, root)
|
names, git, err := inventory(ctx, directory, root, s.excluded)
|
||||||
s.scope = "Workspace regular files"
|
s.scope = "Workspace regular files"
|
||||||
if git {
|
if git {
|
||||||
s.scope = "Git tracked and nonignored files in the run directory"
|
s.scope = "Git tracked and nonignored files in the run directory"
|
||||||
@@ -379,12 +418,13 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
s.diagnostic = "Workspace capture reached its time/file limit."
|
s.diagnostic = "Workspace capture reached its time/file limit."
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if !fs.ValidPath(name) || protected(name) {
|
if !fs.ValidPath(name) {
|
||||||
s.skipped[name] = true
|
s.skipped[name] = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Reject symlinks in every component, including aliases to sensitive paths.
|
// Never follow a symlink: a path through a symlinked directory is
|
||||||
valid := true
|
// skipped, and a symlink itself is compared by its target only.
|
||||||
|
valid, link := true, false
|
||||||
parts := strings.Split(name, "/")
|
parts := strings.Split(name, "/")
|
||||||
for j := range parts {
|
for j := range parts {
|
||||||
info, err := root.Lstat(strings.Join(parts[:j+1], "/"))
|
info, err := root.Lstat(strings.Join(parts[:j+1], "/"))
|
||||||
@@ -392,6 +432,10 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
valid = false
|
valid = false
|
||||||
break
|
break
|
||||||
} // tracked deletion
|
} // tracked deletion
|
||||||
|
if err == nil && info.Mode()&os.ModeSymlink != 0 && j == len(parts)-1 {
|
||||||
|
link = true
|
||||||
|
break
|
||||||
|
}
|
||||||
if err != nil || info.Mode()&os.ModeSymlink != 0 {
|
if err != nil || info.Mode()&os.ModeSymlink != 0 {
|
||||||
s.skipped[name] = true
|
s.skipped[name] = true
|
||||||
valid = false
|
valid = false
|
||||||
@@ -402,10 +446,38 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
info, err := root.Lstat(name)
|
info, err := root.Lstat(name)
|
||||||
if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes {
|
if err != nil {
|
||||||
s.skipped[name] = true
|
s.skipped[name] = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if protected(name) {
|
||||||
|
// A secret is never opened: its metadata shows whether it changed,
|
||||||
|
// so an untouched .env no longer makes every capture partial.
|
||||||
|
if info.IsDir() {
|
||||||
|
s.skipped[name] = true
|
||||||
|
} else {
|
||||||
|
s.files[name] = file{hash: metaHash(info), secret: true}
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if link {
|
||||||
|
target, err := root.Readlink(name)
|
||||||
|
if err != nil {
|
||||||
|
s.skipped[name] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s.files[name] = file{hash: linkHash(target), size: int64(len(target)), mode: info.Mode().Perm(), reason: reasonSymlink}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
s.skipped[name] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if info.Size() > maxHashBytes {
|
||||||
|
s.files[name] = file{hash: metaHash(info), size: info.Size(), mode: info.Mode().Perm(), reason: reasonLarge}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
generated := generatedFile(name)
|
||||||
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
|
f, err := root.OpenFile(name, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.skipped[name] = true
|
s.skipped[name] = true
|
||||||
@@ -440,6 +512,9 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
// listed (without a patch) instead of being skipped unseen.
|
// listed (without a patch) instead of being skipped unseen.
|
||||||
switch {
|
switch {
|
||||||
case binary:
|
case binary:
|
||||||
|
case generated:
|
||||||
|
// Tool output: compared by hash, listed without a patch.
|
||||||
|
entry.reason = reasonGenerated
|
||||||
case seen && p.hash == entry.hash && !p.binary:
|
case seen && p.hash == entry.hash && !p.binary:
|
||||||
// Unchanged since the previous snapshot: share its representation
|
// Unchanged since the previous snapshot: share its representation
|
||||||
// without spending this snapshot's budget on it again.
|
// without spending this snapshot's budget on it again.
|
||||||
@@ -463,7 +538,11 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap
|
|||||||
s.skipped[name] = true
|
s.skipped[name] = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
s.files[name] = file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
|
entry := file{hash: hash, size: opened.Size(), mode: opened.Mode().Perm(), binary: binary, hashOnly: !binary, limit: reasonFileSize}
|
||||||
|
if generated && !binary {
|
||||||
|
entry.hashOnly, entry.limit, entry.reason = false, "", reasonGenerated
|
||||||
|
}
|
||||||
|
s.files[name] = entry
|
||||||
}
|
}
|
||||||
if prev != nil {
|
if prev != nil {
|
||||||
s.recoverBaselines(ctx, directory, prev, used)
|
s.recoverBaselines(ctx, directory, prev, used)
|
||||||
@@ -584,6 +663,14 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
|||||||
result.Files = append(result.Files, change)
|
result.Files = append(result.Files, change)
|
||||||
}
|
}
|
||||||
listed := 0
|
listed := 0
|
||||||
|
secretChanges := 0
|
||||||
|
defer func() {
|
||||||
|
if secretChanges > 0 {
|
||||||
|
result.Skipped += secretChanges
|
||||||
|
result.Status = "partial"
|
||||||
|
result.Diagnostic = "A protected file (secrets, credentials, databases) changed; it is never read or listed, so this is not a complete workspace diff."
|
||||||
|
}
|
||||||
|
}()
|
||||||
// decided records every path the content comparison settled (changed or
|
// decided records every path the content comparison settled (changed or
|
||||||
// not), so the Git-status pass below only speaks for the rest.
|
// not), so the Git-status pass below only speaks for the rest.
|
||||||
decided := map[string]bool{}
|
decided := map[string]bool{}
|
||||||
@@ -598,7 +685,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
decided[name] = true
|
decided[name] = true
|
||||||
if aOK && bOK && a.hash == b.hash && a.mode == b.mode {
|
if aOK && bOK && a.hash == b.hash && a.mode == b.mode && a.secret == b.secret {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if a.secret || b.secret {
|
||||||
|
// A protected file changed: never listed, so the capture is honest
|
||||||
|
// about being incomplete.
|
||||||
|
secretChanges++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
kind := "modified"
|
kind := "modified"
|
||||||
@@ -615,6 +708,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
|||||||
if bOK {
|
if bOK {
|
||||||
change.AfterMode = fmt.Sprintf("%04o", b.mode)
|
change.AfterMode = fmt.Sprintf("%04o", b.mode)
|
||||||
}
|
}
|
||||||
|
if reason := policyReason(a, aOK, b, bOK); reason != "" {
|
||||||
|
// Listed completely by design (a symlink, a huge or generated
|
||||||
|
// file), without a patch; not a capture limit.
|
||||||
|
change.NoPatchReason = reason
|
||||||
|
add(change)
|
||||||
|
continue
|
||||||
|
}
|
||||||
// A clean-at-start file kept only its Git blob id; its start content
|
// A clean-at-start file kept only its Git blob id; its start content
|
||||||
// comes from the after snapshot's verified Git recovery.
|
// comes from the after snapshot's verified Git recovery.
|
||||||
aData, unavailable := a.data, ""
|
aData, unavailable := a.data, ""
|
||||||
@@ -690,7 +790,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges {
|
|||||||
}
|
}
|
||||||
ordered := make([]string, 0, len(gitNames))
|
ordered := make([]string, 0, len(gitNames))
|
||||||
for name := range gitNames {
|
for name := range gitNames {
|
||||||
if !decided[name] && fs.ValidPath(name) && !protected(name) {
|
if !decided[name] && fs.ValidPath(name) && !protected(name) && !before.excluded[name] && !after.excluded[name] {
|
||||||
ordered = append(ordered, name)
|
ordered = append(ordered, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -248,10 +248,10 @@ func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestGitStatusListsUncomparableChanges proves a file the content snapshot
|
// TestHugeFilesAreListedByMetadata proves a file above the hash bound is
|
||||||
// skips (here: above the hash bound) is still listed when its Git status
|
// listed completely (by size, mtime and mode, without a patch), while a
|
||||||
// changes during the visit, while a protected path never is.
|
// protected path is never listed and its change marks the capture partial.
|
||||||
func TestGitStatusListsUncomparableChanges(t *testing.T) {
|
func TestHugeFilesAreListedByMetadata(t *testing.T) {
|
||||||
previous := maxHashBytes
|
previous := maxHashBytes
|
||||||
maxHashBytes = 16
|
maxHashBytes = 16
|
||||||
defer func() { maxHashBytes = previous }()
|
defer func() { maxHashBytes = previous }()
|
||||||
@@ -263,21 +263,30 @@ func TestGitStatusListsUncomparableChanges(t *testing.T) {
|
|||||||
git("commit", "-qm", "init")
|
git("commit", "-qm", "init")
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
before := Capture(ctx, dir)
|
before := Capture(ctx, dir)
|
||||||
put(t, dir, "big.bin", strings.Repeat("y", 64))
|
if quiet := Compare(before, Capture(ctx, dir, before)); quiet.Status != "complete" || quiet.Skipped != 0 {
|
||||||
|
t.Fatalf("an untouched secret and huge file made the capture %+v", quiet)
|
||||||
|
}
|
||||||
|
put(t, dir, "big.bin", strings.Repeat("y", 65))
|
||||||
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
|
put(t, dir, "fresh.bin", strings.Repeat("z", 64))
|
||||||
put(t, dir, ".env", "A=2\n")
|
|
||||||
changes := Compare(before, Capture(ctx, dir, before))
|
changes := Compare(before, Capture(ctx, dir, before))
|
||||||
got := map[string]string{}
|
got := map[string]string{}
|
||||||
for _, f := range changes.Files {
|
for _, f := range changes.Files {
|
||||||
if !f.NoPatch {
|
if f.Patch != "" || f.NoPatchReason != reasonLarge || f.Truncated {
|
||||||
t.Fatalf("git-listed change carries a patch: %+v", f)
|
t.Fatalf("huge-file change: %+v", f)
|
||||||
}
|
}
|
||||||
got[f.Path] = f.Kind
|
got[f.Path] = f.Kind
|
||||||
}
|
}
|
||||||
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" {
|
if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" || changes.Status != "complete" {
|
||||||
t.Fatalf("git status listing = %v (%+v)", got, changes)
|
t.Fatalf("listing = %v (%+v)", got, changes)
|
||||||
}
|
}
|
||||||
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "without patches") {
|
put(t, dir, ".env", "A=2\n")
|
||||||
|
changes = Compare(before, Capture(ctx, dir, before))
|
||||||
|
for _, f := range changes.Files {
|
||||||
|
if f.Path == ".env" {
|
||||||
|
t.Fatal("a protected path was listed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if changes.Status != "partial" || !strings.Contains(changes.Diagnostic, "protected") {
|
||||||
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
|
t.Fatalf("status/diagnostic = %q/%q", changes.Status, changes.Diagnostic)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package pipeline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||||
|
)
|
||||||
|
|
||||||
|
func checkStageSource(key, commands, configs, edges string) string {
|
||||||
|
return "# stage " + key + "\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// A check stage sits between implement and review: a red tree goes back to
|
||||||
|
// the implementer with the failing output, never to the reviewer.
|
||||||
|
func TestParseCheckStageBeforeReview(t *testing.T) {
|
||||||
|
source := lintSource(
|
||||||
|
modelStage("implement", "Make the change.", "read\nedit\nshell", "success -> verify\nerror -> #failure", "```checks\nnone: the verify stage runs the suite\n```"),
|
||||||
|
checkStageSource("verify", "go vet ./...\ngo test ./...", "command_timeout=15m", "pass -> review\nfail -> implement"),
|
||||||
|
modelStage("review", "Review the diff.", "read\nglob\ngrep", "success -> #success\nerror -> #failure", ""),
|
||||||
|
)
|
||||||
|
g, err := ParseDefinition(source)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
verify := g.Stages[1]
|
||||||
|
if verify.Type != stage.CheckType || verify.Blocks["commands"] != "go vet ./...\ngo test ./..." || verify.Configs["command_timeout"] != "15m" {
|
||||||
|
t.Fatalf("parsed %+v", verify)
|
||||||
|
}
|
||||||
|
if verify.Edges["error"] != "#failure" || !verify.FallbackError {
|
||||||
|
t.Fatal("check stage error edge", verify.Edges)
|
||||||
|
}
|
||||||
|
def := StageDefinition(verify)
|
||||||
|
if _, err := stage.CheckStageSpec(def); err != nil {
|
||||||
|
t.Fatal("stored definition no longer validates:", err)
|
||||||
|
}
|
||||||
|
errs, _ := Lint(g)
|
||||||
|
var rules []string
|
||||||
|
for _, finding := range errs {
|
||||||
|
rules = append(rules, finding.String())
|
||||||
|
}
|
||||||
|
// fail -> implement loops back: the existing loop rule asks for a limit.
|
||||||
|
if len(errs) != 1 || errs[0].Rule != "limits" {
|
||||||
|
t.Fatalf("lint %v", rules)
|
||||||
|
}
|
||||||
|
limited := strings.Replace(source, "```configs\ntype=check", "```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check", 1)
|
||||||
|
if g, err = ParseDefinition(limited); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if errs, _ := Lint(g); len(errs) != 0 {
|
||||||
|
t.Fatal(errs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckStageRejectsModelBlocksAndSilentGuards(t *testing.T) {
|
||||||
|
if _, err := ParseDefinition(checkStageSource("verify", "go test ./...", "model=x", "pass -> #success\nfail -> #failure")); err == nil {
|
||||||
|
t.Fatal("model config accepted on a check stage")
|
||||||
|
}
|
||||||
|
if _, err := ParseDefinition(checkStageSource("verify", "", "", "pass -> #success\nfail -> #failure")); err == nil {
|
||||||
|
t.Fatal("empty commands accepted")
|
||||||
|
}
|
||||||
|
g, err := ParseDefinition(checkStageSource("verify", "ruff check . || true", "", "pass -> #success\nfail -> #failure"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
errs, _ := Lint(g)
|
||||||
|
if len(errs) != 1 || errs[0].Rule != "commands" {
|
||||||
|
t.Fatal(errs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A delivery check stage is the landing gate: its commands are the checks the
|
||||||
|
// server runs on the committed candidate before fast-forwarding main.
|
||||||
|
func TestCheckStageAsLandingGateSatisfiesDeliveryLint(t *testing.T) {
|
||||||
|
source := lintSource(
|
||||||
|
modelStage("implement", "Make the change; the delivery gate lands it.", "read\nedit\nshell", "success -> land\nerror -> #failure", "```checks\nnone: the land gate runs the suite\n```"),
|
||||||
|
checkStageSource("land", "go test ./...", "delivery=true", "pass -> #success\nfail -> #failure"),
|
||||||
|
)
|
||||||
|
g, err := ParseDefinition(source)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if errs, _ := Lint(g); len(errs) != 0 {
|
||||||
|
t.Fatal(errs)
|
||||||
|
}
|
||||||
|
if enabled, err := stage.DeliveryEnabled(StageDefinition(g.Stages[1])); err != nil || !enabled {
|
||||||
|
t.Fatal(enabled, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -90,6 +90,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if stage.EffectiveType(s.Type) == stage.CheckType {
|
||||||
|
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
|
||||||
|
if guard := silentGuard(line); guard != "" {
|
||||||
|
add(&errs, s, "commands", "command %q can pass without running anything (%s); a missing tool must fail the check, so remove the guard", strings.TrimSpace(line), guard)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if stage.EffectiveType(s.Type) == stage.HumanType {
|
if stage.EffectiveType(s.Type) == stage.HumanType {
|
||||||
continue // a person bounds a human stage's loop
|
continue // a person bounds a human stage's loop
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user