From 61c7eee2b0fc0af99224e9adb3131791e95d114c Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 12:47:42 +0000 Subject: [PATCH 1/6] App: open a chat, the terminal or a diff in a new window "Open in new window" sits beside Float: the chat pane and chat list row menus, a floating chat window's title bar, the terminal options menu and the diff bar, plus Alt+Shift+Y for the chat with the keyboard (listed in the shortcut help). Once the window opens the item leaves the main window as Float takes a pane out of the tiling. The window is its own app instance at /window/chat/, /window/terminal?tab= or /window/diff/: only that item, named after it, with "Bring back to main window". It has its own connection and writes no shared layout (no open-chat workspace, window store or terminal layout) and posts no notifications, so they stay the main window's. Web opens a popup window (a blocked popup offers a tab); Linux and macOS start a second process with --detached (Flutter's multi-window API is still experimental); Android and iOS hide the action. The capture kit gains a follow step for windows a page opens. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/app_terminals.dart | 9 + app/lib/application/bootstrap.dart | 10 +- .../application/detached/detached_app.dart | 246 +++++++++++++++++ .../application/detached/detached_chat.dart | 153 +++++++++++ .../application/detached/detached_diff.dart | 107 ++++++++ .../detached/detached_platform.dart | 96 +++++++ .../detached/detached_platform_io.dart | 159 +++++++++++ .../detached/detached_platform_stub.dart | 41 +++ .../detached/detached_platform_web.dart | 164 ++++++++++++ .../application/detached/detached_route.dart | 108 ++++++++ .../detached/detached_terminal.dart | 92 +++++++ .../detached/detached_window_body.dart | 72 +++++ .../detached/detached_windows.dart | 193 ++++++++++++++ app/lib/application/pipelines_app.dart | 41 ++- app/lib/application/pipelines_root.dart | 20 ++ .../features/changes/domain/file_change.dart | 24 ++ .../changes/widgets/file_diff_page.dart | 34 +++ app/lib/features/chat/chat_screen_float.dart | 39 ++- .../features/chat/chat_screen_pane_menu.dart | 8 + app/lib/features/chat/screen.dart | 1 + .../chat/ui/sessions/session_actions.dart | 1 + .../chat/ui/sessions/session_pane_menu.dart | 1 + .../features/chat/windows/chat_windows.dart | 78 +++++- .../settings/keyboard_shortcuts_registry.dart | 13 + .../features/terminal/terminal_layout.dart | 5 + .../features/terminal/terminal_tab_strip.dart | 100 ++++--- app/lib/main.dart | 2 +- .../shell/detached/detached_window_scope.dart | 77 ++++++ app/linux/runner/my_application.cc | 23 +- app/notes/detached-windows.md | 75 ++++++ .../detached/detached_app_test.dart | 106 ++++++++ .../detached/detached_fixtures.dart | 180 +++++++++++++ .../detached/detached_main_window_test.dart | 89 +++++++ .../detached/detached_route_test.dart | 83 ++++++ .../detached/detached_windows_test.dart | 119 +++++++++ .../changes/diff_new_window_test.dart | 142 ++++++++++ .../features/chat/chat_new_window_test.dart | 248 ++++++++++++++++++ .../terminal/terminal_new_window_test.dart | 120 +++++++++ .../detached_window_shortcut_test.dart | 65 +++++ app/tool/capture/README.md | 1 + app/tool/capture/browser.mjs | 28 ++ app/tool/capture/capture.mjs | 11 +- .../examples/detached-chat-window.json | 24 ++ .../examples/detached-terminal-window.json | 13 + app/tool/capture/page.mjs | 15 ++ app/tool/search_selection_probe_entry.dart | 59 +++-- 46 files changed, 3223 insertions(+), 72 deletions(-) create mode 100644 app/lib/application/detached/detached_app.dart create mode 100644 app/lib/application/detached/detached_chat.dart create mode 100644 app/lib/application/detached/detached_diff.dart create mode 100644 app/lib/application/detached/detached_platform.dart create mode 100644 app/lib/application/detached/detached_platform_io.dart create mode 100644 app/lib/application/detached/detached_platform_stub.dart create mode 100644 app/lib/application/detached/detached_platform_web.dart create mode 100644 app/lib/application/detached/detached_route.dart create mode 100644 app/lib/application/detached/detached_terminal.dart create mode 100644 app/lib/application/detached/detached_window_body.dart create mode 100644 app/lib/application/detached/detached_windows.dart create mode 100644 app/lib/shell/detached/detached_window_scope.dart create mode 100644 app/notes/detached-windows.md create mode 100644 app/test/application/detached/detached_app_test.dart create mode 100644 app/test/application/detached/detached_fixtures.dart create mode 100644 app/test/application/detached/detached_main_window_test.dart create mode 100644 app/test/application/detached/detached_route_test.dart create mode 100644 app/test/application/detached/detached_windows_test.dart create mode 100644 app/test/features/changes/diff_new_window_test.dart create mode 100644 app/test/features/chat/chat_new_window_test.dart create mode 100644 app/test/features/terminal/terminal_new_window_test.dart create mode 100644 app/test/shell/detached/detached_window_shortcut_test.dart create mode 100644 app/tool/capture/examples/detached-chat-window.json create mode 100644 app/tool/capture/examples/detached-terminal-window.json diff --git a/app/lib/application/app_terminals.dart b/app/lib/application/app_terminals.dart index 81c3aed3..214b89a6 100644 --- a/app/lib/application/app_terminals.dart +++ b/app/lib/application/app_terminals.dart @@ -75,6 +75,15 @@ class AppTerminals { Widget? barToggle(BuildContext context) => 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() { floating?.dispose(); hub.dispose(); diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart index 7e03bd51..a66aa712 100644 --- a/app/lib/application/bootstrap.dart +++ b/app/lib/application/bootstrap.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'app_url_strategy.dart'; +import 'detached/detached_platform.dart'; import 'pipelines_binding.dart'; import 'pipelines_root.dart'; import 'server_endpoint.dart'; @@ -49,13 +50,19 @@ Future resolveLaunchServer({ /// system font. 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 runPipelinesApp({ Uri? base, String configured = configuredServerUrl, SettingsStore? settingsStore, + List args = const [], }) async { 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(); registerAppFontLicenses(); // The device's chosen font loads beside the session; a slow download does @@ -83,6 +90,7 @@ Future runPipelinesApp({ server: server, buildDefault: configured, signedIn: kIsWeb || ServerSession.cookie != null, + detached: detached, ), ); } diff --git a/app/lib/application/detached/detached_app.dart b/app/lib/application/detached/detached_app.dart new file mode 100644 index 00000000..0d572450 --- /dev/null +++ b/app/lib/application/detached/detached_app.dart @@ -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? serverAddresses; + final DetachedPlatform? platform; + final bool web; + + @override + State createState() => _DetachedWindowAppState(); +} + +class _DetachedWindowAppState extends State { + late final AppSession _session; + late final DetachedPlatform _platform = + widget.platform ?? DetachedPlatform.instance; + final _title = ValueNotifier(''); + final _ready = ValueNotifier(false); + final _sync = ValueNotifier(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 _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 _page() => MaterialPageRoute( + 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); +} diff --git a/app/lib/application/detached/detached_chat.dart b/app/lib/application/detached/detached_chat.dart new file mode 100644 index 00000000..2bc3dfaa --- /dev/null +++ b/app/lib/application/detached/detached_chat.dart @@ -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 createState() => _DetachedChatState(); +} + +class _DetachedChatState extends State { + // 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, + ), + ], + ), + ); + }, + ); +} diff --git a/app/lib/application/detached/detached_diff.dart b/app/lib/application/detached/detached_diff.dart new file mode 100644 index 00000000..45f7fcf7 --- /dev/null +++ b/app/lib/application/detached/detached_diff.dart @@ -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 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 createState() => _DetachedDiffState(); +} + +class _DetachedDiffState extends State { + late final Future _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( + 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, + ), + ), + ], + ); + }, + ); +} diff --git a/app/lib/application/detached/detached_platform.dart b/app/lib/application/detached/detached_platform.dart new file mode 100644 index 00000000..496ae568 --- /dev/null +++ b/app/lib/application/detached/detached_platform.dart @@ -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; + +/// 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 `, +/// 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 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 launch( + DetachedRoute route, { + required String title, + required Size size, + bool tab = false, + }); + + /// Messages the detached windows send to this (main) window. + Stream get messages; + + /// Keeps [json] for the window that will ask for [token]. + Future put(String token, String json); + + /// The data kept under [token], for this window; null when there is none. + Future take(String token); + + /// Sends [message] to the main window that opened this one; false when + /// there is none to receive it. + Future sendToMain(DetachedMessage message); + + /// Closes this detached window. + Future closeSelf(); + + /// Opens the full app (the main window) at [appPath], in place of this + /// detached window; false when this platform cannot. + Future becomeMain(String appPath); +} + +/// The detached window this launch opens, or null for the main window: the +/// browser location on the web, `--detached ` (or the environment) on +/// a desktop. +DetachedRoute? detachedLaunchRoute(List 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.from(value)..remove('marker'); + } on FormatException { + return null; + } +} diff --git a/app/lib/application/detached/detached_platform_io.dart b/app/lib/application/detached/detached_platform_io.dart new file mode 100644 index 00000000..75f7bf44 --- /dev/null +++ b/app/lib/application/detached/detached_platform_io.dart @@ -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 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 `; `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 _children = {}; + final _messages = StreamController.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 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 get messages => _messages.stream; + + File _file(String token) => + File('${Directory.systemTemp.path}/pipelines-detached-$token.json'); + + @override + Future put(String token, String json) async { + try { + await _file(token).writeAsString(json, flush: true); + } catch (_) { + // The window says the diff is gone. + } + } + + @override + Future 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 _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 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 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 becomeMain(String appPath) async { + try { + await Process.start( + Platform.resolvedExecutable, + const [], + environment: {DetachedRoute.environment: '', parentVariable: ''}, + mode: ProcessStartMode.detached, + ); + } catch (_) { + return false; + } + exit(0); + } +} diff --git a/app/lib/application/detached/detached_platform_stub.dart b/app/lib/application/detached/detached_platform_stub.dart new file mode 100644 index 00000000..4b69392a --- /dev/null +++ b/app/lib/application/detached/detached_platform_stub.dart @@ -0,0 +1,41 @@ +import 'dart:ui'; + +import 'detached_platform.dart'; +import 'detached_route.dart'; + +DetachedPlatform createDetachedPlatform() => UnsupportedDetachedPlatform(); + +DetachedRoute? launchedDetachedRoute(List 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 launch( + DetachedRoute route, { + required String title, + required Size size, + bool tab = false, + }) async => DetachedLaunch.failed; + + @override + Stream get messages => const Stream.empty(); + + @override + Future put(String token, String json) async {} + + @override + Future take(String token) async => null; + + @override + Future sendToMain(DetachedMessage message) async => false; + + @override + Future closeSelf() async {} + + @override + Future becomeMain(String appPath) async => false; +} diff --git a/app/lib/application/detached/detached_platform_web.dart b/app/lib/application/detached/detached_platform_web.dart new file mode 100644 index 00000000..6b0fd169 --- /dev/null +++ b/app/lib/application/detached/detached_platform_web.dart @@ -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 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 _opened = {}; + StreamController? _messages; + JSFunction? _listener; + + @override + bool get supported => true; + + @override + Future 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 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()) 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 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 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 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 closeSelf() async => web.window.close(); + + @override + Future 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()); + } +} diff --git a/app/lib/application/detached/detached_route.dart b/app/lib/application/detached/detached_route.dart new file mode 100644 index 00000000..7b233983 --- /dev/null +++ b/app/lib/application/detached/detached_route.dart @@ -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 ` (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 ` (or + /// `--detached=`) in [args], else [env]'s `PIPELINES_DETACHED`. + static DetachedRoute? fromLaunch( + List args, [ + Map 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 _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; +} diff --git a/app/lib/application/detached/detached_terminal.dart b/app/lib/application/detached/detached_terminal.dart new file mode 100644 index 00000000..9ddbe960 --- /dev/null +++ b/app/lib/application/detached/detached_terminal.dart @@ -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 createState() => _DetachedTerminalState(); +} + +class _DetachedTerminalState extends State { + 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)), + ], + ), + ), + ), + ); +} diff --git a/app/lib/application/detached/detached_window_body.dart b/app/lib/application/detached/detached_window_body.dart new file mode 100644 index 00000000..9b144aaf --- /dev/null +++ b/app/lib/application/detached/detached_window_body.dart @@ -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 ready; + + /// Advances when the connection is replaced; open views re-subscribe. + final ValueListenable sync; + + /// Names the window after the item (the browser or desktop title). + final ValueChanged 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> files, + int initialIndex, + ) + bringBackItem; + + void bringBack( + DetachedKind kind, + String id, { + List> 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), + ); +} diff --git a/app/lib/application/detached/detached_windows.dart b/app/lib/application/detached/detached_windows.dart new file mode 100644 index 00000000..ec5a90cf --- /dev/null +++ b/app/lib/application/detached/detached_windows.dart @@ -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> 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.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? 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 _messenger; + StreamSubscription? _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> 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 _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 _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('=', ''); +} diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 34e4f87f..bfdf0b82 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -57,7 +57,12 @@ import 'app_terminals.dart'; import '../features/chat/chat_run_opener.dart'; import '../features/chat/chat_runtime.dart'; import '../features/chat/data/chat_recency.dart'; +import '../features/changes/domain/file_change.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 'open_in_chat.dart'; import 'send_to_chat.dart'; @@ -119,10 +124,14 @@ class PipelinesApp extends StatefulWidget { this.tabLocationsStore, this.terminalLayout, this.windows, + this.detachedPlatform, }); 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. final TerminalLayout? terminalLayout; @@ -330,6 +339,7 @@ class _PipelinesAppState extends State late final DiffWindows _diffWindows; late final ChatRuntime _chatRuntime; late final ChatWindows _chatWindows; + late final DetachedWindows _detached; @override void initState() { @@ -391,6 +401,11 @@ class _PipelinesAppState extends State windows: _windows, ); _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 // terminal may open its window, and the floating chats an older build // saved are brought over once. @@ -656,6 +671,7 @@ class _PipelinesAppState extends State _session.removeListener(_chatSyncChanged); _session.removeListener(_learnServerHostname); widget.chatPool?.removeListener(_chatSyncChanged); + _detached.dispose(); _chatWindows.dispose(); _diffWindows.dispose(); _chatRuntime.dispose(); @@ -747,9 +763,12 @@ class _PipelinesAppState extends State @override Widget build(BuildContext context) { // A chat's run card (show_run) opens the run's detail. + final router = MyApp.router(routerConfig: _config); final app = ChatRunOpener( openRun: _openRunFromChat, - child: MyApp.router(routerConfig: _config), + child: _detached.supported + ? DetachedWindowScope(opener: _detached, child: router) + : router, ); return widget.servers == null ? app @@ -762,6 +781,26 @@ class _PipelinesAppState extends State 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 /// hit navigates nowhere: the screen already presents it read-only rather than /// guessing a destination. diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index 8b54dffa..43c3cea4 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -18,6 +18,8 @@ import '../features/settings/settings_store.dart'; import '../ui/scale/ui_scale.dart'; import '../ui/theme/app_font_controller.dart'; import '../ui/theme/app_theme.dart'; +import 'detached/detached_app.dart'; +import 'detached/detached_route.dart'; import 'pipelines_app.dart'; import 'server_endpoint.dart'; @@ -38,8 +40,12 @@ class PipelinesRoot extends StatefulWidget { this.nativeUpdatesSupported, this.federatedChats = true, this.chatPoolFactory, + this.detached, }); + /// The detached window this launch shows instead of the whole app. + final DetachedRoute? detached; + final ServerEndpoint server; /// The server this build was made for; it pre-fills onboarding. @@ -321,6 +327,20 @@ class _PipelinesRootState extends State { ), ); } + 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) { return PipelinesApp( androidSupported: widget.nativeUpdatesSupported, diff --git a/app/lib/features/changes/domain/file_change.dart b/app/lib/features/changes/domain/file_change.dart index 6068d6f2..dc1bc9c0 100644 --- a/app/lib/features/changes/domain/file_change.dart +++ b/app/lib/features/changes/domain/file_change.dart @@ -82,6 +82,30 @@ class FileChange { 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 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 /// capture owns the decision to skip such an entry, so it is never rendered /// as an anonymous row. diff --git a/app/lib/features/changes/widgets/file_diff_page.dart b/app/lib/features/changes/widgets/file_diff_page.dart index 855cf93f..b27d43a6 100644 --- a/app/lib/features/changes/widgets/file_diff_page.dart +++ b/app/lib/features/changes/widgets/file_diff_page.dart @@ -14,6 +14,8 @@ import 'diff_search_bar.dart'; import 'diff_search_controller.dart'; import 'file_diff_viewer.dart'; import 'stacked_diff_view.dart'; +import '../../../shell/detached/detached_window_scope.dart'; +import '../../../shell/windows/window_scope.dart'; import '../windows/diff_windows.dart'; /// Whether diff pages show every file stacked (GitHub's Files changed) rather @@ -54,6 +56,7 @@ class FileDiffPage extends StatefulWidget { required this.files, this.initialIndex = 0, this.inWindow = false, + this.actions = const [], }); final List files; @@ -62,6 +65,10 @@ class FileDiffPage extends StatefulWidget { /// Shown inside a floating window: no Back, and no Open in a window. final bool inWindow; + /// The host's own bar buttons, after the diff's (a detached window's + /// Bring back). + final List actions; + @override State createState() => _FileDiffPageState(); } @@ -184,6 +191,25 @@ class _FileDiffPageState extends State { 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(() { if (!_collapsed.remove(index)) _collapsed.add(index); }); @@ -288,6 +314,13 @@ class _FileDiffPageState extends State { ), 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( key: const ValueKey('diff-search-open'), tooltip: 'Find in diff (/)', @@ -315,6 +348,7 @@ class _FileDiffPageState extends State { _all ? Icons.article_outlined : Icons.view_agenda_outlined, ), ), + ...widget.actions, ], ), body: body, diff --git a/app/lib/features/chat/chat_screen_float.dart b/app/lib/features/chat/chat_screen_float.dart index 56e9638b..afc224e3 100644 --- a/app/lib/features/chat/chat_screen_float.dart +++ b/app/lib/features/chat/chat_screen_float.dart @@ -25,6 +25,8 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { final pane = _workspace.activePane; if (pane != null) _floatPane(pane.id); }, + release: _releaseSession, + activeSession: () => _workspace.activePane?.sessionId, ); } @@ -66,6 +68,19 @@ mixin _ChatScreenFloat on State, _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) { if (!mounted) return; _workspaceVisible = true; @@ -75,15 +90,25 @@ mixin _ChatScreenFloat on State, _ChatScreenWorkspace { _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 _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 [ - ChatBarAction( - label: 'Float (${chatFloatShortcutLabel()})', - onPressed: () => _floatPane(pane.id), - materialIcon: Icons.picture_in_picture_alt_outlined, - ), + if (_floatsHere) + ChatBarAction( + label: 'Float (${chatFloatShortcutLabel()})', + 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, + ), ]; } } diff --git a/app/lib/features/chat/chat_screen_pane_menu.dart b/app/lib/features/chat/chat_screen_pane_menu.dart index b7e2b909..9ab42fff 100644 --- a/app/lib/features/chat/chat_screen_pane_menu.dart +++ b/app/lib/features/chat/chat_screen_pane_menu.dart @@ -43,6 +43,12 @@ mixin _ChatScreenPaneMenu on State, _ChatScreenWorkspace final moves = pane == null ? null : _paneMoveTargets[pane.id]; final directory = '${session['directory'] ?? ''}'.trim(); return [ + if (widget.windows?.detached != null) + ( + action: SessionPaneAction.newWindow, + label: detachedChatWindowLabel(), + enabled: true, + ), ( action: SessionPaneAction.addPane, label: 'Add chat pane', @@ -97,6 +103,8 @@ mixin _ChatScreenPaneMenu on State, _ChatScreenWorkspace final id = '${session['id'] ?? ''}'; if (id.isEmpty) return; switch (action) { + case SessionPaneAction.newWindow: + widget.windows?.detach(id); case SessionPaneAction.addPane: _openBySelection(session); _addPane(context); diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 694632ee..ce9df7e3 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -22,6 +22,7 @@ import 'package:flutter/services.dart'; import '../../core/api_gateway.dart'; import '../../core/servers/server_context.dart'; import '../../core/servers/server_scope.dart'; +import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_scope.dart'; import 'shell/chat_shell_dismiss.dart'; import '../terminal/terminal_open_action.dart'; diff --git a/app/lib/features/chat/ui/sessions/session_actions.dart b/app/lib/features/chat/ui/sessions/session_actions.dart index eda03201..e7136ab1 100644 --- a/app/lib/features/chat/ui/sessions/session_actions.dart +++ b/app/lib/features/chat/ui/sessions/session_actions.dart @@ -105,6 +105,7 @@ class SessionActionsButton extends StatelessWidget { } IconData _paneIcon(SessionPaneAction action) => switch (action) { + SessionPaneAction.newWindow => Icons.open_in_browser, SessionPaneAction.addPane => Icons.add_box_outlined, SessionPaneAction.openChats => Icons.view_quilt_outlined, SessionPaneAction.centerStage => Icons.center_focus_strong_outlined, diff --git a/app/lib/features/chat/ui/sessions/session_pane_menu.dart b/app/lib/features/chat/ui/sessions/session_pane_menu.dart index 9fa78e42..685628f7 100644 --- a/app/lib/features/chat/ui/sessions/session_pane_menu.dart +++ b/app/lib/features/chat/ui/sessions/session_pane_menu.dart @@ -4,6 +4,7 @@ import '../../../../core/api_gateway.dart'; /// The pane More menu's choices that a chat row's menu also offers. enum SessionPaneAction { + newWindow, addPane, openChats, centerStage, diff --git a/app/lib/features/chat/windows/chat_windows.dart b/app/lib/features/chat/windows/chat_windows.dart index 14f68a5e..8f23392b 100644 --- a/app/lib/features/chat/windows/chat_windows.dart +++ b/app/lib/features/chat/windows/chat_windows.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; +import '../../../shell/detached/detached_window_scope.dart'; import '../../../shell/list_detail_policy.dart'; import '../../../shell/windows/window_entry.dart'; import '../../../shell/windows/window_kind.dart'; @@ -25,6 +26,8 @@ class ChatTiling { required this.dock, required this.canFloatActive, required this.floatActive, + this.release, + this.activeSession, }); /// Whether the tiling shows [sessionId]. @@ -36,6 +39,13 @@ class ChatTiling { /// Whether the chord can float the active pane now. final bool Function() canFloatActive; final VoidCallback floatActive; + + /// Takes [sessionId]'s panes out of the tiling (it went to a window of + /// its own). + final void Function(String sessionId)? release; + + /// The active pane's chat. + final String? Function()? activeSession; } /// The floating chat windows, for the app's lifetime: the `chat` window kind @@ -66,6 +76,10 @@ class ChatWindows { /// The mounted Chat destination's tiling, if it is built. ChatTiling? tiling; + /// Opens a chat in a window of its own (a browser window or app process); + /// null where the platform has none. + DetachedWindowOpener? detached; + late final ChatWindowKind kind = ChatWindowKind(this); bool _started = false; @@ -86,7 +100,8 @@ class ChatWindows { manager.kinds.register(kind); FocusManager.instance ..addEarlyKeyEventHandler(_key) - ..addEarlyKeyEventHandler(_tabKey); + ..addEarlyKeyEventHandler(_tabKey) + ..addEarlyKeyEventHandler(_detachKey); runtime.addSessionReplacedListener(_replacedElsewhere); runtime.sessions.addListener(_rowsChanged); manager.addListener(_rowsChanged); @@ -98,7 +113,8 @@ class ChatWindows { _started = false; FocusManager.instance ..removeEarlyKeyEventHandler(_key) - ..removeEarlyKeyEventHandler(_tabKey); + ..removeEarlyKeyEventHandler(_tabKey) + ..removeEarlyKeyEventHandler(_detachKey); runtime.removeSessionReplacedListener(_replacedElsewhere); runtime.sessions.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 /// that session is already open elsewhere. void startedNewSession( @@ -242,6 +287,29 @@ class ChatWindows { return KeyEventResult.handled; } + /// Alt+Shift+Y sends the chat with the keyboard (a floating window's, else + /// the active tiled pane's) to a new window. Left alone when there is no + /// such chat or no platform window. + KeyEventResult _detachKey(KeyEvent event) { + if (detached == null || + !detachedWindowShortcut(event, HardwareKeyboard.instance)) { + return KeyEventResult.ignored; + } + final scope = keyboardWindow(); + String? id; + if (scope != null) { + if (scope.entry.kind == chatWindowKind) id = scope.entry.contentId; + } else { + final tiling = this.tiling; + if (tiling != null && tiling.canFloatActive()) { + id = tiling.activeSession?.call(); + } + } + if (id == null || id.isEmpty) return KeyEventResult.ignored; + if (event is KeyDownEvent) detach(id); + return KeyEventResult.handled; + } + /// Ctrl+Tab and Ctrl+Shift+Tab while a floating chat window holds the /// keyboard: the next (previous) shown chat window, in open order and /// wrapping, comes to the top. The window host then gives it the keyboard, @@ -350,6 +418,12 @@ class ChatWindowKind extends WindowKind { icon: Icons.vertical_split_outlined, onPressed: () => windows.dock(entry), ), + if (windows.detached != null) + WindowAction( + label: detachedChatWindowLabel(), + icon: Icons.open_in_browser, + onPressed: () => windows.detach(entry.contentId), + ), ]; @override diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index f3914a76..592b7c7c 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart'; import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../terminal/terminal_shortcuts.dart'; +import '../../shell/detached/detached_window_scope.dart'; import '../../shell/windows/window_shortcuts.dart'; import '../../shell/shell_chat_actions_shortcut.dart'; import '../../shell/shell_chat_shortcut.dart'; @@ -221,6 +222,18 @@ class KeyboardShortcutRegistry { action: 'Cycle floating windows', 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. diff --git a/app/lib/features/terminal/terminal_layout.dart b/app/lib/features/terminal/terminal_layout.dart index 656b7b19..69ffb663 100644 --- a/app/lib/features/terminal/terminal_layout.dart +++ b/app/lib/features/terminal/terminal_layout.dart @@ -132,6 +132,10 @@ class TerminalLayout extends ChangeNotifier { /// Whether the last change could not be saved. 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 restore() async { final revision = _revision; final raw = await _store.load(); @@ -196,6 +200,7 @@ class TerminalLayout extends ChangeNotifier { /// Saves the current layout (a drag saves once, when it ends). Future save() async { + if (!persist) return; final revision = _revision; final saved = await _store.save( jsonEncode({ diff --git a/app/lib/features/terminal/terminal_tab_strip.dart b/app/lib/features/terminal/terminal_tab_strip.dart index 7f8f3078..c01f0787 100644 --- a/app/lib/features/terminal/terminal_tab_strip.dart +++ b/app/lib/features/terminal/terminal_tab_strip.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import '../../shell/detached/detached_window_scope.dart'; import 'terminal_browser_keys.dart'; import 'terminal_hub.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 - /// that can) and Hide terminal, with the shortcuts under them. - Widget _options(BuildContext context) => TerminalMenuButton<_Option>( - label: 'Terminal options', - info: TerminalShortcutLabels.current().summary, - icon: Icons.more_vert, - choices: [ - for (final mode in TerminalMode.values) - TerminalChoice( - _Option(mode), - mode.label, - checked: layout.mode == mode, - key: ValueKey('terminal-mode-${mode.name}'), + /// The options menu: the modes, Open in new window (where the platform + /// has windows), the browser keys capture (on a browser that can) and + /// Hide terminal, with the shortcuts under them. + Widget _options(BuildContext context) { + final opener = DetachedWindowScope.maybeOf(context); + return TerminalMenuButton<_Option>( + label: 'Terminal options', + info: TerminalShortcutLabels.current().summary, + icon: Icons.more_vert, + choices: [ + for (final mode in TerminalMode.values) + TerminalChoice( + _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( - 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'), - ), - ], - onSelected: (option) { - if (option.browserKeys) { - unawaited(toggleTerminalBrowserKeys(context, browserKeys)); - } else if (option.mode == null) { - layout.hide(); - } else { - layout.setMode(option.mode!); - } - }, - ); + ], + onSelected: (option) { + if (option.newWindow) { + _openInNewWindow(opener!); + } else if (option.browserKeys) { + unawaited(toggleTerminalBrowserKeys(context, browserKeys)); + } else if (option.mode == null) { + layout.hide(); + } else { + layout.setMode(option.mode!); + } + }, + ); + } + + /// The terminal moves to a window of its own, on the selected tab; this + /// one hides it once that window is open. The terminals keep running on + /// the machines, so both windows reach the same shells. + void _openInNewWindow(DetachedWindowOpener opener) { + final tab = hub.selected; + opener.openTerminal( + tabKey: tab?.key ?? '', + title: tab == null ? 'Terminal' : 'Terminal: ${tab.title}', + onOpened: layout.hide, + ); + } String _label(TerminalTab tab) => 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 /// capture. class _Option { - const _Option(this.mode, {this.browserKeys = false}); + const _Option(this.mode, {this.browserKeys = false, this.newWindow = false}); final TerminalMode? mode; final bool browserKeys; + final bool newWindow; } diff --git a/app/lib/main.dart b/app/lib/main.dart index ef65859c..23c2a83a 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -4,4 +4,4 @@ export 'application/app.dart' show MyApp; export 'shell/adaptive_shell.dart'; export 'shell/destination.dart'; -void main() => runPipelinesApp(); +void main(List args) => runPipelinesApp(args: args); diff --git a/app/lib/shell/detached/detached_window_scope.dart b/app/lib/shell/detached/detached_window_scope.dart new file mode 100644 index 00000000..1ba70b5b --- /dev/null +++ b/app/lib/shell/detached/detached_window_scope.dart @@ -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> 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()?.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()})'; diff --git a/app/linux/runner/my_application.cc b/app/linux/runner/my_application.cc index 3e1ed334..cb898c4e 100644 --- a/app/linux/runner/my_application.cc +++ b/app/linux/runner/my_application.cc @@ -1,6 +1,7 @@ #include "my_application.h" #include +#include #ifdef GDK_WINDOWING_X11 #include #endif @@ -25,6 +26,13 @@ static void my_application_activate(GApplication* application) { GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + // A detached window (a chat, the terminal or a diff sent to a window of + // its own) is named after its item and sized for it by the main process. + const gchar* detached_title = g_getenv("PIPELINES_WINDOW_TITLE"); + const gchar* title = detached_title != nullptr && detached_title[0] != '\0' + ? detached_title + : "Pipelines"; + // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). @@ -45,14 +53,23 @@ static void my_application_activate(GApplication* application) { if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 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_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { - gtk_window_set_title(window, "Pipelines"); + gtk_window_set_title(window, title); } - 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(); fl_dart_project_set_dart_entrypoint_arguments( diff --git a/app/notes/detached-windows.md b/app/notes/detached-windows.md new file mode 100644 index 00000000..4a9e94d2 --- /dev/null +++ b/app/notes/detached-windows.md @@ -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/`, `/window/terminal?tab=` + or `/window/diff/` (`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 ` + and `PIPELINES_DETACHED=` (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=` 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). diff --git a/app/test/application/detached/detached_app_test.dart b/app/test/application/detached/detached_app_test.dart new file mode 100644 index 00000000..be5d77b1 --- /dev/null +++ b/app/test/application/detached/detached_app_test.dart @@ -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 _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 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(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'); + }); +} diff --git a/app/test/application/detached/detached_fixtures.dart b/app/test/application/detached/detached_fixtures.dart new file mode 100644 index 00000000..ae35ac26 --- /dev/null +++ b/app/test/application/detached/detached_fixtures.dart @@ -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 = {}; + final sent = []; + bool mainOpen = true; + bool closed = false; + String? becameMain; + final incoming = StreamController.broadcast(); + + @override + bool get supported => true; + + @override + Future 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 get messages => incoming.stream; + + @override + Future put(String token, String json) async => stored[token] = json; + + @override + Future take(String token) async => stored[token]; + + @override + Future sendToMain(DetachedMessage message) async { + if (!mainOpen) return false; + sent.add(message); + return true; + } + + @override + Future closeSelf() async => closed = true; + + @override + Future 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 = []; + final terminals = []; + final diffs = >>[]; + 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> 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 openChats = const []}) + : _entries = openChats; + + final FakeChannel channel; + final _answered = {}; + final requests = >[]; + List _entries; + int _revision = 1; + + /// The open-chat writes the app sent (`chat_open_workspace_request`). + List> 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; + final id = m['id']; + if (id == null || !_answered.add(id)) continue; + requests.add(m); + channel.incoming.add(jsonEncode(_reply('${m['type']}', id, m))); + } + } + + Map _reply(String type, Object? id, Map 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; + } + return { + 'id': id, + 'type': type, + 'chat_open_workspace': {'revision': _revision, 'entries': _entries}, + }; + default: + return {'id': id, 'type': type}; + } + } +} diff --git a/app/test/application/detached/detached_main_window_test.dart b/app/test/application/detached/detached_main_window_test.dart new file mode 100644 index 00000000..12f6dcdc --- /dev/null +++ b/app/test/application/detached/detached_main_window_test.dart @@ -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 _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(find.byType(ChatThreadView)); + expect(thread.sessionId, 'b'); + }); +} diff --git a/app/test/application/detached/detached_route_test.dart b/app/test/application/detached/detached_route_test.dart new file mode 100644 index 00000000..94cfb166 --- /dev/null +++ b/app/test/application/detached/detached_route_test.dart @@ -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); + }); +} diff --git a/app/test/application/detached/detached_windows_test.dart b/app/test/application/detached/detached_windows_test.dart new file mode 100644 index 00000000..c2d09aca --- /dev/null +++ b/app/test/application/detached/detached_windows_test.dart @@ -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 returned; + late GlobalKey messenger; + late DetachedWindows windows; + + setUp(() { + platform = FakeDetachedPlatform(); + returned = []; + messenger = GlobalKey(); + windows = DetachedWindows( + platform: platform, + onReturn: returned.add, + messenger: messenger, + )..start(); + }); + tearDown(() => windows.dispose()); + + Future 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'); + }); +} diff --git a/app/test/features/changes/diff_new_window_test.dart b/app/test/features/changes/diff_new_window_test.dart new file mode 100644 index 00000000..e000151f --- /dev/null +++ b/app/test/features/changes/diff_new_window_test.dart @@ -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 = []; + 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); + }); +} diff --git a/app/test/features/chat/chat_new_window_test.dart b/app/test/features/chat/chat_new_window_test.dart new file mode 100644 index 00000000..882c5d7a --- /dev/null +++ b/app/test/features/chat/chat_new_window_test.dart @@ -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 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 _tiled(WidgetTester tester) => [ + for (final pane + in tester + .widget( + 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 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 get floating => [for (final w in windows.windows) w.contentId]; +} + +Future _paneMenu(WidgetTester tester, String session) async { + await tester.tap( + find + .descendant( + of: _thread(session), + matching: find.byTooltip('More actions'), + ) + .hitTestable(), + ); + await tester.pumpAndSettle(); +} + +Future _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']); + }); +} diff --git a/app/test/features/terminal/terminal_new_window_test.dart b/app/test/features/terminal/terminal_new_window_test.dart new file mode 100644 index 00000000..1f1bfdb6 --- /dev/null +++ b/app/test/features/terminal/terminal_new_window_test.dart @@ -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 = []; + 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()); + }); +} diff --git a/app/test/shell/detached/detached_window_shortcut_test.dart b/app/test/shell/detached/detached_window_shortcut_test.dart new file mode 100644 index 00000000..35122c09 --- /dev/null +++ b/app/test/shell/detached/detached_window_shortcut_test.dart @@ -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 chord(List 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); + }); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index b7760430..5e98e76e 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -88,6 +88,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | | `pinch=>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 | +| `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=` | evaluate an expression in the page and log/record its value | | `expect=` | fail the run (status 1) unless the expression is truthy; JSON `name` labels the check | diff --git a/app/tool/capture/browser.mjs b/app/tool/capture/browser.mjs index 9e96c8eb..a4916db4 100644 --- a/app/tool/capture/browser.mjs +++ b/app/tool/capture/browser.mjs @@ -88,6 +88,7 @@ export async function openBrowser({ cdp, gpu = false, args = [], chromePath = pr ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) })); }); let targetId; + let main; try { ({ targetId } = await raw('Target.createTarget', { url: 'about:blank' })); ({ 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). */ 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 () => { await raw('Target.closeTarget', { targetId }).catch(() => {}); ws.close(); diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index f13affec..c280a9e5 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -28,7 +28,7 @@ options: --script --size WxH (880x1000) steps: open=[@WxH] wait= shot= click= waitfor= type= press= scroll= size=WxH files=[,] (answers the next file chooser) - film= labels= tabs= eval= expect= hover= + film= labels= tabs= follow= eval= expect= hover= keys= grant=clipboard clipboard=read|write: (the browser's clipboard, from a scratch page on the loopback origin, so it works for an --insecure page) @@ -246,6 +246,15 @@ try { break; } case 'tabs': await save(file(value || 'tabs', 'json'), JSON.stringify(await browser.targets(), null, 2)); break; + case 'follow': { + // follow=: 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 'film': { const what = String(value).startsWith('press:') ? String(value) : describe(parseTarget(value)); diff --git a/app/tool/capture/examples/detached-chat-window.json b/app/tool/capture/examples/detached-chat-window.json new file mode 100644 index 00000000..9ec92843 --- /dev/null +++ b/app/tool/capture/examples/detached-chat-window.json @@ -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" } + ] } diff --git a/app/tool/capture/examples/detached-terminal-window.json b/app/tool/capture/examples/detached-terminal-window.json new file mode 100644 index 00000000..b66183d0 --- /dev/null +++ b/app/tool/capture/examples/detached-terminal-window.json @@ -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" } + ] } diff --git a/app/tool/capture/page.mjs b/app/tool/capture/page.mjs index 54f65873..d20e058b 100644 --- a/app/tool/capture/page.mjs +++ b/app/tool/capture/page.mjs @@ -125,6 +125,21 @@ export function flutterPage(browser, log, { touch = false, semantics = true, use if (touch) await enableTouch(send, viewport); 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) { const point = await locate(target, timeout); await tap(point); diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 0b3add4b..f2a82fd0 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -28,6 +28,9 @@ import 'dart:convert'; import 'package:pipelines_app/application/app_url_strategy.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/core/api_gateway.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; @@ -1079,25 +1082,43 @@ Future main() async { }, ) : null; - final app = PipelinesApp( - 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), - ); + // A detached window (`/window/chat/`, opened by Open in new window) + // runs on the same fixture: its URL carries this page's parameters. + DetachedPlatform.extraQuery = () => { + for (final entry in params.entries) + if (entry.key != 'route' && entry.key != 'q') entry.key: entry.value, + }; + final detached = kIsWeb ? DetachedRoute.parse(Uri.base.toString()) : null; + final app = detached != null + ? DetachedWindowApp( + route: detached, + server: fixtureServer(params), + serverId: machines?.catalog.active?.id, + servers: machines, + chatPool: pool, + client: PipelinesClient(channelFactory: (_) => _FixtureChannel()), + ) + : PipelinesApp( + 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']) { 'dark' => Brightness.dark, 'light' => Brightness.light, From 87016ef5dceac8244cc73da7855f948730456d0e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 12:52:16 +0000 Subject: [PATCH 2/6] Engine: check stages, harness-agnostic delivery, read-only enforcement, complete captures - New `type=check` stage: the server runs a `commands` block (sh -c, per command_timeout, workspace env) and routes on pass/fail; per-command status, exit code, duration and bounded output are recorded and the failing output is the handoff. With delivery=true it is the landing gate (commit leftovers, merge moved main, checks in a fresh candidate worktree, fast-forward main). Parser/registry, lint (silent guards), format docs, CLI inspect, app graph and run detail rendering. - delivery=true is accepted on every harness (and on check stages). - permissions.shell on claude stages maps to Bash(cmd) / Bash(prefix:*) rules instead of a bare Bash allow; stages without edit that change the workspace fail the visit with the changed files listed (allow_workspace_changes=true opts out; artifacts, public and harness state dirs are ignored). - File-change capture: symlinks compared by target, untouched protected files no longer make captures partial, untracked caches/dependency/build output left out, lockfiles listed without patch, huge files compared by metadata, raised patch/line limits. Outcome repair follow-ups are logged and counted on the step (control.outcome_repairs). Co-Authored-By: Claude Opus 5.5 --- .../changes/domain/change_wording.dart | 11 +- .../features/changes/domain/file_change.dart | 6 +- .../features/graph/domain/check_stage.dart | 45 ++ .../graph/domain/graph_definition.dart | 29 +- .../graph/domain/stage_definition.dart | 37 +- .../graph/widgets/graph_stage_node.dart | 42 +- .../graph/widgets/run_graph_canvas.dart | 2 +- .../graph/widgets/stage_definition_view.dart | 16 +- .../runs/domain/check_step_output.dart | 133 ++++++ .../runs/ui/run_check_output_view.dart | 136 ++++++ .../runs/ui/run_detail_visit_facts.dart | 16 + .../runs/ui/run_detail_visit_facts_view.dart | 26 +- .../runs/ui/run_detail_visit_sections.dart | 13 +- .../ui/run_detail_visit_session_state.dart | 6 + .../changes/no_patch_reason_test.dart | 11 +- .../graph/domain/check_stage_test.dart | 80 ++++ .../widgets/check_stage_render_test.dart | 81 ++++ .../runs/domain/check_step_output_test.dart | 77 ++++ .../runs/ui/run_check_visit_test.dart | 141 ++++++ docs/stage-file-diffs.md | 39 +- internal/author/skill/SKILL.md | 7 +- internal/author/skill/references/delivery.md | 6 +- internal/author/skill/references/format.md | 87 +++- internal/cli/agent_mode_test.go | 19 + internal/cli/inspect.go | 14 + internal/filediff/policy.go | 117 +++++ internal/filediff/policy_test.go | 73 ++++ internal/filediff/snapshot.go | 142 +++++- internal/filediff/snapshot_test.go | 31 +- internal/pipeline/check_stage_test.go | 89 ++++ internal/pipeline/lint.go | 7 + internal/protocol/runs.go | 11 +- internal/server/check_stage.go | 139 ++++++ internal/server/check_stage_test.go | 205 +++++++++ internal/server/delivery_gate.go | 25 +- internal/server/retry_test.go | 7 +- internal/server/runner.go | 36 +- internal/stage/check.go | 413 ++++++++++++++++++ internal/stage/check_test.go | 159 +++++++ internal/stage/claude_stage.go | 36 +- internal/stage/claude_stage_test.go | 86 +++- internal/stage/model.go | 12 +- internal/stage/model_repair.go | 32 +- internal/stage/permissions.go | 54 ++- internal/stage/stage.go | 7 +- internal/stage/tools.go | 13 +- internal/stage/tools_test.go | 29 +- 47 files changed, 2674 insertions(+), 129 deletions(-) create mode 100644 app/lib/features/graph/domain/check_stage.dart create mode 100644 app/lib/features/runs/domain/check_step_output.dart create mode 100644 app/lib/features/runs/ui/run_check_output_view.dart create mode 100644 app/test/features/graph/domain/check_stage_test.dart create mode 100644 app/test/features/graph/widgets/check_stage_render_test.dart create mode 100644 app/test/features/runs/domain/check_step_output_test.dart create mode 100644 app/test/features/runs/ui/run_check_visit_test.dart create mode 100644 internal/filediff/policy.go create mode 100644 internal/filediff/policy_test.go create mode 100644 internal/pipeline/check_stage_test.go create mode 100644 internal/server/check_stage.go create mode 100644 internal/server/check_stage_test.go create mode 100644 internal/stage/check.go create mode 100644 internal/stage/check_test.go diff --git a/app/lib/features/changes/domain/change_wording.dart b/app/lib/features/changes/domain/change_wording.dart index 67f894f5..766ee805 100644 --- a/app/lib/features/changes/domain/change_wording.dart +++ b/app/lib/features/changes/domain/change_wording.dart @@ -111,7 +111,7 @@ String? noPatchReasonMessage(String? reason) => switch (reason) { 'budget' => 'The workspace snapshot ran out of text budget, so no diff text was ' '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' => "This visit's recorded changes reached their size limit, so this patch " 'was dropped.', @@ -121,6 +121,15 @@ String? noPatchReasonMessage(String? reason) => switch (reason) { 'baseline' => "The file's content at stage start couldn't be recovered from Git, so no " '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, }; diff --git a/app/lib/features/changes/domain/file_change.dart b/app/lib/features/changes/domain/file_change.dart index 6068d6f2..c11222e5 100644 --- a/app/lib/features/changes/domain/file_change.dart +++ b/app/lib/features/changes/domain/file_change.dart @@ -36,8 +36,10 @@ class FileChange { final bool truncated; /// Why the server recorded no (complete) patch: `binary`, `file_size`, - /// `budget`, `lines`, `evidence_size`, `git_status` or `baseline`. Null from - /// an older server or when a patch was recorded. + /// `budget`, `lines`, `evidence_size`, `git_status`, `baseline`, `symlink`, + /// `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? beforeMode; final String? afterMode; diff --git a/app/lib/features/graph/domain/check_stage.dart b/app/lib/features/graph/domain/check_stage.dart new file mode 100644 index 00000000..23bc3dc1 --- /dev/null +++ b/app/lib/features/graph/domain/check_stage.dart @@ -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 checkCommands(dynamic stage) { + if (stage is! Map) return const []; + final blocks = stage['blocks']; + if (blocks is! Map) return const []; + 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'; +} diff --git a/app/lib/features/graph/domain/graph_definition.dart b/app/lib/features/graph/domain/graph_definition.dart index 60735fa9..32fae060 100644 --- a/app/lib/features/graph/domain/graph_definition.dart +++ b/app/lib/features/graph/domain/graph_definition.dart @@ -1,3 +1,4 @@ +import 'check_stage.dart'; import 'graph_protocol.dart'; /// 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 /// routes to. 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 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. final int? stageIndex; @@ -142,7 +159,15 @@ List graphNodes(dynamic graph) { for (var index = 0; index < stages.length; index += 1) { final key = _stageKey(stages[index]); 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)) { nodes.add(const GraphNode(key: failureEnd, terminal: true)); diff --git a/app/lib/features/graph/domain/stage_definition.dart b/app/lib/features/graph/domain/stage_definition.dart index 03f8b1f6..5b667c55 100644 --- a/app/lib/features/graph/domain/stage_definition.dart +++ b/app/lib/features/graph/domain/stage_definition.dart @@ -1,3 +1,4 @@ +import 'check_stage.dart'; import 'graph_definition.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 /// stage executed. 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 value; /// Multi-line content (prompt, output, outcomes, tools, memory, routes). 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 @@ -58,6 +68,12 @@ String stageConfigLabel(String key) { return 'Budget (tokens)'; case 'harness': return 'Harness'; + case 'command_timeout': + return 'Command timeout'; + case 'keep_going': + return 'Keep going'; + case 'delivery': + return 'Delivery gate'; default: return key; } @@ -69,10 +85,27 @@ String stageConfigLabel(String key) { /// interpreted here; the pane keeps the stage's raw JSON so they stay visible. List stageDefinitionFields(dynamic stage) { if (stage is! Map) return const []; + final type = effectiveStageType(stage['type']); final fields = [ - 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']); if (prompt.trim().isNotEmpty) { fields.add(StageDefinitionField('Prompt', prompt, block: true)); diff --git a/app/lib/features/graph/widgets/graph_stage_node.dart b/app/lib/features/graph/widgets/graph_stage_node.dart index bea4c6b8..c1f60290 100644 --- a/app/lib/features/graph/widgets/graph_stage_node.dart +++ b/app/lib/features/graph/widgets/graph_stage_node.dart @@ -45,10 +45,7 @@ class GraphStageNode extends StatelessWidget { return status != null && status.trim().isNotEmpty ? status : null; } - String get _label { - final status = _status; - return status == null ? node.label : '${node.label}\n$status'; - } + String get _label => graphNodeSemanticsLabel(node, _status); @override Widget build(BuildContext context) { @@ -112,11 +109,13 @@ class GraphStageNode extends StatelessWidget { graphStatusState(status), Theme.of(context).colorScheme, ); + final caption = node.kindCaption; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(_breakable(node.label), softWrap: true), + if (caption != null) _kind(context, caption), if (status != null) Row( 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 /// long unbroken key, so the same invisible break opportunities are added. /// The visible text and the semantics label stay unchanged. @@ -265,6 +287,18 @@ class StageActivityHaloPainter extends CustomPainter { 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 /// a block is red, running is blue, waiting teal, anything else grey. String graphStatusState(String status) { diff --git a/app/lib/features/graph/widgets/run_graph_canvas.dart b/app/lib/features/graph/widgets/run_graph_canvas.dart index 113a3f1b..47c76319 100644 --- a/app/lib/features/graph/widgets/run_graph_canvas.dart +++ b/app/lib/features/graph/widgets/run_graph_canvas.dart @@ -341,7 +341,7 @@ class RunGraphNode extends StatelessWidget { } return Semantics( container: true, - label: status == null ? node.label : '${node.label}\n$status', + label: graphNodeSemanticsLabel(node, status), child: ExcludeSemantics( child: IgnorePointer( child: GraphStageNode( diff --git a/app/lib/features/graph/widgets/stage_definition_view.dart b/app/lib/features/graph/widgets/stage_definition_view.dart index 26fd3fec..2d17bc2f 100644 --- a/app/lib/features/graph/widgets/stage_definition_view.dart +++ b/app/lib/features/graph/widgets/stage_definition_view.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/text/markdown_source_view.dart'; +import '../../../ui/text/monospace.dart'; import '../../chat/ui/transcript/chat_markdown_view.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; @@ -190,8 +191,15 @@ class _StageDefinitionFieldView extends StatelessWidget { children: [ Text(field.label, style: style.label), 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. - if (field.block && raw) + else if (field.block && raw) _SelectableDefinitionText(value: field.value, style: style.value) else if (field.block) 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 /// the host's own line metrics, not a font override or a fixed height. 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 TextStyle style; diff --git a/app/lib/features/runs/domain/check_step_output.dart b/app/lib/features/runs/domain/check_step_output.dart new file mode 100644 index 00000000..2b4f7989 --- /dev/null +++ b/app/lib/features/runs/domain/check_step_output.dart @@ -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 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; +} diff --git a/app/lib/features/runs/ui/run_check_output_view.dart b/app/lib/features/runs/ui/run_check_output_view.dart new file mode 100644 index 00000000..bdeb6978 --- /dev/null +++ b/app/lib/features/runs/ui/run_check_output_view.dart @@ -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, + }; +} diff --git a/app/lib/features/runs/ui/run_detail_visit_facts.dart b/app/lib/features/runs/ui/run_detail_visit_facts.dart index 49cdfccb..7bae3f72 100644 --- a/app/lib/features/runs/ui/run_detail_visit_facts.dart +++ b/app/lib/features/runs/ui/run_detail_visit_facts.dart @@ -133,6 +133,22 @@ String? detailVisitSkills(JsonMap step) { 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. String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']); diff --git a/app/lib/features/runs/ui/run_detail_visit_facts_view.dart b/app/lib/features/runs/ui/run_detail_visit_facts_view.dart index 8d76052f..81e9067d 100644 --- a/app/lib/features/runs/ui/run_detail_visit_facts_view.dart +++ b/app/lib/features/runs/ui/run_detail_visit_facts_view.dart @@ -21,6 +21,7 @@ class RunVisitFactsView extends StatelessWidget { final facts = detailVisitFacts(step); final verdict = detailVisitVerdict(step); final diagnostic = detailVisitDiagnostic(step); + final repairs = detailVisitOutcomeRepairs(step); return Padding( key: const Key('run-visit-facts'), padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 12), @@ -28,6 +29,23 @@ class RunVisitFactsView extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.start, children: [ _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) ...[ const SizedBox(height: 8), Text('Verdict', style: style.heading), @@ -57,10 +75,14 @@ class _FactGrid extends StatelessWidget { static String _stateOf(VisitFact fact) { final value = fact.value.trim().toLowerCase(); if (fact.label == 'Outcome') { - if (value == 'error' || value == 'failed' || value == 'blocked') { + if (value == 'error' || + value == 'failed' || + value == 'fail' || + value == 'blocked') { return 'failed'; } - if (value == 'success') return 'succeeded'; + // A check stage routes `pass`/`fail`. + if (value == 'success' || value == 'pass') return 'succeeded'; return 'running'; } return graphStatusState(fact.value); diff --git a/app/lib/features/runs/ui/run_detail_visit_sections.dart b/app/lib/features/runs/ui/run_detail_visit_sections.dart index e0182105..024e8723 100644 --- a/app/lib/features/runs/ui/run_detail_visit_sections.dart +++ b/app/lib/features/runs/ui/run_detail_visit_sections.dart @@ -4,6 +4,8 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/floating_destination_bar.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_field_body.dart'; import '../../../ui/layout/sticky_section.dart'; @@ -216,6 +218,9 @@ class _VisitSummaryState extends State<_VisitSummary> { ); final open = !_closed.contains(name); 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( key: ValueKey('run-visit-section-$name'), title: name, @@ -224,13 +229,15 @@ class _VisitSummaryState extends State<_VisitSummary> { if (!_closed.remove(name)) _closed.add(name); }), trailing: [copy], - body: lazy + body: sliver ? null : 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( padding: padding, sliver: RunFieldSliver(value: value, empty: empty), diff --git a/app/lib/features/runs/ui/run_detail_visit_session_state.dart b/app/lib/features/runs/ui/run_detail_visit_session_state.dart index 940d6a4b..7c3b119e 100644 --- a/app/lib/features/runs/ui/run_detail_visit_session_state.dart +++ b/app/lib/features/runs/ui/run_detail_visit_session_state.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import '../domain/check_step_output.dart'; import 'run_detail_visit_export.dart'; import 'run_detail_visit_recorded.dart'; @@ -18,6 +19,10 @@ const String visitSessionNoIdentity = 'Runtime error: this model stage has no recorded session identity.'; 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. const String visitSessionEndpointMissing = 'Set the server URL in Settings to open the session.'; @@ -94,6 +99,7 @@ String _noSessionMessage(JsonMap step) { if (status == 'canceled' || status == 'interrupted') { return visitSessionStopped; } + if (checkStepOutput(step['output']) != null) return visitSessionCheck; final model = recordedText(step['provider']) != null || recordedText(step['model']) != null; diff --git a/app/test/features/changes/no_patch_reason_test.dart b/app/test/features/changes/no_patch_reason_test.dart index d7e737a9..8b30f2d4 100644 --- a/app/test/features/changes/no_patch_reason_test.dart +++ b/app/test/features/changes/no_patch_reason_test.dart @@ -13,7 +13,7 @@ const _expected = { 'budget': 'The workspace snapshot ran out of text budget, so no diff text was ' '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': "This visit's recorded changes reached their size limit, so this patch " 'was dropped.', @@ -24,6 +24,15 @@ const _expected = { "The file's content at stage start couldn't be recovered from Git, so no " 'diff 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}) => diff --git a/app/test/features/graph/domain/check_stage_test.dart b/app/test/features/graph/domain/check_stage_test.dart new file mode 100644 index 00000000..5085f23f --- /dev/null +++ b/app/test/features/graph/domain/check_stage_test.dart @@ -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 _verify({Map? 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')); + }); +} diff --git a/app/test/features/graph/widgets/check_stage_render_test.dart b/app/test/features/graph/widgets/check_stage_render_test.dart new file mode 100644 index 00000000..cd71d157 --- /dev/null +++ b/app/test/features/graph/widgets/check_stage_render_test.dart @@ -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 _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( + 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); + }); +} diff --git a/app/test/features/runs/domain/check_step_output_test.dart b/app/test/features/runs/domain/check_step_output_test.dart new file mode 100644 index 00000000..0b3b67b0 --- /dev/null +++ b/app/test/features/runs/domain/check_step_output_test.dart @@ -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'); + }); +} diff --git a/app/test/features/runs/ui/run_check_visit_test.dart b/app/test/features/runs/ui/run_check_visit_test.dart new file mode 100644 index 00000000..0dd3579a --- /dev/null +++ b/app/test/features/runs/ui/run_check_visit_test.dart @@ -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}) => { + 'id': 78, + 'title': 'Check run', + 'name': 'release', + 'pipeline_id': 7, + 'version': 4, + 'status': 'succeeded', + 'graph': { + 'stages': [ + { + 'key': 'verify', + 'type': 'check', + 'configs': {'delivery': 'true'}, + 'edges': {'pass': '#', 'fail': 'verify'}, + 'blocks': {'commands': 'go vet ./...\ngo test ./...'}, + }, + ], + }, + 'steps': [ + { + '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': {'visit': 1, 'outcome_repairs': repairs}, + 'output': { + 'markdown': '# outcome\n\nfail\n\n# handoff\n\nFix the test.', + 'summary': '1 of 2 checks failed: go test ./...', + 'delivery': true, + 'checks': [ + { + 'command': 'go vet ./...', + 'status': 'passed', + 'exit_code': 0, + 'duration_ms': 2100, + 'output': 'vet ok', + 'truncated': false, + }, + { + '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( + 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)'); + }); +} diff --git a/docs/stage-file-diffs.md b/docs/stage-file-diffs.md index 96909a7b..956f7ccb 100644 --- a/docs/stage-file-diffs.md +++ b/docs/stage-file-diffs.md @@ -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"`. - Added/deleted files and permission changes are recorded. Renames appear as deletion/addition. Binary changes retain metadata, not binary contents. -- Symlinks, special files, common credential/environment/key/database paths, - `secrets/`, Git internals and `node_modules/` are excluded. This is a path-based +- Common credential/environment/key/database paths and `secrets/` are protected: + 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 sensitive text and become part of retained history. -- Limits: 10,000 inventoried entries, 1 MiB per file and 32 MiB per snapshot of - retained text, 256 MiB per hashed file, five seconds per snapshot, 5,000 - combined lines per textual comparison, 64 KiB per patch and 128 KiB serialized - file evidence per visit. Oversized, unreadable, omitted or truncated evidence - is explicitly flagged partial. +- Tool output is not stage work: untracked files below cache and dependency + directories (`node_modules/`, `.git/`, `__pycache__/`, `.venv/`, `.mypy_cache/`, + `.pytest_cache/`, `.ruff_cache/`, `.next/`, `.dart_tool/`, `.gradle/`, ...), + untracked `*.pyc`, and untracked files below `build/`, `dist/`, `out/`, + `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, 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 @@ -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 `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`. - 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`: - `binary`, `file_size` (text over 1 MiB), `budget` (32 MiB snapshot text - budget), `lines` (over 5,000 combined lines), `evidence_size` (per-visit - retained evidence limit), `git_status` (seen only in Git status) or `baseline`. - Binary changes stay `complete`; the others make the visit `partial`. + `binary`, `symlink`, `large`, `generated` (lockfiles such as `go.sum` or + `package-lock.json`, `*.min.js`, source maps, files below a cache directory), + `file_size` (text over 1 MiB), `budget` (32 MiB snapshot text budget), `lines` + (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 printed to stderr) naming every visit whose capture was partial or unavailable. - Failed/canceled stages still retain changes when execution returns. Unconfirmed diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index 373158b2..f2009c88 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -64,7 +64,12 @@ Start from `pipelines templates` and `pipelines new NAME --template KEY` (`research`, `task`); these fill in the server's provider/model. Read `references/format.md` and `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 without `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 constraints. The runner enforces turns, tools and limits and explains the output diff --git a/internal/author/skill/references/delivery.md b/internal/author/skill/references/delivery.md index bc27855a..31c71898 100644 --- a/internal/author/skill/references/delivery.md +++ b/internal/author/skill/references/delivery.md @@ -9,9 +9,9 @@ request does not authorize publication, execution or deployment. 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 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 -lands it, first merging a moved main and re-checking the merged tree; only a real -conflict fails. Direct recovery can complete a reviewed merge without another pipeline. +With delivery=true (a model land stage on any harness, or a check stage), the +server checks and lands the candidate, first merging a moved main and +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 builds as WIP. Verify any download URL serves the real bytes before reporting it. diff --git a/internal/author/skill/references/format.md b/internal/author/skill/references/format.md index ed7ae534..5f48275c 100644 --- a/internal/author/skill/references/format.md +++ b/internal/author/skill/references/format.md @@ -2,8 +2,8 @@ A definition is Markdown made only of `# stage KEY` headings and fenced blocks; no prose outside blocks. Blocks: `prompt`, `configs`, `tools`, `skills`, `edges`, -`checks`, `limits` (`references/control.md`), `permissions` and `notify` -(`references/notifications.md`). There are no memory, links, input or output +`checks`, `limits` (`references/control.md`), `permissions`, `notify` +(`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/`. Schedules are saved run configurations, never definition blocks (`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 hand-written draft. Availability needs `pipelines provider-check`. - `harness=opencode|pi|claude`; omission means OpenCode (`references/harnesses.md`). - `claude` needs `provider=anthropic` and a Claude model ID, and accepts no - `permissions` block, `delivery=true` or run write paths. + `claude` needs `provider=anthropic` and a Claude model ID; its `permissions` + 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 and timeouts; a stage with `edit`/`shell` (or no tools block) never replays 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 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`). -- `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 without `edit` leave file changes + in the run directory (below). - `auto_skip=false`: disable the server skip fallback for a stage that declares a `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 traversal are rejected. With restricted edits and shell enabled, list shell too: `{"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 lacks `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: `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 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 `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 -A workflow that commits its change ends in `land`: a model stage with -`read`/`glob`/`grep`/`shell`, no `edit`, that commits locally. Its prompt states: +A workflow that commits its change ends in `land`: either a check stage with +`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). 2. Check the staged diff for unrelated work and secrets. 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 worktree (see "Run worktrees" below); requires the item checkout to be clean, untracked files included (the main checkout need not be: the final diff --git a/internal/cli/agent_mode_test.go b/internal/cli/agent_mode_test.go index ab18edb7..acf6a570 100644 --- a/internal/cli/agent_mode_test.go +++ b/internal/cli/agent_mode_test.go @@ -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) { line := waitLine(sampleRun()) if !strings.Contains(line, "failed at implement · go test failed") || strings.Contains(line, "long detail line") { diff --git a/internal/cli/inspect.go b/internal/cli/inspect.go index fe53caff..ba0dac64 100644 --- a/internal/cli/inspect.go +++ b/internal/cli/inspect.go @@ -93,9 +93,23 @@ func inspectStep(d *protocol.RunDetail, sequence int, transcripts bool) (string, if step.SessionID != "" { 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 != "" { 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) != "" { b.WriteString("\noutput:\n" + indent(strings.TrimSpace(markdown)) + "\n") } else if len(step.Output) > 0 { diff --git a/internal/filediff/policy.go b/internal/filediff/policy.go new file mode 100644 index 00000000..978bbc65 --- /dev/null +++ b/internal/filediff/policy.go @@ -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)) +} diff --git a/internal/filediff/policy_test.go b/internal/filediff/policy_test.go new file mode 100644 index 00000000..67c27425 --- /dev/null +++ b/internal/filediff/policy_test.go @@ -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) + } + } +} diff --git a/internal/filediff/snapshot.go b/internal/filediff/snapshot.go index 28ef9dc5..fda4dd7f 100644 --- a/internal/filediff/snapshot.go +++ b/internal/filediff/snapshot.go @@ -26,12 +26,12 @@ import ( ) const ( - maxFiles = 10000 + maxFiles = 20000 maxFileBytes = 1 << 20 maxSnapshotBytes = 32 << 20 - maxPatchBytes = 128 << 10 - maxFilePatchBytes = 64 << 10 - maxLines = 5000 + maxPatchBytes = 512 << 10 + maxFilePatchBytes = 128 << 10 + maxLines = 20000 binarySniffBytes = 8 << 10 ) @@ -82,6 +82,12 @@ type file struct { // 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. 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 @@ -108,6 +114,9 @@ type Snapshot struct { // the previous snapshot; missing records why one could not be recovered. baselines map[string]baseline 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 @@ -245,7 +254,7 @@ func protected(name string) bool { if template(part) { 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 } 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; // 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") 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", "--", ".") - out := &boundedOutput{limit: 2 << 20} - cmd.Stdout = out - if err := cmd.Run(); err != nil { - return nil, true, fmt.Errorf("Git file inventory unavailable") + list := func(args ...string) ([]string, error) { + cmd := gitCommand(ctx, directory, append([]string{"-c", "core.fsmonitor=false", "-C", directory, "ls-files"}, append(args, "-z", "--", ".")...)...) + out := &boundedOutput{limit: 2 << 20} + cmd.Stdout = out + 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 { return nil, false, ctx.Err() @@ -300,6 +336,9 @@ func inventory(ctx context.Context, directory string, root *os.Root) ([]string, if err != nil { return err } + if name != "." && entry.IsDir() && cacheDirs[entry.Name()] { + return fs.SkipDir // tool output, not stage work + } if name != "." && protected(name) { names = append(names, name) 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 { - 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) if err != nil { s.diagnostic = "Workspace snapshot unavailable." @@ -327,7 +366,7 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap } defer root.Close() s.available = true - names, git, err := inventory(ctx, directory, root) + names, git, err := inventory(ctx, directory, root, s.excluded) s.scope = "Workspace regular files" if git { 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." break } - if !fs.ValidPath(name) || protected(name) { + if !fs.ValidPath(name) { s.skipped[name] = true continue } - // Reject symlinks in every component, including aliases to sensitive paths. - valid := true + // Never follow a symlink: a path through a symlinked directory is + // skipped, and a symlink itself is compared by its target only. + valid, link := true, false parts := strings.Split(name, "/") for j := range parts { 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 break } // 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 { s.skipped[name] = true valid = false @@ -402,10 +446,38 @@ func Capture(ctx context.Context, directory string, previous ...*Snapshot) *Snap continue } info, err := root.Lstat(name) - if err != nil || !info.Mode().IsRegular() || info.Size() > maxHashBytes { + if err != nil { s.skipped[name] = true 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) if err != nil { 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. switch { case binary: + case generated: + // Tool output: compared by hash, listed without a patch. + entry.reason = reasonGenerated case seen && p.hash == entry.hash && !p.binary: // Unchanged since the previous snapshot: share its representation // 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 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 { s.recoverBaselines(ctx, directory, prev, used) @@ -584,6 +663,14 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges { result.Files = append(result.Files, change) } 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 // not), so the Git-status pass below only speaks for the rest. decided := map[string]bool{} @@ -598,7 +685,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges { continue } 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 } kind := "modified" @@ -615,6 +708,13 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges { if bOK { 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 // comes from the after snapshot's verified Git recovery. aData, unavailable := a.data, "" @@ -690,7 +790,7 @@ func Compare(before, after *Snapshot) *protocol.StageFileChanges { } ordered := make([]string, 0, len(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) } } diff --git a/internal/filediff/snapshot_test.go b/internal/filediff/snapshot_test.go index b4c18b98..64250fdd 100644 --- a/internal/filediff/snapshot_test.go +++ b/internal/filediff/snapshot_test.go @@ -248,10 +248,10 @@ func TestOverBudgetChangeIsListedWithoutPatch(t *testing.T) { } } -// TestGitStatusListsUncomparableChanges proves a file the content snapshot -// skips (here: above the hash bound) is still listed when its Git status -// changes during the visit, while a protected path never is. -func TestGitStatusListsUncomparableChanges(t *testing.T) { +// TestHugeFilesAreListedByMetadata proves a file above the hash bound is +// listed completely (by size, mtime and mode, without a patch), while a +// protected path is never listed and its change marks the capture partial. +func TestHugeFilesAreListedByMetadata(t *testing.T) { previous := maxHashBytes maxHashBytes = 16 defer func() { maxHashBytes = previous }() @@ -263,21 +263,30 @@ func TestGitStatusListsUncomparableChanges(t *testing.T) { git("commit", "-qm", "init") ctx := context.Background() 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, ".env", "A=2\n") changes := Compare(before, Capture(ctx, dir, before)) got := map[string]string{} for _, f := range changes.Files { - if !f.NoPatch { - t.Fatalf("git-listed change carries a patch: %+v", f) + if f.Patch != "" || f.NoPatchReason != reasonLarge || f.Truncated { + t.Fatalf("huge-file change: %+v", f) } got[f.Path] = f.Kind } - if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" { - t.Fatalf("git status listing = %v (%+v)", got, changes) + if len(got) != 2 || got["big.bin"] != "modified" || got["fresh.bin"] != "added" || changes.Status != "complete" { + 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) } } diff --git a/internal/pipeline/check_stage_test.go b/internal/pipeline/check_stage_test.go new file mode 100644 index 00000000..4452d6e9 --- /dev/null +++ b/internal/pipeline/check_stage_test.go @@ -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) + } +} diff --git a/internal/pipeline/lint.go b/internal/pipeline/lint.go index d0bd6a37..c2765c80 100644 --- a/internal/pipeline/lint.go +++ b/internal/pipeline/lint.go @@ -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 { continue // a person bounds a human stage's loop } diff --git a/internal/protocol/runs.go b/internal/protocol/runs.go index 27d3129c..1b55d128 100644 --- a/internal/protocol/runs.go +++ b/internal/protocol/runs.go @@ -458,6 +458,9 @@ type ControlEvidence struct { LimitReached bool `json:"limit_reached,omitempty"` ModelTarget string `json:"model_target,omitempty"` Memory map[string]MemoryRead `json:"memory,omitempty"` + // OutcomeRepairs counts the "missing # outcome" repair follow-ups the + // server sent during this visit (0 when the first answer was valid). + OutcomeRepairs int `json:"outcome_repairs,omitempty"` } // StageFileChanges is observed workspace evidence, not a model's claim of authorship. @@ -483,9 +486,13 @@ type FileChange struct { NoPatch bool `json:"no_patch,omitempty"` // NoPatchReason says why a content change has no (complete) patch: // "binary", "file_size" (text over 1 MiB), "budget" (snapshot text budget), - // "lines" (over 5,000 combined lines), "evidence_size" (per-visit retained + // "lines" (over 20,000 combined lines), "evidence_size" (per-visit retained // evidence limit), "git_status" (seen only in Git status) or "baseline" - // (stage-start content unrecoverable). Empty when a patch was recorded. + // (stage-start content unrecoverable). Policy reasons, which list the + // change completely and leave Truncated unset: "symlink" (target + // compared), "large" (over the hash bound; size/mtime/mode compared) and + // "generated" (lockfile, minified bundle, source map, cache file). + // Empty when a patch was recorded. NoPatchReason string `json:"no_patch_reason,omitempty"` BeforeMode string `json:"before_mode,omitempty"` AfterMode string `json:"after_mode,omitempty"` diff --git a/internal/server/check_stage.go b/internal/server/check_stage.go new file mode 100644 index 00000000..d5b906ec --- /dev/null +++ b/internal/server/check_stage.go @@ -0,0 +1,139 @@ +package server + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +// errDeliveryChecksFailed marks a delivery check stage whose commands ran and +// failed on the candidate: that is the stage's fail outcome, not an error. +var errDeliveryChecksFailed = errors.New("delivery checks failed") + +// runCheckStage executes a check stage. Without delivery its commands run in +// place in the run workspace. With delivery=true it is the landing gate: the +// server commits the run's leftovers, merges a moved main, runs the commands +// in a fresh candidate worktree of the commit and fast-forwards main only when +// every command passes. A failing command is the fail outcome (main is not +// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is +// an error. +func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) { + spec, err := stage.CheckStageSpec(def) + if err != nil { + return stage.Result{}, err + } + if !delivery { + def.Workspace = workspace + return stage.CheckStage{}.Run(ctx, def, nil) + } + ctx, cancel := context.WithTimeout(ctx, spec.Timeout) + defer cancel() + var report stage.CheckReport + note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error { + report = stage.RunCheckCommands(ctx, candidate, spec) + if report.Failed() { + return errDeliveryChecksFailed + } + return nil + }) + if err != nil && !errors.Is(err, errDeliveryChecksFailed) { + return stage.Result{}, err + } + result := stage.CheckResult(def.Key, spec, report) + markdown, _ := result.Output["markdown"].(string) + gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed." + if err == nil { + gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it." + } + if note != "" { + gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "." + } + result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1) + return result, nil +} + +// checkVerdict is the check stage's one-line verdict: its own summary, never +// a model's paraphrase of the command output. +func checkVerdict(output stage.Values) *protocol.StageVerdict { + summary, _ := output["summary"].(string) + if strings.TrimSpace(summary) == "" { + return nil + } + return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback} +} + +// readOnlyViolation reports the files a stage without edit left changed in +// the run directory. Paths under the stage's artifacts directory, the run's +// shared public directory and a harness state directory that lives inside the +// workspace (for example CLAUDE_CONFIG_DIR) are the harness's or the run's own +// and are not counted. It returns "" when the stage may change files or none +// changed. +func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string { + if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil { + return "" + } + for _, tool := range tools { + if tool == "edit" { + return "" + } + } + var prefixes []string + for _, dir := range ignored { + if rel, ok := workspaceRelative(workspace, dir); ok { + prefixes = append(prefixes, rel+"/") + } + } + var changed []string + for _, file := range changes.Files { + skip := false + for _, prefix := range prefixes { + if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) { + skip = true + break + } + } + if !skip { + changed = append(changed, file.Kind+" "+file.Path) + } + } + if len(changed) == 0 && changes.Omitted == 0 { + return "" + } + listed := changed + if len(listed) > 20 { + listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20)) + } + if changes.Omitted > 0 { + listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted)) + } + return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", ")) +} + +// workspaceEnv is the environment a command in workspace runs with: the run's +// directory environment when one applies, else the server's. +func workspaceEnv(ctx context.Context, workspace string) []string { + if env := workenv.CommandEnv(ctx, workspace); env != nil { + return env + } + return os.Environ() +} + +// workspaceRelative returns dir relative to workspace when dir is inside it. +func workspaceRelative(workspace, dir string) (string, bool) { + workspace = strings.TrimSuffix(workspace, "/") + dir = strings.TrimSuffix(dir, "/") + if workspace == "" || dir == "" { + return "", false + } + if dir == workspace { + return ".", true + } + rel, ok := strings.CutPrefix(dir, workspace+"/") + return rel, ok && rel != "" +} diff --git a/internal/server/check_stage_test.go b/internal/server/check_stage_test.go new file mode 100644 index 00000000..7c7e6918 --- /dev/null +++ b/internal/server/check_stage_test.go @@ -0,0 +1,205 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +func checkModelStage(key, tools, edges, configs string) string { + return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n" +} + +func checkTypeStage(key, commands, edges, configs string) string { + return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n" +} + +func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) { + t.Helper() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { store.Close() }) + if _, err := store.Submit(ctx, "check", source); err != nil { + t.Fatal(err) + } + items, _ := store.List(ctx) + r, err := newRunner(ctx, store) + if err != nil { + t.Fatal(err) + } + r.execute = execute + run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, err := store.GetRun(ctx, run.ID) + if err != nil { + t.Fatal(err) + } + return detail, store +} + +// A failing check sends the run back to the implementer with the failing +// output in its input; the reviewer only runs once the tree is green. +func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) { + ctx := context.Background() + workspace := t.TempDir() + source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") + + checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") + + checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "") + var visits atomic.Int32 + var secondInput string + detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) { + if def.Key == "implement" { + if visits.Add(1) == 2 { + data, _ := os.ReadFile(def.Turn.Input) + secondInput = string(data) + if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil { + return stage.Result{}, err + } + } + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil + }) + if detail.Status != "succeeded" { + t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps) + } + var stages []string + for _, step := range detail.Steps { + stages = append(stages, step.Stage+":"+step.Outcome) + } + if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" { + t.Fatal(got) + } + for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} { + if !strings.Contains(secondInput, want) { + t.Fatalf("implementer input lacks %q:\n%s", want, secondInput) + } + } + failed := detail.Steps[1] + if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") { + t.Fatalf("verdict %+v", failed.Verdict) + } + checks, _ := failed.Output["checks"].([]any) + if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" { + t.Fatalf("check step %+v", failed) + } +} + +// A delivery check stage is the landing gate: the run's uncommitted work is +// committed, the commands run on a fresh candidate and main fast-forwards; +// a failing command is the fail outcome and leaves main alone. +func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) { + for _, test := range []struct { + name, command, status string + landed bool + }{ + {"pass", "test -f work", "succeeded", true}, + {"fail", "test -f absent", "failed", false}, + } { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + root := t.TempDir() + main := filepath.Join(root, "main") + runGit(t, root, "init", "-b", "main", main) + runGit(t, main, "config", "user.email", "test@example.invalid") + runGit(t, main, "config", "user.name", "test") + if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, main, "add", "README") + runGit(t, main, "commit", "-m", "base") + item := filepath.Join(root, "item") + runGit(t, main, "worktree", "add", "-b", "item", item) + if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil { + t.Fatal(err) + } + runGit(t, item, "add", "work") + runGit(t, item, "commit", "-m", "work") + before := runGitOutput(t, main, "rev-parse", "HEAD") + source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true") + detail, _ := startSource(t, ctx, source, item, nil) + if detail.Status != test.status || len(detail.Steps) != 1 { + t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps) + } + step := detail.Steps[0] + markdown, _ := step.Output["markdown"].(string) + if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true { + t.Fatalf("gate evidence missing: %q", markdown) + } + landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD") + if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) { + t.Fatalf("landed = %v, want %v", landed, test.landed) + } + }) + } +} + +// A stage without edit that changes the workspace fails its visit and names +// the files; allow_workspace_changes=true opts a stage out. +func TestReadOnlyStageThatChangesFilesFails(t *testing.T) { + ctx := context.Background() + for _, test := range []struct { + name, configs, status string + }{ + {"enforced", "", "failed"}, + {"allowed", "allow_workspace_changes=true", "succeeded"}, + } { + t.Run(test.name, func(t *testing.T) { + workspace := t.TempDir() + if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil { + t.Fatal(err) + } + source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs) + detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil { + return stage.Result{}, err + } + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil + }) + if detail.Status != test.status { + t.Fatalf("run %s %q", detail.Status, detail.Diagnostic) + } + if test.status == "failed" { + diagnostic := detail.Steps[0].Diagnostic + if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") { + t.Fatal(diagnostic) + } + } + }) + } +} + +func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) { + def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}} + changes := &protocol.StageFileChanges{Files: []protocol.FileChange{ + {Path: ".claude-profile/.claude.json", Kind: "modified"}, + {Path: "artifacts/x/out.md", Kind: "added"}, + }} + ignored := []string{"/w/.claude-profile", "/w/artifacts/x"} + if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" { + t.Fatal(v) + } + changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"}) + if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") { + t.Fatal(v) + } + for name, ok := range map[string]bool{ + "edit tool": readOnlyViolation(def, []string{"edit"}, true, changes, "/w", nil) == "", + "no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "", + } { + if !ok { + t.Fatal(name, "was enforced") + } + } +} diff --git a/internal/server/delivery_gate.go b/internal/server/delivery_gate.go index 7a9a377e..095cc690 100644 --- a/internal/server/delivery_gate.go +++ b/internal/server/delivery_gate.go @@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second // own `merge --ff-only`, which refuses without touching anything when a local // change or untracked file would be overwritten. func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) { + return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error { + for _, check := range checks { + if err := runDeliveryCheck(ctx, candidate, check); err != nil { + return err + } + } + return nil + }) +} + +// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as +// a function of the fresh candidate worktree: a check stage records each +// command's result there instead of stopping at the first error. +func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) { lock, err := acquireDeliveryLock(ctx, access.LockPath) if err != nil { return "", err @@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged)) itemHead = merged } - if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil { + if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil { if note != "" { return note, fmt.Errorf("%s; %w", note, err) } @@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) { } } -func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error { +func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error { candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-") if err != nil { return fmt.Errorf("create delivery candidate: %w", err) @@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output))) } defer cleanupDeliveryCandidate(workspace, candidate) - for _, check := range checks { - if err := runDeliveryCheck(ctx, candidate, check); err != nil { - return err - } - } - return nil + return check(ctx, candidate) } // cleanupDeliveryCandidate always uses its own bounded context: the stage context diff --git a/internal/server/retry_test.go b/internal/server/retry_test.go index ba85eb17..9d711b51 100644 --- a/internal/server/retry_test.go +++ b/internal/server/retry_test.go @@ -597,7 +597,10 @@ esac runStage := func(name, tools string) (status, sessions, diagnostic string) { t.Helper() workspace := t.TempDir() - script := strings.ReplaceAll(scriptTemplate, "@STATE@", workspace) + // The fake harness keeps its counters outside the workspace: a read-only + // stage must leave the run directory unchanged. + state := t.TempDir() + script := strings.ReplaceAll(scriptTemplate, "@STATE@", state) if err := os.WriteFile(executable, []byte(script), 0700); err != nil { t.Fatal(err) } @@ -623,7 +626,7 @@ esac if len(detail.Steps) > 0 { diagnostic = detail.Steps[0].Diagnostic } - if data, err := os.ReadFile(filepath.Join(workspace, "sessions")); err == nil { + if data, err := os.ReadFile(filepath.Join(state, "sessions")); err == nil { sessions = strings.TrimSpace(string(data)) } return detail.Status, sessions, diagnostic diff --git a/internal/server/runner.go b/internal/server/runner.go index c2b8330a..473c30f8 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -2193,6 +2193,8 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na budgetBefore = budgets[key].Snapshot() stageCtx = stage.WithBudget(stageCtx, budgets[key]) } + repairs := &stage.RepairCounter{} + stageCtx = stage.WithRepairCounter(stageCtx, repairs) snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second) before := filediff.Capture(snapshotCtx, workspace) snapshotCancel() @@ -2209,7 +2211,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na err = ctx.Err() return } - if r.execute != nil { + if stage.EffectiveType(def.Type) == stage.CheckType { + // The server runs a check stage's commands itself, in the run + // workspace or, for delivery, in a fresh candidate worktree. + result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id) + } else if r.execute != nil { timeout, _ := stage.StageTimeout(def) executeCtx, cancel := context.WithTimeout(stageCtx, timeout) defer cancel() @@ -2383,7 +2389,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input} } } - if err == nil && delivery && result.Outcome == "success" { + if err == nil { + // A stage without edit must leave the run directory as it found it; + // a shell is not a licence to write (allow_workspace_changes opts out). + ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...) + if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" { + err = errors.New(violation) + log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation) + step.Status = "failed" + step.Diagnostic = violation + step.Outcome = "error" + step.Output = stage.Values{"error": violation, "stage": key, "input": input} + if len(result.Output) > 0 { + step.Output["salvage"] = result.Output + } + } + } + if err == nil && stage.EffectiveType(def.Type) == stage.CheckType { + step.Verdict = checkVerdict(result.Output) + } + if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" { checks, checksErr := stage.DeliveryChecks(def) if checksErr != nil { err = checksErr @@ -2427,7 +2452,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false) return } - step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads} + step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()} + if step.Control.OutcomeRepairs > 0 { + log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs) + } if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits { for _, outcome := range selected.Limits.On { if outcome == step.Outcome { @@ -2474,7 +2502,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na // markdown body, which the field-map summariser reads as untrusted data and // answers with an invented rationale; those steps get the honest read-time // fallback instead. - if r.verdict != nil && !turnOutputOnly(step.Output) { + if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil { reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout) if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary { step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel} diff --git a/internal/stage/check.go b/internal/stage/check.go new file mode 100644 index 00000000..0d21927f --- /dev/null +++ b/internal/stage/check.go @@ -0,0 +1,413 @@ +package stage + +import ( + "bytes" + "context" + "errors" + "fmt" + "os/exec" + "strconv" + "strings" + "syscall" + "time" + "unicode/utf8" + + "git.a-wan.net/alan/pipelines/internal/workenv" +) + +// CheckType is a stage the server runs itself: a list of shell commands in the +// run's workspace, no model. Its outcome is pass or fail, so a red tree can be +// routed back to the implementer (with the failing output as the handoff) +// before a reviewer or a landing stage ever sees it. +const CheckType = "check" + +// Check outcomes. error stays the infrastructure-failure route, as for every +// stage type. +const ( + CheckPass = "pass" + CheckFail = "fail" +) + +// Per-command check statuses recorded on the step output. +const ( + CheckStatusPassed = "passed" + CheckStatusFailed = "failed" + CheckStatusTimedOut = "timed_out" + CheckStatusNotRun = "not_run" +) + +const ( + maxCheckCommands = 20 + maxCheckCommandBytes = 4096 + defaultCommandTimeout = 30 * time.Minute + maxCheckOutputBytes = 64 << 10 // retained per failed command (head and tail) + maxPassedOutputBytes = 2 << 10 // retained per passing command (tail) + checkHandoffTailBytes = 1500 // per failed command in the handoff + checkOutputHeadBytes = 16 << 10 + checkProcessWaitDelay = 5 * time.Second + checkFailureHandoffMax = 3 +) + +// CheckSpec is a validated check stage. +type CheckSpec struct { + Commands []string + CommandTimeout time.Duration + Timeout time.Duration + KeepGoing bool + Delivery bool +} + +// CheckCommandResult is one command's recorded result (step output "checks"). +type CheckCommandResult struct { + Command string `json:"command"` + Status string `json:"status"` + ExitCode int `json:"exit_code"` + DurationMS int64 `json:"duration_ms"` + Output string `json:"output,omitempty"` + Truncated bool `json:"truncated,omitempty"` +} + +// CheckReport is the result of running a check stage's commands once. +type CheckReport struct { + Commands []CheckCommandResult +} + +// Failed reports whether any command did not pass. +func (r CheckReport) Failed() bool { + for _, c := range r.Commands { + if c.Status != CheckStatusPassed { + return true + } + } + return false +} + +type CheckStage struct{} + +var _ Stage = CheckStage{} + +func (CheckStage) Validate(def Definition) error { + _, err := CheckStageSpec(def) + return err +} + +// CheckStageSpec validates a check stage definition and returns its settings. +func CheckStageSpec(def Definition) (CheckSpec, error) { + if EffectiveType(def.Type) != CheckType { + return CheckSpec{}, fmt.Errorf("expected check stage") + } + for name := range def.Blocks { + switch name { + case "configs", "edges", "output", "commands": + case "skills": + return CheckSpec{}, errSkillsModelOnly("check") + case "prompt", "tools", "permissions", "checks": + return CheckSpec{}, fmt.Errorf("check stages run their commands block on the server, without a model; remove the %s block", name) + default: + return CheckSpec{}, fmt.Errorf("unexpected block %q for check stage", name) + } + } + commands, err := CheckCommands(def.Blocks["commands"]) + if err != nil { + return CheckSpec{}, err + } + spec := CheckSpec{Commands: commands, CommandTimeout: defaultCommandTimeout} + for key, value := range def.Configs { + switch key { + case "timeout": + case "command_timeout": + duration, err := time.ParseDuration(value) + if err != nil || duration <= 0 { + return CheckSpec{}, fmt.Errorf("command_timeout must be a positive duration, such as 10m") + } + spec.CommandTimeout = duration + case "keep_going": + if value != "true" && value != "false" { + return CheckSpec{}, fmt.Errorf("keep_going must be true or false") + } + spec.KeepGoing = value == "true" + case "delivery": + if value != "true" { + return CheckSpec{}, fmt.Errorf("delivery must be true when set") + } + spec.Delivery = true + default: + return CheckSpec{}, fmt.Errorf("unknown check config %q (use timeout, command_timeout, keep_going or delivery)", key) + } + } + if spec.Timeout, err = StageTimeout(def); err != nil { + return CheckSpec{}, err + } + for _, outcome := range []string{CheckPass, CheckFail} { + if def.Edges[outcome] == "" { + return CheckSpec{}, fmt.Errorf("check stage requires %s and %s edges", CheckPass, CheckFail) + } + } + for outcome := range def.Edges { + if outcome != CheckPass && outcome != CheckFail && outcome != "error" { + return CheckSpec{}, fmt.Errorf("check stage outcomes are %s, %s and error; remove the %s edge", CheckPass, CheckFail, outcome) + } + } + return spec, nil +} + +// CheckCommands parses a commands block: one shell command per line; blank +// lines and lines starting with # are ignored. +func CheckCommands(text string) ([]string, error) { + var commands []string + for _, line := range strings.Split(text, "\n") { + command := strings.TrimSpace(line) + if command == "" || strings.HasPrefix(command, "#") { + continue + } + if len(command) > maxCheckCommandBytes { + return nil, fmt.Errorf("check command exceeds %d bytes", maxCheckCommandBytes) + } + if !utf8.ValidString(command) || strings.ContainsRune(command, 0) { + return nil, fmt.Errorf("check commands must be UTF-8 text") + } + commands = append(commands, command) + } + if len(commands) == 0 || len(commands) > maxCheckCommands { + return nil, fmt.Errorf("check stage requires a commands block with 1 to %d commands, one per line", maxCheckCommands) + } + return commands, nil +} + +// Run executes the commands in place in def.Workspace. The runner calls +// RunCheckCommands directly for a delivery check (in a fresh candidate +// worktree); this is the in-place path. +func (CheckStage) Run(ctx context.Context, def Definition, _ Values) (Result, error) { + spec, err := CheckStageSpec(def) + if err != nil { + return Result{}, err + } + if strings.TrimSpace(def.Workspace) == "" { + return Result{}, fmt.Errorf("check stage has no workspace") + } + ctx, cancel := context.WithTimeout(ctx, spec.Timeout) + defer cancel() + report := RunCheckCommands(ctx, def.Workspace, spec) + if err := ctx.Err(); err != nil && !report.Failed() { + return Result{}, err + } + return CheckResult(def.Key, spec, report), nil +} + +// RunCheckCommands runs every command with `sh -c` from directory, in order, +// with the directory's workspace environment. It stops at the first failure +// unless KeepGoing; later commands are recorded as not_run. +func RunCheckCommands(ctx context.Context, directory string, spec CheckSpec) CheckReport { + report := CheckReport{} + stop := false + for _, command := range spec.Commands { + if stop || ctx.Err() != nil { + report.Commands = append(report.Commands, CheckCommandResult{Command: command, Status: CheckStatusNotRun, ExitCode: -1}) + continue + } + result := runCheckCommand(ctx, directory, command, spec.CommandTimeout) + report.Commands = append(report.Commands, result) + if result.Status != CheckStatusPassed && !spec.KeepGoing { + stop = true + } + } + return report +} + +func runCheckCommand(ctx context.Context, directory, command string, timeout time.Duration) CheckCommandResult { + commandCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + cmd := exec.CommandContext(commandCtx, "sh", "-c", command) + cmd.Dir = directory + cmd.Env = workenv.CommandEnv(ctx, directory) + // A test suite starts children; a timeout kills the whole process group, + // and WaitDelay bounds a child that keeps the output pipes open. + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Cancel = func() error { + if cmd.Process != nil { + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + return nil + } + cmd.WaitDelay = checkProcessWaitDelay + output := &headTailBuffer{head: checkOutputHeadBytes, limit: maxCheckOutputBytes} + cmd.Stdout = output + cmd.Stderr = output + started := time.Now() + err := cmd.Run() + result := CheckCommandResult{Command: command, DurationMS: time.Since(started).Milliseconds()} + result.Output, result.Truncated = output.String() + var exit *exec.ExitError + switch { + case err == nil: + result.Status = CheckStatusPassed + case commandCtx.Err() != nil: + result.Status = CheckStatusTimedOut + result.ExitCode = -1 + if ctx.Err() != nil { + result.Output = strings.TrimRight(result.Output+"\n[stopped: the stage timeout or cancellation ended the command]", "\n") + } else { + result.Output = strings.TrimRight(result.Output+"\n[stopped: command_timeout "+timeout.String()+" reached]", "\n") + } + case errors.As(err, &exit): + result.Status = CheckStatusFailed + result.ExitCode = exit.ExitCode() + default: + result.Status = CheckStatusFailed + result.ExitCode = -1 + result.Output = strings.TrimSpace(result.Output + "\n" + err.Error()) + } + if result.Status == CheckStatusPassed && len(result.Output) > maxPassedOutputBytes { + cut := len(result.Output) - maxPassedOutputBytes + for cut < len(result.Output) && !utf8.RuneStart(result.Output[cut]) { + cut++ + } + result.Output = "[... earlier output omitted ...]\n" + result.Output[cut:] + result.Truncated = true + } + return result +} + +// CheckResult renders a report as the stage result: outcome pass or fail, the +// output.md-style markdown later stages read (handoff first, then every +// command's output), a one-line summary and the structured per-command list. +func CheckResult(key string, spec CheckSpec, report CheckReport) Result { + outcome := CheckPass + if report.Failed() { + outcome = CheckFail + } + summary := CheckSummary(report) + var b strings.Builder + b.WriteString("# outcome\n\n" + outcome + "\n\n# handoff\n\n" + summary + "\n") + failures := 0 + for _, c := range report.Commands { + if c.Status != CheckStatusFailed && c.Status != CheckStatusTimedOut { + continue + } + failures++ + if failures > checkFailureHandoffMax { + b.WriteString("\nMore failures are listed below.\n") + break + } + fmt.Fprintf(&b, "\n`%s` %s:\n\n~~~\n%s\n~~~\n", c.Command, checkStatusPhrase(c), tailText(c.Output, checkHandoffTailBytes)) + } + if outcome == CheckFail { + b.WriteString("\nFix the cause; the server reruns these checks.\n") + } + b.WriteString("\n## Commands\n") + for _, c := range report.Commands { + fmt.Fprintf(&b, "\n### `%s`: %s\n", c.Command, checkStatusPhrase(c)) + if c.Status == CheckStatusNotRun { + continue + } + if strings.TrimSpace(c.Output) == "" { + b.WriteString("\n(no output)\n") + continue + } + fmt.Fprintf(&b, "\n~~~\n%s\n~~~\n", c.Output) + } + checks := make([]any, 0, len(report.Commands)) + for _, c := range report.Commands { + checks = append(checks, map[string]any{ + "command": c.Command, "status": c.Status, "exit_code": c.ExitCode, + "duration_ms": c.DurationMS, "output": c.Output, "truncated": c.Truncated, + }) + } + output := Values{"markdown": b.String(), "summary": summary, "checks": checks} + if spec.Delivery { + output["delivery"] = true + } + return Result{Outcome: outcome, Output: output} +} + +// CheckSummary is the one-line verdict for a report. +func CheckSummary(report CheckReport) string { + total := len(report.Commands) + var failed []string + for _, c := range report.Commands { + if c.Status == CheckStatusFailed || c.Status == CheckStatusTimedOut { + failed = append(failed, c.Command) + } + } + if len(failed) == 0 { + if total == 1 { + return "1 check passed." + } + return strconv.Itoa(total) + " checks passed." + } + line := fmt.Sprintf("%d of %d checks failed: %s", len(failed), total, strings.Join(failed, "; ")) + if len(line) > 180 { + line = strings.ToValidUTF8(line[:180], "") + "…" + } + return line +} + +func checkStatusPhrase(c CheckCommandResult) string { + duration := (time.Duration(c.DurationMS) * time.Millisecond).Round(100 * time.Millisecond) + switch c.Status { + case CheckStatusPassed: + return "passed (" + duration.String() + ")" + case CheckStatusTimedOut: + return "timed out (" + duration.String() + ")" + case CheckStatusNotRun: + return "not run (an earlier check failed)" + default: + return fmt.Sprintf("failed with exit code %d (%s)", c.ExitCode, duration) + } +} + +func tailText(text string, limit int) string { + text = strings.TrimSpace(text) + if len(text) <= limit { + if text == "" { + return "(no output)" + } + return text + } + cut := len(text) - limit + for cut < len(text) && !utf8.RuneStart(text[cut]) { + cut++ + } + return "[...]\n" + text[cut:] +} + +// headTailBuffer keeps the first head bytes and the last limit-head bytes of a +// stream: compiler errors come first, test summaries last. +type headTailBuffer struct { + head, limit int + first bytes.Buffer + tail []byte + dropped int64 +} + +func (b *headTailBuffer) Write(p []byte) (int, error) { + n := len(p) + if room := b.head - b.first.Len(); room > 0 { + take := min(room, len(p)) + b.first.Write(p[:take]) + p = p[take:] + } + if len(p) == 0 { + return n, nil + } + keep := b.limit - b.head + b.tail = append(b.tail, p...) + if over := len(b.tail) - keep; over > 0 { + b.dropped += int64(over) + b.tail = append(b.tail[:0], b.tail[over:]...) + } + return n, nil +} + +// String returns the retained text and whether anything was dropped. +func (b *headTailBuffer) String() (string, bool) { + if b.dropped == 0 { + return strings.ToValidUTF8(strings.TrimRight(b.first.String()+string(b.tail), "\n"), "\uFFFD"), false + } + tail := b.tail + for len(tail) > 0 && !utf8.RuneStart(tail[0]) { + tail = tail[1:] + } + text := b.first.String() + fmt.Sprintf("\n[... %d bytes omitted ...]\n", b.dropped) + string(tail) + return strings.ToValidUTF8(strings.TrimRight(text, "\n"), "\uFFFD"), true +} diff --git a/internal/stage/check_test.go b/internal/stage/check_test.go new file mode 100644 index 00000000..d4000960 --- /dev/null +++ b/internal/stage/check_test.go @@ -0,0 +1,159 @@ +package stage + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func checkDefinition(t *testing.T, commands string, configs map[string]string) Definition { + t.Helper() + if configs == nil { + configs = map[string]string{} + } + return Definition{Key: "verify", Type: CheckType, Workspace: t.TempDir(), + Blocks: map[string]string{"commands": commands, "configs": "type=check", "edges": "x"}, + Configs: configs, + Edges: map[string]string{"pass": "review", "fail": "implement", "error": "#failure"}} +} + +func TestCheckStageValidation(t *testing.T) { + def := checkDefinition(t, "# lint first\ngo vet ./...\n\ngo test ./...", map[string]string{"command_timeout": "5m", "keep_going": "true", "timeout": "20m", "delivery": "true"}) + spec, err := CheckStageSpec(def) + if err != nil { + t.Fatal(err) + } + if len(spec.Commands) != 2 || spec.CommandTimeout != 5*time.Minute || spec.Timeout != 20*time.Minute || !spec.KeepGoing || !spec.Delivery { + t.Fatalf("spec %+v", spec) + } + if err := DefaultRegistry().Validate(def); err != nil { + t.Fatal("registry:", err) + } + if enabled, err := DeliveryEnabled(def); err != nil || !enabled { + t.Fatal("delivery check", enabled, err) + } + for name, change := range map[string]func(*Definition){ + "no commands": func(d *Definition) { d.Blocks["commands"] = "# only a comment\n" }, + "too many": func(d *Definition) { d.Blocks["commands"] = strings.Repeat("true\n", 21) }, + "prompt block": func(d *Definition) { d.Blocks["prompt"] = "Run the tests." }, + "tools block": func(d *Definition) { d.Blocks["tools"] = "shell" }, + "skills block": func(d *Definition) { d.Blocks["skills"] = "x" }, + "unknown config": func(d *Definition) { d.Configs["model"] = "x" }, + "bad timeout": func(d *Definition) { d.Configs["command_timeout"] = "soon" }, + "bad keep_going": func(d *Definition) { d.Configs["keep_going"] = "yes" }, + "bad delivery": func(d *Definition) { d.Configs["delivery"] = "false" }, + "missing fail": func(d *Definition) { delete(d.Edges, "fail") }, + "missing pass": func(d *Definition) { delete(d.Edges, "pass") }, + "success outcome": func(d *Definition) { d.Edges["success"] = "#success" }, + } { + t.Run(name, func(t *testing.T) { + copy := def + copy.Blocks, copy.Configs, copy.Edges = map[string]string{}, map[string]string{}, map[string]string{} + for k, v := range def.Blocks { + copy.Blocks[k] = v + } + for k, v := range def.Configs { + copy.Configs[k] = v + } + for k, v := range def.Edges { + copy.Edges[k] = v + } + change(©) + if err := (CheckStage{}).Validate(copy); err == nil { + t.Fatal("accepted") + } + }) + } +} + +func TestCheckStageRunsCommandsInTheWorkspace(t *testing.T) { + def := checkDefinition(t, "pwd > where.txt\necho all good", nil) + result, err := DefaultRegistry().Run(context.Background(), def, Values{}) + if err != nil { + t.Fatal(err) + } + if result.Outcome != CheckPass { + t.Fatalf("outcome %q: %v", result.Outcome, result.Output) + } + where, _ := os.ReadFile(filepath.Join(def.Workspace, "where.txt")) + real, _ := filepath.EvalSymlinks(def.Workspace) + if got := strings.TrimSpace(string(where)); got != def.Workspace && got != real { + t.Fatalf("ran in %q, want %q", got, def.Workspace) + } + if result.Output["summary"] != "2 checks passed." { + t.Fatal("summary", result.Output["summary"]) + } + checks := result.Output["checks"].([]any) + if len(checks) != 2 || checks[1].(map[string]any)["output"] != "all good" { + t.Fatalf("checks %v", checks) + } +} + +func TestCheckStageFailureIsTheHandoff(t *testing.T) { + def := checkDefinition(t, "echo compiling\necho 'FAIL: TestParse expected 2' >&2; exit 3\necho never", nil) + result, err := (CheckStage{}).Run(context.Background(), def, nil) + if err != nil { + t.Fatal(err) + } + if result.Outcome != CheckFail { + t.Fatalf("outcome %q", result.Outcome) + } + markdown := result.Output["markdown"].(string) + handoff := markdown[strings.Index(markdown, "# handoff"):strings.Index(markdown, "## Commands")] + for _, want := range []string{"1 of 3 checks failed", "exit code 3", "FAIL: TestParse expected 2"} { + if !strings.Contains(handoff, want) { + t.Fatalf("handoff lacks %q:\n%s", want, handoff) + } + } + if !strings.HasPrefix(markdown, "# outcome\n\nfail\n") { + t.Fatalf("markdown does not start with the outcome:\n%s", markdown) + } + checks := result.Output["checks"].([]any) + if checks[2].(map[string]any)["status"] != CheckStatusNotRun { + t.Fatal("a later check ran after a failure", checks[2]) + } + // keep_going runs every command and reports each failure. + def.Configs["keep_going"] = "true" + def.Blocks["commands"] = "exit 1\nexit 2\ntrue" + result, _ = (CheckStage{}).Run(context.Background(), def, nil) + if result.Output["summary"] != "2 of 3 checks failed: exit 1; exit 2" { + t.Fatal(result.Output["summary"]) + } +} + +func TestCheckStageCommandTimeoutKillsTheProcessGroup(t *testing.T) { + def := checkDefinition(t, "sleep 30 & echo started; wait", map[string]string{"command_timeout": "300ms"}) + started := time.Now() + result, err := (CheckStage{}).Run(context.Background(), def, nil) + if err != nil { + t.Fatal(err) + } + if time.Since(started) > 10*time.Second { + t.Fatal("timeout did not stop the command", time.Since(started)) + } + check := result.Output["checks"].([]any)[0].(map[string]any) + if result.Outcome != CheckFail || check["status"] != CheckStatusTimedOut || !strings.Contains(check["output"].(string), "command_timeout") { + t.Fatalf("result %v", check) + } +} + +func TestCheckOutputIsBoundedHeadAndTail(t *testing.T) { + buffer := &headTailBuffer{head: 10, limit: 30} + for i := 0; i < 100; i++ { + _, _ = buffer.Write([]byte("0123456789")) + } + _, _ = buffer.Write([]byte("THE-END")) + text, truncated := buffer.String() + if !truncated || !strings.HasPrefix(text, "0123456789") || !strings.HasSuffix(text, "THE-END") || len(text) > 80 { + t.Fatalf("%v %q", truncated, text) + } + def := checkDefinition(t, "head -c 300000 /dev/zero | tr '\\0' x; echo; echo TAIL; exit 1", nil) + result, _ := (CheckStage{}).Run(context.Background(), def, nil) + check := result.Output["checks"].([]any)[0].(map[string]any) + if output := check["output"].(string); len(output) > maxCheckOutputBytes+200 || !strings.HasSuffix(output, "TAIL") || check["truncated"] != true { + t.Fatalf("output %d bytes, truncated %v", len(output), check["truncated"]) + } +} diff --git a/internal/stage/claude_stage.go b/internal/stage/claude_stage.go index 6d659863..c17839b6 100644 --- a/internal/stage/claude_stage.go +++ b/internal/stage/claude_stage.go @@ -131,7 +131,10 @@ func claudeMCPAllowRules(tools []string) ([]string, error) { // approved only below the run directory and the stage's artifacts directory; // everything else a declared tool does not need approval for stays denied by // dontAsk. -func claudeAllowRules(tools []string, directory, artifactsDir string) []string { +// +// A non-nil shell allow-list replaces the bare Bash rule with one Bash(...) +// rule per permitted command, so any other command is refused. +func claudeAllowRules(tools []string, directory, artifactsDir string, shell []string) []string { rules := []string{} edit := false for _, tool := range tools { @@ -139,6 +142,12 @@ func claudeAllowRules(tools []string, directory, artifactsDir string) []string { case "Edit": edit = true case "Write": + case "Bash": + if shell != nil { + rules = append(rules, claudeShellRules(shell)...) + } else { + rules = append(rules, tool) + } default: rules = append(rules, tool) } @@ -160,7 +169,7 @@ func (c *ClaudeStageClient) args(config ModelConfig, tools []string, effort stri // skills block) may be loaded. A skill only adds instructions; the declared // tools and their rules still bound what the session can do. tools = append(append([]string(nil), tools...), "Skill") - rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir) + rules := claudeAllowRules(tools, c.Directory, c.ArtifactsDir, c.Policy.Shell) args := []string{"-p", "--output-format", "stream-json", "--verbose", "--model", config.Model, "--permission-mode", "dontAsk", @@ -212,10 +221,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr if effort == "none" || effort == "minimal" { return "", fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max") } - if len(c.WritePaths) > 0 || c.Policy.Edit != nil || c.Policy.Shell != nil { + if len(c.WritePaths) > 0 || c.Policy.Edit != nil { // The other harnesses enforce these narrower scopes themselves. Claude - // Code's rule syntax is not audited for them, so refuse, never widen. - return "", fmt.Errorf("the claude harness cannot enforce a permissions block or a narrowed write scope; use the opencode harness for this stage") + // Code's edit-path rules are not audited for them, so refuse, never + // widen. A shell allow-list is enforced with Bash(...) rules. + return "", fmt.Errorf("the claude harness cannot enforce permissions.edit or a narrowed write scope; use the opencode harness for this stage") } tools, err := claudeTools(c.Tools) if err != nil { @@ -272,6 +282,11 @@ func (c *ClaudeStageClient) Generate(ctx context.Context, config ModelConfig, pr } owned = true } + if c.Policy.Shell != nil { + // The allow-list is enforced by Bash(...) rules; say it up front so the + // session does not spend turns on refused commands. + prompt += "\nPermitted shell commands (a trailing * allows any arguments; anything else is refused): " + strings.Join(c.Policy.Shell, "; ") + } if text, err = c.run(ctx, env, c.args(config, tools, effort, false), config.Model, prompt); err != nil { return "", err } @@ -327,6 +342,17 @@ func claudeStageEnvironment(inherited []string, artifactsDir string) []string { // claudeConfigDir is the Claude Code configuration directory the stage's CLI // will use: the environment's CLAUDE_CONFIG_DIR, else $HOME/.claude. +// HarnessStateDirs are directories a harness itself writes during a visit +// (Claude Code's config directory: session state, caches) for the given +// environment. When one lives inside the run directory its changes are the +// harness's, not the stage's. +func HarnessStateDirs(env []string) []string { + if dir := claudeConfigDir(env); dir != "" { + return []string{filepath.Clean(dir)} + } + return nil +} + func claudeConfigDir(env []string) string { lookup := func(name string) string { for i := len(env) - 1; i >= 0; i-- { diff --git a/internal/stage/claude_stage_test.go b/internal/stage/claude_stage_test.go index c7f247bf..104dcad8 100644 --- a/internal/stage/claude_stage_test.go +++ b/internal/stage/claude_stage_test.go @@ -228,6 +228,74 @@ func TestClaudeStageDeclaredToolsAreTheOnlyTools(t *testing.T) { } } +// A shell allow-list replaces the bare Bash rule: only the listed commands +// (exact, or a prefix with any arguments) are approved under dontAsk. +func TestClaudeStageShellAllowListMapsToBashRules(t *testing.T) { + client, root, _ := fakeClaudeClient(t, "success") + client.Tools = []string{"read", "shell"} + client.Policy.Shell = []string{"go test ./...", "git diff *"} + if _, err := client.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { + t.Fatal(err) + } + calls := fakeClaudeArgs(t, root) + if len(calls) != 1 { + t.Fatal(calls) + } + args := calls[0] + for _, want := range []string{"Read,Bash,Skill", "Bash(go test ./...)", "Bash(git diff:*)"} { + if !slices.Contains(args, want) { + t.Fatalf("missing %q in args %q", want, args) + } + } + if slices.Contains(args, "Bash") { + t.Fatalf("a bare Bash rule approves every command: %q", args) + } + prompt, _ := os.ReadFile(filepath.Join(root, "prompt")) + if !strings.Contains(string(prompt), "Permitted shell commands") || !strings.Contains(string(prompt), "git diff *") { + t.Fatalf("prompt does not name the allow-list: %q", prompt) + } + // An empty list approves no command at all. + client2, root2, _ := fakeClaudeClient(t, "success") + client2.Tools = []string{"shell"} + client2.Policy.Shell = []string{} + if _, err := client2.Generate(context.Background(), claudeConfig(nil), "task"); err != nil { + t.Fatal(err) + } + for _, arg := range fakeClaudeArgs(t, root2)[0] { + if strings.HasPrefix(arg, "Bash") && arg != "Bash,Skill" { + t.Fatalf("empty allow-list approved %q", arg) + } + } +} + +func TestClaudeStagePermissionsValidation(t *testing.T) { + def := func(permissions string) Definition { + return Definition{Key: "review", Type: ModelType, + Blocks: map[string]string{"prompt": "Review.", "configs": "x", "tools": "read\nshell", "permissions": permissions}, + Configs: map[string]string{"harness": "claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, + Edges: map[string]string{"success": "#success"}} + } + if _, err := (ModelStage{}).Spec(def(`{"shell":["git diff *","go test ./..."]}`)); err != nil { + t.Fatal("shell allow-list rejected:", err) + } + for name, permissions := range map[string]string{ + "edit": `{"edit":["a.go"],"shell":[]}`, + "chaining": `{"shell":["go test && rm x"]}`, + "mid star": `{"shell":["git * diff"]}`, + "parentheses": `{"shell":["echo (x)"]}`, + } { + if _, err := (ModelStage{}).Spec(def(permissions)); err == nil { + t.Fatal(name, "accepted") + } + } + // Prefix entries are claude-only: other harnesses enforce exact commands. + opencode := def(`{"shell":["git diff *"]}`) + opencode.Configs = map[string]string{"provider": "opencode-go", "model": "deepseek-v4.1-flash"} + if _, err := (ModelStage{}).Spec(opencode); err == nil || !strings.Contains(err.Error(), "claude harness") { + t.Fatal("opencode prefix permission:", err) + } +} + func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) { client, root, _ := fakeClaudeClient(t, "success") client.Tools = []string{"read", "mcp:ai-memory", "mcp:linear/list_issues"} @@ -254,12 +322,11 @@ func TestClaudeStageNamedMCPToolsAreAllowlistedSeparately(t *testing.T) { func TestClaudeStageRefusesWhatItCannotEnforce(t *testing.T) { for name, change := range map[string]func(*ClaudeStageClient, *ModelConfig){ - "write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} }, - "edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} }, - "shell permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Shell = []string{"go test"} }, - "unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} }, - "other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" }, - "no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" }, + "write paths": func(c *ClaudeStageClient, _ *ModelConfig) { c.WritePaths = []string{"app"} }, + "edit permissions": func(c *ClaudeStageClient, _ *ModelConfig) { c.Policy.Edit = []string{"app/**"} }, + "unknown tool": func(c *ClaudeStageClient, _ *ModelConfig) { c.Tools = []string{"browser"} }, + "other provider": func(_ *ClaudeStageClient, m *ModelConfig) { m.Provider = "opencode-go" }, + "no reasoning": func(_ *ClaudeStageClient, m *ModelConfig) { m.ReasoningEffort = "none" }, } { t.Run(name, func(t *testing.T) { client, root, active := fakeClaudeClient(t, "success") @@ -326,7 +393,8 @@ func TestClaudeStageBudgetAccounting(t *testing.T) { func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) { client, root, _ := fakeClaudeClient(t, "repair") budget := NewBudget(0, 1000) - ctx := withOutputRepair(context.Background(), []string{"error", "success"}) + counter := &RepairCounter{} + ctx := withOutputRepair(WithRepairCounter(context.Background(), counter), []string{"error", "success"}) text, err := client.Generate(ctx, claudeConfig(budget), "task") if err != nil || !strings.HasPrefix(text, "# outcome\nsuccess\n") || !strings.Contains(text, "Report kept.") { t.Fatalf("%q %v", text, err) @@ -339,6 +407,9 @@ func TestClaudeStageOutcomeRepairResumesTheSameSession(t *testing.T) { if budget.Snapshot().UsedTokens != 34 { t.Fatalf("usage %+v", budget.Snapshot()) } + if counter.Count() != 1 { + t.Fatalf("repair follow-ups counted %d, want 1", counter.Count()) + } } func TestClaudeStageTimeoutStopsTheProcessGroup(t *testing.T) { @@ -395,7 +466,6 @@ func TestClaudeHarnessValidation(t *testing.T) { "unknown harness": definition(map[string]string{"harness": "codex", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil), "capitalised": definition(map[string]string{"harness": "Claude", "provider": "anthropic", "model": "claude-haiku-5-5"}, nil), "other provider": definition(claude(map[string]string{"provider": "opencode-go"}), nil), - "delivery": definition(claude(map[string]string{"delivery": "true"}), nil), "permissions block": definition(claude(nil), map[string]string{"permissions": `{"edit":["app/**"]}`}), "no reasoning": definition(claude(map[string]string{"reasoning_effort": "none"}), nil), } { diff --git a/internal/stage/model.go b/internal/stage/model.go index 78356b72..49f173a9 100644 --- a/internal/stage/model.go +++ b/internal/stage/model.go @@ -84,7 +84,7 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { } for key := range def.Configs { switch key { - case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip": + case "provider", "model", "reasoning_effort", "retries", "timeout", "budget_usd", "budget_tokens", "harness", "delivery", "auto_skip", "allow_workspace_changes": default: return ModelSpec{}, fmt.Errorf("unknown config %q", key) } @@ -111,8 +111,10 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { if value := def.Configs["auto_skip"]; value != "" && value != "true" && value != "false" { return ModelSpec{}, fmt.Errorf("auto_skip must be true or false") } - if def.Configs["delivery"] == "true" && backend != "opencode" { - return ModelSpec{}, fmt.Errorf("delivery is supported only by the opencode harness") + // allow_workspace_changes=true lets a stage without edit leave file changes + // in the run directory; by default the runner fails such a visit. + if value := def.Configs["allow_workspace_changes"]; value != "" && value != "true" && value != "false" { + return ModelSpec{}, fmt.Errorf("allow_workspace_changes must be true or false") } if err := ValidateChecksBlock(def); err != nil { return ModelSpec{}, err @@ -143,8 +145,8 @@ func (ModelStage) Spec(def Definition) (ModelSpec, error) { if _, err := claudeTools(tools); err != nil { return ModelSpec{}, err } - if _, present := def.Blocks["permissions"]; present { - return ModelSpec{}, fmt.Errorf("the claude harness cannot enforce a permissions block; use the opencode harness for this stage") + if err := claudePermissionsSupported(def); err != nil { + return ModelSpec{}, err } if effort == "none" || effort == "minimal" { return ModelSpec{}, fmt.Errorf("the claude harness supports reasoning_effort low, medium, high, xhigh or max") diff --git a/internal/stage/model_repair.go b/internal/stage/model_repair.go index db75e888..84181fd9 100644 --- a/internal/stage/model_repair.go +++ b/internal/stage/model_repair.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strings" + "sync/atomic" "git.a-wan.net/alan/pipelines/internal/turn" ) @@ -13,14 +14,38 @@ import ( // message in the same session asking only for the outcome, instead of failing // a stage whose admitted work a full retry would repeat. The outcome is always // stated by the model; the server never infers one from prose. -type outputRepair struct{ outcomes []string } +type outputRepair struct { + outcomes []string + counter *RepairCounter +} type outputRepairKey struct{} +type repairCounterKey struct{} + +// RepairCounter counts the outcome repair follow-ups sent during one visit +// (across its attempts). The runner records the count on the step. +type RepairCounter struct{ n atomic.Int32 } + +// Count is the number of follow-ups sent so far. +func (c *RepairCounter) Count() int { + if c == nil { + return 0 + } + return int(c.n.Load()) +} + +// WithRepairCounter makes every outcome repair follow-up under ctx increment +// counter. +func WithRepairCounter(ctx context.Context, counter *RepairCounter) context.Context { + return context.WithValue(ctx, repairCounterKey{}, counter) +} + // withOutputRepair lets a model client repair a missing or invalid outcome // for the given declared outcomes while its session is still open. func withOutputRepair(ctx context.Context, outcomes []string) context.Context { - return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes}) + counter, _ := ctx.Value(repairCounterKey{}).(*RepairCounter) + return context.WithValue(ctx, outputRepairKey{}, &outputRepair{outcomes: outcomes, counter: counter}) } // outputRepairFrom returns the attempt's repair, or nil when none applies. @@ -40,6 +65,9 @@ func (r *outputRepair) followUp(text string) (string, bool) { if !errors.Is(err, turn.ErrMissingOutcome) && !errors.Is(err, turn.ErrOutcomeNotAllowed) && !errors.Is(err, turn.ErrDuplicateOutcome) { return "", false } + if r.counter != nil { + r.counter.n.Add(1) + } allowed := strings.Join(r.outcomes, ", ") return "Your final message has no valid `# outcome` section. Do not redo any work or repeat your report; the server keeps it. " + outputShape(r.outcomes) + " Reply with only these two lines:\n\n# outcome\n\n", true diff --git a/internal/stage/permissions.go b/internal/stage/permissions.go index 7713ec5f..ff4a64ba 100644 --- a/internal/stage/permissions.go +++ b/internal/stage/permissions.go @@ -77,9 +77,17 @@ func StagePermissions(def Definition) (ToolPolicy, error) { seen[pattern] = true } seen = map[string]bool{} + claude := def.Configs["harness"] == ClaudeBackend for _, command := range policy.Shell { - if command == "" || strings.TrimSpace(command) != command || strings.ContainsAny(command, "*?;|&<>`$\r\n\\") { - return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands without wildcards, chaining, redirects, or expansion") + exact, prefix := ShellPermissionPrefix(command) + if prefix && !claude { + return ToolPolicy{}, fmt.Errorf("shell prefix permissions (%q) are supported only by the claude harness; list exact commands", command) + } + if exact == "" || strings.TrimSpace(exact) != exact || strings.ContainsAny(exact, "*?;|&<>`$\r\n\\") { + return ToolPolicy{}, fmt.Errorf("shell permissions must be exact commands (or, on the claude harness, a command prefix ending in \" *\") without other wildcards, chaining, redirects, or expansion") + } + if claude && strings.ContainsAny(exact, "()") { + return ToolPolicy{}, fmt.Errorf("claude shell permissions cannot contain parentheses") } if seen[command] { return ToolPolicy{}, fmt.Errorf("duplicate shell permission") @@ -92,3 +100,45 @@ func StagePermissions(def Definition) (ToolPolicy, error) { } return *policy, nil } + +// ShellPermissionPrefix splits a permissions.shell entry. "go test *" is a +// prefix entry (the command with any arguments; claude harness only) and +// returns ("go test", true); any other entry is an exact command. +func ShellPermissionPrefix(entry string) (string, bool) { + if base, ok := strings.CutSuffix(entry, " *"); ok { + return base, true + } + return entry, false +} + +// claudePermissionsSupported limits a claude stage's permissions block to a +// shell allow-list (mapped to Bash(...) rules). Claude Code's edit-path rules +// are not audited, so restricted edits stay with the other harnesses. +func claudePermissionsSupported(def Definition) error { + if _, present := def.Blocks["permissions"]; !present { + return nil + } + policy, err := StagePermissions(def) + if err != nil { + return err + } + if policy.Edit != nil { + return fmt.Errorf("the claude harness enforces only permissions.shell; remove permissions.edit or use the opencode harness for this stage") + } + return nil +} + +// claudeShellRules maps a shell allow-list to Claude Code permission rules: +// an exact command to Bash(command) and a prefix entry to Bash(prefix:*). +// Claude Code checks each part of a chained command against the rules. +func claudeShellRules(shell []string) []string { + rules := make([]string, 0, len(shell)) + for _, entry := range shell { + if base, prefix := ShellPermissionPrefix(entry); prefix { + rules = append(rules, "Bash("+base+":*)") + } else { + rules = append(rules, "Bash("+base+")") + } + } + return rules +} diff --git a/internal/stage/stage.go b/internal/stage/stage.go index 0dc747a2..655f1fbd 100644 --- a/internal/stage/stage.go +++ b/internal/stage/stage.go @@ -33,7 +33,10 @@ type Definition struct { // ArtifactsDir is the per-run/step directory the runtime created for this // visit; empty when the runner did not provide one (for example in tests). ArtifactsDir string - Turn TurnPaths + // Workspace is the run directory (runtime-provided); a check stage runs + // its commands there. + Workspace string + Turn TurnPaths // Skills is the visit's materialised skills block (runtime-provided, like // ArtifactsDir); nil when the stage configures none or in tests. Skills *SkillSet @@ -72,7 +75,7 @@ func NewRegistry(types map[string]Stage) *Registry { } func DefaultRegistry() *Registry { - return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}}) + return NewRegistry(map[string]Stage{ModelType: ModelStage{}, NtfyType: NtfyStage{}, HumanType: HumanStage{}, CheckType: CheckStage{}}) } func EffectiveType(name string) string { diff --git a/internal/stage/tools.go b/internal/stage/tools.go index e935d2c3..30b496b5 100644 --- a/internal/stage/tools.go +++ b/internal/stage/tools.go @@ -40,8 +40,9 @@ func (a LandingAccess) valid() bool { } // DeliveryEnabled is the narrow, declarative capability check used before the -// runner supplies any landing paths. Only a validated model definition can ask -// for it; runtime paths are still derived by the server. +// runner supplies any landing paths. Only a validated model or check +// definition can ask for it, whatever its harness; runtime paths are still +// derived by the server. func DeliveryEnabled(def Definition) (bool, error) { delivery := def.Configs["delivery"] if delivery == "" { @@ -50,8 +51,14 @@ func DeliveryEnabled(def Definition) (bool, error) { if delivery != "true" { return false, fmt.Errorf("delivery must be true when set") } + if EffectiveType(def.Type) == CheckType { + if _, err := CheckStageSpec(def); err != nil { + return false, fmt.Errorf("invalid delivery check stage: %w", err) + } + return true, nil + } if EffectiveType(def.Type) != ModelType { - return false, fmt.Errorf("delivery is supported only by model stages") + return false, fmt.Errorf("delivery is supported only by model and check stages") } if _, err := (ModelStage{}).Spec(def); err != nil { return false, fmt.Errorf("invalid delivery model stage: %w", err) diff --git a/internal/stage/tools_test.go b/internal/stage/tools_test.go index 210af862..3fdd3576 100644 --- a/internal/stage/tools_test.go +++ b/internal/stage/tools_test.go @@ -246,18 +246,27 @@ func TestDeliveryEnabledRequiresValidatedModelStage(t *testing.T) { } } -func TestDeliveryRejectsPiBeforeAgentExecution(t *testing.T) { +func TestDeliveryIsHarnessAgnostic(t *testing.T) { + for _, harness := range []string{"opencode", "pi"} { + def := modelDefinition() + def.Configs["delivery"] = "true" + def.Configs["harness"] = harness + def.Blocks["checks"] = "go test ./..." + if err := (ModelStage{}).Validate(def); err != nil { + t.Fatalf("%s delivery was rejected: %v", harness, err) + } + if enabled, err := DeliveryEnabled(def); err != nil || !enabled { + t.Fatalf("%s delivery = %v, %v", harness, enabled, err) + } + } def := modelDefinition() def.Configs["delivery"] = "true" - def.Configs["harness"] = "pi" - def.Blocks["checks"] = "true" - if err := (ModelStage{}).Validate(def); err == nil || !strings.Contains(err.Error(), "opencode harness") { - t.Fatal("Pi delivery was accepted", err) - } - delete(def.Configs, "delivery") - delete(def.Blocks, "checks") - if err := (ModelStage{}).Validate(def); err != nil { - t.Fatal("Pi non-delivery was changed", err) + def.Configs["harness"] = ClaudeBackend + def.Configs["provider"] = ClaudeProvider + def.Configs["model"] = "claude-sonnet-4-5" + def.Blocks["checks"] = "go test ./..." + if enabled, err := DeliveryEnabled(def); err != nil || !enabled { + t.Fatalf("claude delivery = %v, %v", enabled, err) } } From 8138cdc3d9a63f7589f41f5763793172ab15a950 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 12:54:18 +0000 Subject: [PATCH 3/6] Linux desktop: optimized release build, installer, Linux gaps Build: split Dart debug info out of libapp.so (13.96 -> 11.27 MB, symbols kept in the cache) and fix icon tree shaking, which Flutter 3.44's Linux CMake backend silently disables by quoting the define; the build image patches its SDK copy (MaterialIcons 1.6 MB -> 25 KB). Impeller cannot be enabled in a Linux release build and was slower in a profile-build bench. Install: `./install --linux --install` installs the bundle into /lib/app-linux with com.pipelines.app.desktop (the GTK/Wayland app id), its icon and a ~/.local/bin/pipelines-app link, through scripts/install-linux-app.sh. Linux gaps: notifications through the freedesktop daemon; HTML artifacts explain the missing web view instead of throwing; no Share for files; a GTK clipboard reader for pasting files and screenshots (Ctrl+V and Omarchy's Super+V); GTK header bar only on GNOME; window icon. Bench: native fixture frame log, wheel/mark steps and tool/perf/linux_desktop_bench.py (private Xvfb); results in app/notes/linux-desktop-optimized.md. Co-Authored-By: Claude Opus 5.5 --- app/docker/Dockerfile | 8 ++ app/docker/build.sh | 6 +- .../actions/artifact_transfer_io.dart | 13 +- .../ui/artifact_html_view_native.dart | 33 ++++- .../notify/notification_bridge_io.dart | 31 +++- .../domain/chat_clipboard_paste_native.dart | 22 +-- .../domain/chat_clipboard_paste_stub.dart | 2 +- app/linux/CMakeLists.txt | 5 + app/linux/runner/CMakeLists.txt | 1 + app/linux/runner/clipboard_files.cc | 135 ++++++++++++++++++ app/linux/runner/clipboard_files.h | 12 ++ app/linux/runner/my_application.cc | 34 +++-- app/linux/runner/resources/app_icon.png | Bin 0 -> 73827 bytes app/notes/linux-desktop-optimized.md | 69 +++++++++ .../ui/artifact_linux_capabilities_test.dart | 53 +++++++ .../chat_composer_injected_paste_test.dart | 9 ++ .../chat_clipboard_paste_native_test.dart | 48 ++++++- .../fixture_host/fixture_host_native.dart | 7 +- app/tool/fixture_host/fixture_steps.dart | 25 +++- app/tool/perf/frame_log_native.dart | 28 ++++ app/tool/perf/linux_desktop_bench.py | 102 +++++++++++++ docs/install.md | 20 +++ scripts/app_build.py | 5 +- scripts/app_desktop_build.py | 23 ++- scripts/install-linux-app.sh | 46 +++--- scripts/test_app_desktop_build.py | 45 ++++++ 26 files changed, 722 insertions(+), 60 deletions(-) create mode 100644 app/linux/runner/clipboard_files.cc create mode 100644 app/linux/runner/clipboard_files.h create mode 100644 app/linux/runner/resources/app_icon.png create mode 100644 app/notes/linux-desktop-optimized.md create mode 100644 app/test/features/artifacts/ui/artifact_linux_capabilities_test.dart create mode 100644 app/tool/perf/frame_log_native.dart create mode 100644 app/tool/perf/linux_desktop_bench.py diff --git a/app/docker/Dockerfile b/app/docker/Dockerfile index 8b3cf479..44b1f602 100644 --- a/app/docker/Dockerfile +++ b/app/docker/Dockerfile @@ -24,10 +24,18 @@ COPY --chmod=0755 build.sh /usr/local/bin/pipelines-app-build WORKDIR /tmp 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 \ && 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/* \ && 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 FROM web AS android diff --git a/app/docker/build.sh b/app/docker/build.sh index 8f30af2d..11e2b78f 100755 --- a/app/docker/build.sh +++ b/app/docker/build.sh @@ -42,8 +42,12 @@ PROPERTIES /tmp/apk-certificates.txt > /out/signing-certificate-sha256.txt ;; linux) - flutter build linux --release "$@" + # Dart symbols go beside the bundle, not into libapp.so (about 18% + # smaller); `flutter symbolize -i -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 /tmp/debug-info /out/.debug-info ;; *) echo "unknown build: $kind" >&2 diff --git a/app/lib/features/artifacts/actions/artifact_transfer_io.dart b/app/lib/features/artifacts/actions/artifact_transfer_io.dart index 5fb3ccb9..52b57b13 100644 --- a/app/lib/features/artifacts/actions/artifact_transfer_io.dart +++ b/app/lib/features/artifacts/actions/artifact_transfer_io.dart @@ -1,18 +1,25 @@ import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; import 'package:share_plus/share_plus.dart'; import 'artifact_file.dart'; import 'artifact_transfer.dart'; /// 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 artifactShareSupported => true; +bool get artifactShareSupported => + defaultTargetPlatform != TargetPlatform.linux; String get artifactDownloadUnsupportedMessage => ''; -String get artifactShareUnsupportedMessage => ''; +String get artifactShareUnsupportedMessage => + defaultTargetPlatform == TargetPlatform.linux + ? 'Sharing files is not available on Linux; use Download.' + : ''; Future saveArtifactFile(ArtifactFile file) async { try { diff --git a/app/lib/features/artifacts/ui/artifact_html_view_native.dart b/app/lib/features/artifacts/ui/artifact_html_view_native.dart index fd61d5fe..cdf62172 100644 --- a/app/lib/features/artifacts/ui/artifact_html_view_native.dart +++ b/app/lib/features/artifacts/ui/artifact_html_view_native.dart @@ -12,6 +12,18 @@ import 'artifact_external_open.dart'; /// the full-screen view needs no zoom buttons. 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 /// recorded document itself loads. /// @@ -99,6 +111,7 @@ class _InertHtmlViewState extends State { @override void didUpdateWidget(covariant InertHtmlView oldWidget) { super.didUpdateWidget(oldWidget); + if (!inertHtmlViewSupported()) return; if (oldWidget.html != widget.html || oldWidget.dark != widget.dark) { _loaded = false; _controller.loadHtmlString(_document); @@ -106,8 +119,20 @@ class _InertHtmlViewState extends State { } @override - Widget build(BuildContext context) => WebViewWidget( - controller: _controller, - gestureRecognizers: widget.interactive ? _allGestures : _inlineGestures, - ); + Widget build(BuildContext context) => inertHtmlViewSupported() + ? WebViewWidget( + controller: _controller, + gestureRecognizers: widget.interactive + ? _allGestures + : _inlineGestures, + ) + : const Center( + child: Padding( + padding: EdgeInsets.all(16), + child: Text( + inertHtmlUnsupportedMessage, + textAlign: TextAlign.center, + ), + ), + ); } diff --git a/app/lib/features/attention/notify/notification_bridge_io.dart b/app/lib/features/attention/notify/notification_bridge_io.dart index 696df157..6c35f865 100644 --- a/app/lib/features/attention/notify/notification_bridge_io.dart +++ b/app/lib/features/attention/notify/notification_bridge_io.dart @@ -1,5 +1,6 @@ import 'dart:io'; +import 'package:flutter/foundation.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'notification_bridge.dart'; @@ -7,8 +8,10 @@ import 'notification_models.dart'; /// System notifications from the native app: Android's notification shade (when /// 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 -/// is refreshed when the bridge starts and after every request. +/// notification centre, and the Linux desktop's notification daemon (the +/// 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 { NativeNotificationBridge() { _ready = _start(); @@ -40,13 +43,27 @@ class NativeNotificationBridge implements NotificationBridge { 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 _start() async { try { await _plugin.initialize( - settings: const InitializationSettings( + settings: InitializationSettings( android: AndroidInitializationSettings('@mipmap/ic_launcher'), iOS: _darwin, macOS: _darwin, + linux: _linuxSettings, ), onDidReceiveNotificationResponse: (response) { final id = response.id; @@ -63,7 +80,10 @@ class NativeNotificationBridge implements NotificationBridge { } Future _refresh() async { - if (Platform.isAndroid) { + if (_linux) { + // A notification daemon asks no permission. + _permission = 'granted'; + } else if (Platform.isAndroid) { final enabled = await _plugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin @@ -82,7 +102,8 @@ class NativeNotificationBridge implements NotificationBridge { @override 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. secureContext: true, permission: _permission, diff --git a/app/lib/features/chat/domain/chat_clipboard_paste_native.dart b/app/lib/features/chat/domain/chat_clipboard_paste_native.dart index 786469a1..ac93aa3d 100644 --- a/app/lib/features/chat/domain/chat_clipboard_paste_native.dart +++ b/app/lib/features/chat/domain/chat_clipboard_paste_native.dart @@ -7,7 +7,9 @@ import 'package:flutter/widgets.dart'; import 'chat_attachment_picker.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( 'pipelines/clipboard_files', ); @@ -17,7 +19,7 @@ const MethodChannel chatClipboardFilesChannel = MethodChannel( /// /// Flutter's own [Clipboard] carries text only, so a native host reads the /// 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 /// 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 @@ -46,13 +48,14 @@ ChatClipboardPaste nativeChatClipboardPaste({ ); /// Whether the held modifiers make V the host's paste shortcut: Cmd alone on -/// macOS. -bool chatIsNativePasteShortcut() { +/// macOS; Ctrl on Linux, also with Super held (Omarchy's universal Super+V +/// sends Ctrl+V while Super is down). +bool chatIsNativePasteShortcut([TargetPlatform? platform]) { final keys = HardwareKeyboard.instance; - return keys.isMetaPressed && - !keys.isControlPressed && - !keys.isAltPressed && - !keys.isShiftPressed; + if (keys.isAltPressed || keys.isShiftPressed) return false; + return (platform ?? defaultTargetPlatform) == TargetPlatform.linux + ? keys.isControlPressed + : keys.isMetaPressed && !keys.isControlPressed; } Future _readPasteboard( @@ -121,4 +124,5 @@ String chatNothingToPasteMessage(List types) => types.isEmpty /// Whether [platform] has a Runner that answers [chatClipboardFilesChannel]. bool chatHostReadsClipboardFiles(TargetPlatform platform) => - !kIsWeb && platform == TargetPlatform.macOS; + !kIsWeb && + (platform == TargetPlatform.macOS || platform == TargetPlatform.linux); diff --git a/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart b/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart index e93ec3ec..d62fe93a 100644 --- a/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart +++ b/app/lib/features/chat/domain/chat_clipboard_paste_stub.dart @@ -5,7 +5,7 @@ import 'chat_clipboard_paste_native.dart'; /// 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 /// yet: they report that missing capability rather than pretending no paste /// happened, and the composer keeps the host field's own text paste. diff --git a/app/linux/CMakeLists.txt b/app/linux/CMakeLists.txt index ae9c0a53..daefc140 100644 --- a/app/linux/CMakeLists.txt +++ b/app/linux/CMakeLists.txt @@ -97,6 +97,11 @@ install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 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}" COMPONENT Runtime) diff --git a/app/linux/runner/CMakeLists.txt b/app/linux/runner/CMakeLists.txt index e97dabc7..d3a40c79 100644 --- a/app/linux/runner/CMakeLists.txt +++ b/app/linux/runner/CMakeLists.txt @@ -9,6 +9,7 @@ project(runner LANGUAGES CXX) add_executable(${BINARY_NAME} "main.cc" "my_application.cc" + "clipboard_files.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) diff --git a/app/linux/runner/clipboard_files.cc b/app/linux/runner/clipboard_files.cc new file mode 100644 index 00000000..289a60d7 --- /dev/null +++ b/app/linux/runner/clipboard_files.cc @@ -0,0 +1,135 @@ +#include "clipboard_files.h" + +#include +#include + +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(contents), length); + fl_value_append_take( + files, file_entry(name, mime, + reinterpret_cast(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(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); +} diff --git a/app/linux/runner/clipboard_files.h b/app/linux/runner/clipboard_files.h new file mode 100644 index 00000000..13a21081 --- /dev/null +++ b/app/linux/runner/clipboard_files.h @@ -0,0 +1,12 @@ +#ifndef RUNNER_CLIPBOARD_FILES_H_ +#define RUNNER_CLIPBOARD_FILES_H_ + +#include + +// 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_ diff --git a/app/linux/runner/my_application.cc b/app/linux/runner/my_application.cc index 3e1ed334..335cb82c 100644 --- a/app/linux/runner/my_application.cc +++ b/app/linux/runner/my_application.cc @@ -5,6 +5,7 @@ #include #endif +#include "clipboard_files.h" #include "flutter/generated_plugin_registrant.h" struct _MyApplication { @@ -14,6 +15,18 @@ struct _MyApplication { 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. static void first_frame_cb(MyApplication* self, FlView* view) { gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); @@ -25,21 +38,18 @@ static void my_application_activate(GApplication* application) { GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // 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 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } + use_header_bar = g_strcmp0(wm_name, "GNOME Shell") == 0; } #endif if (use_header_bar) { @@ -51,6 +61,7 @@ static void my_application_activate(GApplication* application) { } else { gtk_window_set_title(window, "Pipelines"); } + set_window_icon(window); gtk_window_set_default_size(window, 1280, 720); @@ -74,6 +85,7 @@ static void my_application_activate(GApplication* application) { gtk_widget_realize(GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + clipboard_files_register(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } diff --git a/app/linux/runner/resources/app_icon.png b/app/linux/runner/resources/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..8df1f55e07fb5decc97f70bdfea2aa7473d07778 GIT binary patch literal 73827 zcmb?@c_7sJAGgX@I!G#t%$72pq+$>=6(wt#qC+_*2^ASka%4;^HMtV1NrOp|~72Z`+C2w_b24Ig~`fg8GMA74mNZ~_V!JTqmxWiJKJ-7a_Ry3`>we1zC(Wl^)a18%T5ey} zqH`+d&bt!bq@OGwN-eY2C|7*kC@Vd_vN5-y@srDFb}zp$5QlDn^b#+^roJEv#TXXP zu+hJl&2Q+C^GLmM0*PkY5HQoj-UwS)Ljir{lcg#edK{|wl5obATeK+9eft?KCUDws zNs*s$oDNs*jkJ_a|GbXqclJGw)*mA)4#~eW%8Oh((d$Czb8-XG?u9bkELcsKf4shW z5n9f!(T}vEOL#Z$&J<^N+S{VB&8p0nG0vE`9@)M?gI{o{xu>2W{_K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#m 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. diff --git a/app/test/features/artifacts/ui/artifact_linux_capabilities_test.dart b/app/test/features/artifacts/ui/artifact_linux_capabilities_test.dart new file mode 100644 index 00000000..249ffaa2 --- /dev/null +++ b/app/test/features/artifacts/ui/artifact_linux_capabilities_test.dart @@ -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: '

report

')), + ), + ); + 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: '

next

')), + ), + ); + 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); + }); +} diff --git a/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart b/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart index 7bdf1abd..76290206 100644 --- a/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart +++ b/app/test/features/chat/conversation/chat_composer_injected_paste_test.dart @@ -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_controller.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 'chat_composer_bar_fixtures.dart'; @@ -32,6 +33,12 @@ void main() { if (call.method == 'Clipboard.hasStrings') return {'value': true}; 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(() { @@ -39,6 +46,8 @@ void main() { gateway.close(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, null); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(chatClipboardFilesChannel, null); }); for (final merged in [false, true]) { diff --git a/app/test/features/chat/domain/chat_clipboard_paste_native_test.dart b/app/test/features/chat/domain/chat_clipboard_paste_native_test.dart index 497813eb..baee7524 100644 --- a/app/test/features/chat/domain/chat_clipboard_paste_native_test.dart +++ b/app/test/features/chat/domain/chat_clipboard_paste_native_test.dart @@ -10,6 +10,7 @@ import 'package:pipelines_app/features/chat/domain/chat_clipboard_paste_native.d import '../conversation/chat_composer_bar_fixtures.dart'; final _macOS = TargetPlatformVariant.only(TargetPlatform.macOS); +final _linux = TargetPlatformVariant.only(TargetPlatform.linux); Finder get _field => find.byKey(const Key('chat-composer-field')); @@ -77,10 +78,10 @@ void main() { Future 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.linux), isTrue); for (final platform in [ - TargetPlatform.linux, TargetPlatform.windows, TargetPlatform.android, TargetPlatform.iOS, @@ -228,4 +229,47 @@ void main() { expect(composer.draft, isEmpty); await done(tester); }, 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); } diff --git a/app/tool/fixture_host/fixture_host_native.dart b/app/tool/fixture_host/fixture_host_native.dart index 5fa945ea..d1f0039f 100644 --- a/app/tool/fixture_host/fixture_host_native.dart +++ b/app/tool/fixture_host/fixture_host_native.dart @@ -4,6 +4,7 @@ import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:pipelines_app/application/server_endpoint.dart'; +import '../perf/frame_log_native.dart'; import 'fixture_steps.dart'; import 'narrow_view.dart'; @@ -31,8 +32,10 @@ Map fixtureParams() { return raw.isEmpty ? const {} : Uri.splitQueryString(raw); } -/// The DevTools probes are browser-only. -void installHostProbes(Map params) {} +/// The DevTools probes are browser-only; `perf=1` prints frame timings to +/// stdout (tool/perf/frame_log_native.dart). +void installHostProbes(Map params) => + installNativeFrameLog(params); /// The route goes through [fixtureRouteProvider] instead. void openFixtureRoute(String route) {} diff --git a/app/tool/fixture_host/fixture_steps.dart b/app/tool/fixture_host/fixture_steps.dart index e3603649..02099676 100644 --- a/app/tool/fixture_host/fixture_steps.dart +++ b/app/tool/fixture_host/fixture_steps.dart @@ -9,7 +9,10 @@ import 'package:flutter/services.dart'; /// [script] is `;`-separated steps run after the first frame, 700 ms apart: /// `wait:`, `tap: