Runs park on usage limits; failure classes, harness error policy, run budgets
- A stage refused for a Claude usage limit no longer fails its run: the runner tries the chats' Claude account auto-switch (per-home setting) and reruns the visit, else parks the run in the new waiting_quota status (persisted, with reset/resume time in run summaries, details and events) and resumes the same visit at reset + 1 min, also after a restart. resume_run / `pipelines resume` resumes now; cancel works on parked runs. The rerun visit gets a "# Previous attempt" interruption note. Subscription limits no longer say "top up the provider account". - run/retry into an account known to be limited are deferred (quota_policy defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now). - failure_class on runs (quota, loop_exhausted, timeout, permission_denied, harness_error, blocked, environment, canceled, interrupted, budget, check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/ stats and the app failure line. - Claude permission denials (permission_denials / refused tool results) fail a blocked visit with permission_denied naming the tool use. - Harness failures are classified transient vs deterministic; deterministic ones (and a repeated empty readback) skip error self-loops; transient self-loops back off 15 s, 1 min, 4 min. - Whole-run USD budget: run --budget, server default (run-budget / get/set_run_settings); 80% warning notification, stop with class budget. - App: waiting_quota status/filter with resume time, Resume now and Cancel, failure class wording. Docs and skill references updated. Merges main (check stage, delivery gate, Claude stage restart survival, schedule changes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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();
|
||||
|
||||
@@ -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<ServerEndpoint> 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<void> runPipelinesApp({
|
||||
Uri? base,
|
||||
String configured = configuredServerUrl,
|
||||
SettingsStore? settingsStore,
|
||||
List<String> 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<void> runPipelinesApp({
|
||||
server: server,
|
||||
buildDefault: configured,
|
||||
signedIn: kIsWeb || ServerSession.cookie != null,
|
||||
detached: detached,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
|
||||
import '../../core/servers/chat/chat_server_pool.dart';
|
||||
import '../../core/servers/server_context.dart';
|
||||
import '../../core/servers/server_scope.dart';
|
||||
import '../../core/transport/pipelines_client.dart';
|
||||
import '../../features/settings/server_connections.dart';
|
||||
import '../../features/terminal/terminal_layout.dart';
|
||||
import '../../ui/adaptive/window_margins.dart';
|
||||
import '../../ui/scale/ui_scale.dart';
|
||||
import '../../ui/theme/app_font_controller.dart';
|
||||
import '../../ui/theme/app_theme.dart';
|
||||
import '../app_route.dart';
|
||||
import '../app_session.dart';
|
||||
import '../app_terminals.dart';
|
||||
import '../clipboard_failures.dart' show appScaffoldMessengerKey;
|
||||
import '../server_endpoint.dart';
|
||||
import 'detached_chat.dart';
|
||||
import 'detached_diff.dart';
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
import 'detached_terminal.dart';
|
||||
import 'detached_window_body.dart';
|
||||
import 'detached_windows.dart';
|
||||
|
||||
/// A detached window's whole app: one item ([route]) over its own
|
||||
/// connection, without the shell (no navigation rail, lists, floating
|
||||
/// windows, notifications or update checks).
|
||||
///
|
||||
/// It writes none of the shared layout the main window owns: not the
|
||||
/// server's open-chat workspace (no Chat destination is built), not the
|
||||
/// floating windows (there is no window manager) and not the terminal
|
||||
/// layout ([TerminalLayout.persist] is off). System notifications stay the
|
||||
/// main window's, so nothing is posted twice.
|
||||
class DetachedWindowApp extends StatefulWidget {
|
||||
const DetachedWindowApp({
|
||||
super.key,
|
||||
required this.route,
|
||||
required this.server,
|
||||
this.client,
|
||||
this.chatPool,
|
||||
this.servers,
|
||||
this.serverId,
|
||||
this.serverAddresses,
|
||||
this.platform,
|
||||
this.web = kIsWeb,
|
||||
});
|
||||
|
||||
final DetachedRoute route;
|
||||
final ServerEndpoint server;
|
||||
final PipelinesClient? client;
|
||||
final ChatServerPool? chatPool;
|
||||
final ServerConnections? servers;
|
||||
final String? serverId;
|
||||
final List<Uri>? serverAddresses;
|
||||
final DetachedPlatform? platform;
|
||||
final bool web;
|
||||
|
||||
@override
|
||||
State<DetachedWindowApp> createState() => _DetachedWindowAppState();
|
||||
}
|
||||
|
||||
class _DetachedWindowAppState extends State<DetachedWindowApp> {
|
||||
late final AppSession _session;
|
||||
late final DetachedPlatform _platform =
|
||||
widget.platform ?? DetachedPlatform.instance;
|
||||
final _title = ValueNotifier<String>('');
|
||||
final _ready = ValueNotifier<bool>(false);
|
||||
final _sync = ValueNotifier<int>(0);
|
||||
AppTerminals? _terminals;
|
||||
late final DetachedWindowControls _controls = DetachedWindowControls(
|
||||
ready: _ready,
|
||||
sync: _sync,
|
||||
setTitle: _setTitle,
|
||||
close: () => unawaited(_platform.closeSelf()),
|
||||
bringBackItem: (kind, id, files, index) => unawaited(
|
||||
_bringBack(DetachedReturn(kind, id, files: files, initialIndex: index)),
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
TerminalLayout.instance.persist = false;
|
||||
_session = AppSession(
|
||||
endpoint: widget.server.uri,
|
||||
client: widget.client,
|
||||
knownServer: true,
|
||||
addresses: widget.serverAddresses,
|
||||
);
|
||||
bindServerIdentity(_session.gateway, widget.serverId);
|
||||
bindServerIdentity(_session.client, widget.serverId);
|
||||
_session.addListener(_connectionChanged);
|
||||
widget.chatPool?.addListener(_connectionChanged);
|
||||
_connectionChanged();
|
||||
if (widget.route.kind == DetachedKind.terminal) {
|
||||
_terminals = AppTerminals(
|
||||
pool: widget.chatPool,
|
||||
connection: Listenable.merge([_session, ?widget.servers]),
|
||||
connected: () => _session.connected,
|
||||
gateway: _session.gateway,
|
||||
machineId: widget.serverId ?? 'server',
|
||||
machineName: _serverName,
|
||||
layout: TerminalLayout.instance,
|
||||
);
|
||||
}
|
||||
unawaited(_session.start());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_session.removeListener(_connectionChanged);
|
||||
widget.chatPool?.removeListener(_connectionChanged);
|
||||
_terminals?.dispose();
|
||||
_session.dispose();
|
||||
_title.dispose();
|
||||
_ready.dispose();
|
||||
_sync.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _connectionChanged() {
|
||||
final pool = widget.chatPool;
|
||||
_ready.value =
|
||||
(pool != null && pool.servers.catalog.servers.isNotEmpty) ||
|
||||
_session.connected;
|
||||
_sync.value = pool?.revision ?? _session.connectionEpoch;
|
||||
}
|
||||
|
||||
String _serverName() {
|
||||
final servers = widget.servers;
|
||||
for (final server in servers?.catalog.servers ?? const []) {
|
||||
if (server.id == widget.serverId) return server.name;
|
||||
}
|
||||
return servers?.originHostname ?? _session.endpoint?.host ?? 'Server';
|
||||
}
|
||||
|
||||
/// Titles change from listeners that may fire while a frame is built; the
|
||||
/// app's title follows after it.
|
||||
void _setTitle(String title) {
|
||||
if (SchedulerBinding.instance.schedulerPhase ==
|
||||
SchedulerPhase.persistentCallbacks) {
|
||||
SchedulerBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) _title.value = title;
|
||||
});
|
||||
return;
|
||||
}
|
||||
_title.value = title;
|
||||
}
|
||||
|
||||
/// Hands the item to the main window and closes this one. With no main
|
||||
/// window, a chat or the terminal opens the full app here instead; a diff
|
||||
/// stays (it exists only in this window).
|
||||
Future<void> _bringBack(DetachedReturn item) async {
|
||||
if (await _platform.sendToMain(item.toMessage())) {
|
||||
await _platform.closeSelf();
|
||||
return;
|
||||
}
|
||||
final path = switch (item.kind) {
|
||||
DetachedKind.chat => AppRoute.chatSession(item.id).path,
|
||||
DetachedKind.terminal => AppRoute.chat.path,
|
||||
DetachedKind.diff => null,
|
||||
};
|
||||
if (path != null && await _platform.becomeMain(path)) return;
|
||||
appScaffoldMessengerKey.currentState?.showSnackBar(
|
||||
const SnackBar(content: Text('No main window is open to take it back.')),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body() => switch (widget.route.kind) {
|
||||
DetachedKind.chat => DetachedChat(
|
||||
sessionId:
|
||||
widget.chatPool?.gateway.normalizeId(widget.route.id) ??
|
||||
widget.route.id,
|
||||
gateway: widget.chatPool?.gateway ?? _session.gateway,
|
||||
serverKey: widget.chatPool != null
|
||||
? 'all-saved-servers'
|
||||
: serverStorageScope(widget.serverId),
|
||||
window: _controls,
|
||||
),
|
||||
DetachedKind.terminal => DetachedTerminal(
|
||||
terminals: _terminals!,
|
||||
tabKey: widget.route.id,
|
||||
window: _controls,
|
||||
),
|
||||
DetachedKind.diff => DetachedDiff(
|
||||
token: widget.route.id,
|
||||
platform: _platform,
|
||||
window: _controls,
|
||||
),
|
||||
};
|
||||
|
||||
Route<void> _page() => MaterialPageRoute<void>(
|
||||
settings: RouteSettings(name: widget.route.path),
|
||||
builder: (_) => _DetachedHome(child: _body()),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fonts = AppFontController.instance;
|
||||
final app = ListenableBuilder(
|
||||
listenable: Listenable.merge([fonts, _title]),
|
||||
builder: (context, _) => MaterialApp(
|
||||
title: _title.value.isEmpty
|
||||
? 'Pipelines'
|
||||
: '${_title.value} · Pipelines',
|
||||
scaffoldMessengerKey: appScaffoldMessengerKey,
|
||||
debugShowCheckedModeBanner: false,
|
||||
builder: (context, child) => UiScaleHost(
|
||||
child: WindowMargins(child: child ?? const SizedBox.shrink()),
|
||||
),
|
||||
theme: appLightTheme(fontFamily: fonts.family),
|
||||
darkTheme: appDarkTheme(fontFamily: fonts.family),
|
||||
themeMode: ThemeMode.system,
|
||||
// The window's one page is named by its route, so the address bar
|
||||
// (and a reload) keeps the detached location instead of `/`.
|
||||
initialRoute: widget.route.path,
|
||||
onGenerateInitialRoutes: (_) => [_page()],
|
||||
onGenerateRoute: (_) => _page(),
|
||||
),
|
||||
);
|
||||
final servers = widget.servers;
|
||||
return servers == null
|
||||
? app
|
||||
: ServerContext(
|
||||
connections: servers,
|
||||
serverId: widget.serverId,
|
||||
child: app,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's single page: the item fills it.
|
||||
class _DetachedHome extends StatelessWidget {
|
||||
const _DetachedHome({required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
Scaffold(key: const ValueKey('detached-window'), body: child);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import '../../features/chat/chat_pane_content.dart';
|
||||
import '../../features/chat/chat_runtime.dart';
|
||||
import '../../features/chat/data/chat_recency.dart';
|
||||
import '../../features/chat/ui/sessions/chat_adaptive.dart';
|
||||
import '../../features/chat/workspace/chat_pane_commands.dart';
|
||||
import 'detached_route.dart';
|
||||
import 'detached_window_body.dart';
|
||||
|
||||
/// One chat alone in a detached window: the same live pane as in the Chat
|
||||
/// destination (header, transcript, find, composer), with "Bring back to
|
||||
/// main window" in its More menu. It has its own [ChatRuntime] over this
|
||||
/// window's connection and keeps no workspace: nothing it does is saved as
|
||||
/// the device's or the server's open-chat layout.
|
||||
class DetachedChat extends StatefulWidget {
|
||||
const DetachedChat({
|
||||
super.key,
|
||||
required this.sessionId,
|
||||
required this.gateway,
|
||||
required this.window,
|
||||
this.serverKey = '',
|
||||
});
|
||||
|
||||
final String sessionId;
|
||||
final ApiGateway gateway;
|
||||
final String serverKey;
|
||||
final DetachedWindowControls window;
|
||||
|
||||
@override
|
||||
State<DetachedChat> createState() => _DetachedChatState();
|
||||
}
|
||||
|
||||
class _DetachedChatState extends State<DetachedChat> {
|
||||
// An in-memory recency: the main window keeps the device's.
|
||||
late final ChatRuntime _runtime = ChatRuntime(
|
||||
gateway: widget.gateway,
|
||||
serverKey: widget.serverKey,
|
||||
recency: ChatRecency(),
|
||||
);
|
||||
final _paneCommands = ChatPaneCommands();
|
||||
late String _sessionId = widget.sessionId;
|
||||
bool _reading = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_runtime.addListener(_retitle);
|
||||
_runtime.sessions.addListener(_rowsChanged);
|
||||
_runtime.addSessionReplacedListener(_replacedElsewhere);
|
||||
widget.window.ready.addListener(_rowsChanged);
|
||||
_rowsChanged();
|
||||
_runtime.composerFocus.request(_sessionId);
|
||||
_retitle();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(DetachedChat oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (!identical(oldWidget.gateway, widget.gateway)) {
|
||||
_runtime.gateway = widget.gateway;
|
||||
}
|
||||
if (oldWidget.window.ready != widget.window.ready) {
|
||||
oldWidget.window.ready.removeListener(_rowsChanged);
|
||||
widget.window.ready.addListener(_rowsChanged);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.window.ready.removeListener(_rowsChanged);
|
||||
_runtime.removeListener(_retitle);
|
||||
_runtime.sessions.removeListener(_rowsChanged);
|
||||
_runtime.removeSessionReplacedListener(_replacedElsewhere);
|
||||
_paneCommands.dispose();
|
||||
_runtime.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _retitle() => widget.window.setTitle(_runtime.titleFor(_sessionId));
|
||||
|
||||
/// The pane's title, model and mode come from the session list, read once
|
||||
/// connected (and again on every reconnect, see [build]).
|
||||
void _rowsChanged() {
|
||||
if (!widget.window.ready.value) return;
|
||||
final sessions = _runtime.sessions;
|
||||
if (_runtime.rowFor(_sessionId) == null && !_reading) {
|
||||
_reading = true;
|
||||
unawaited(sessions.refresh().whenComplete(() => _reading = false));
|
||||
}
|
||||
final rows = sessions.sessions;
|
||||
scheduleMicrotask(() {
|
||||
if (mounted) {
|
||||
_runtime.adoptRows(rows, selected: _sessionId, retained: {_sessionId});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// `/new` here, or on another device: the window follows the new session.
|
||||
void _follow(String previousId, JsonMap session, String notice) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty || previousId != _sessionId) return;
|
||||
_runtime.movedToSession(previousId, session, notice);
|
||||
setState(() => _sessionId = id);
|
||||
_retitle();
|
||||
}
|
||||
|
||||
void _startedNewSession(String previousId, JsonMap session, String notice) {
|
||||
_runtime.sessions.replaceSession(previousId, session);
|
||||
_follow(previousId, session, notice);
|
||||
unawaited(_runtime.sessions.refresh());
|
||||
}
|
||||
|
||||
void _replacedElsewhere(String previousId, JsonMap session) =>
|
||||
_follow(previousId, session, 'This chat continues in a new session.');
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: Listenable.merge([widget.window.ready, widget.window.sync]),
|
||||
builder: (context, _) {
|
||||
if (!widget.window.ready.value) return const DetachedConnecting();
|
||||
final sessionId = _sessionId;
|
||||
return buildChatPaneContent(
|
||||
runtime: _runtime,
|
||||
sessionId: sessionId,
|
||||
placement: ChatPanePlacement(
|
||||
syncToken: widget.window.sync.value,
|
||||
onBack: () {},
|
||||
showBackButton: false,
|
||||
// The only chat here: a paste with no field focused is its.
|
||||
pasteTarget: true,
|
||||
paneCommands: _paneCommands,
|
||||
onComposerFocus: () => _runtime.composerFocus.request(sessionId),
|
||||
onNewSession: _startedNewSession,
|
||||
// `/close` was accepted: nothing is left to show.
|
||||
onSessionClosed: widget.window.close,
|
||||
paneControls: (_) => [
|
||||
ChatBarAction(
|
||||
label: detachedBringBackLabel,
|
||||
identifier: 'detached-bring-back',
|
||||
onPressed: () =>
|
||||
widget.window.bringBack(DetachedKind.chat, sessionId),
|
||||
materialIcon: Icons.login,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../features/changes/domain/file_change.dart';
|
||||
import '../../features/changes/widgets/file_diff_page.dart';
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
import 'detached_window_body.dart';
|
||||
|
||||
/// The diff a window was handed: its files and the one it opened on.
|
||||
typedef DetachedDiffContent = ({List<FileChange> files, int index});
|
||||
|
||||
/// Reads the hand-over [json] (`{"files": [...], "index": n}`); null when it
|
||||
/// holds no file.
|
||||
DetachedDiffContent? decodeDetachedDiff(String? json) {
|
||||
if (json == null) return null;
|
||||
try {
|
||||
final value = jsonDecode(json);
|
||||
if (value is! Map) return null;
|
||||
final raw = value['files'];
|
||||
final files = [
|
||||
if (raw is List)
|
||||
for (final entry in raw) ?FileChange.fromHandover(entry),
|
||||
];
|
||||
if (files.isEmpty) return null;
|
||||
final index = value['index'];
|
||||
return (
|
||||
files: files,
|
||||
index: index is int ? index.clamp(0, files.length - 1) : 0,
|
||||
);
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A diff alone in a detached window. Its files are in memory only, handed
|
||||
/// over through the platform (see [DetachedPlatform.take]); there is nothing
|
||||
/// to read from the server.
|
||||
class DetachedDiff extends StatefulWidget {
|
||||
const DetachedDiff({
|
||||
super.key,
|
||||
required this.token,
|
||||
required this.platform,
|
||||
required this.window,
|
||||
});
|
||||
|
||||
final String token;
|
||||
final DetachedPlatform platform;
|
||||
final DetachedWindowControls window;
|
||||
|
||||
@override
|
||||
State<DetachedDiff> createState() => _DetachedDiffState();
|
||||
}
|
||||
|
||||
class _DetachedDiffState extends State<DetachedDiff> {
|
||||
late final Future<DetachedDiffContent?> _content = widget.platform
|
||||
.take(widget.token)
|
||||
.then(decodeDetachedDiff);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
unawaited(_content.then(_retitle));
|
||||
}
|
||||
|
||||
void _retitle(DetachedDiffContent? content) {
|
||||
final files = content?.files;
|
||||
widget.window.setTitle(switch (files) {
|
||||
null || [] => 'Diff',
|
||||
[final file] => file.path.split('/').last,
|
||||
_ => '${files.length} files changed',
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => FutureBuilder<DetachedDiffContent?>(
|
||||
future: _content,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return const Material(child: SizedBox.expand());
|
||||
}
|
||||
final content = snapshot.data;
|
||||
if (content == null) {
|
||||
return const Material(
|
||||
child: Center(child: Text('This diff is no longer available.')),
|
||||
);
|
||||
}
|
||||
return FileDiffPage(
|
||||
files: content.files,
|
||||
initialIndex: content.index,
|
||||
inWindow: true,
|
||||
actions: [
|
||||
DetachedBringBackButton(
|
||||
onPressed: () => widget.window.bringBack(
|
||||
DetachedKind.diff,
|
||||
widget.token,
|
||||
files: [for (final file in content.files) file.toJson()],
|
||||
initialIndex: content.index,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'detached_platform_stub.dart'
|
||||
if (dart.library.js_interop) 'detached_platform_web.dart'
|
||||
if (dart.library.io) 'detached_platform_io.dart'
|
||||
as host;
|
||||
import 'detached_route.dart';
|
||||
|
||||
/// How a launch went.
|
||||
enum DetachedLaunch {
|
||||
/// The window is open (or an open one came to the front).
|
||||
opened,
|
||||
|
||||
/// The browser blocked the popup; a click may open it as a tab.
|
||||
blocked,
|
||||
|
||||
/// Nothing could be opened.
|
||||
failed,
|
||||
}
|
||||
|
||||
/// A message between a detached window and the main window, as JSON.
|
||||
typedef DetachedMessage = Map<String, Object?>;
|
||||
|
||||
/// The platform's side of detached windows: opening one, the messages they
|
||||
/// send back to the main window, and a hand-over of data too large for a
|
||||
/// URL (a diff's files).
|
||||
///
|
||||
/// - Web: `window.open` with popup features, `postMessage` to the opener,
|
||||
/// and `localStorage` for the hand-over.
|
||||
/// - Linux and macOS: a second process of the app with `--detached <path>`,
|
||||
/// a line on its standard output, and a temporary file.
|
||||
/// - Android and iOS: unsupported.
|
||||
abstract class DetachedPlatform {
|
||||
/// The app's platform.
|
||||
static DetachedPlatform instance = host.createDetachedPlatform();
|
||||
|
||||
/// Extra query parameters every detached browser window's URL carries.
|
||||
/// The capture fixture sets its own (`chats=2`, `theme=dark`), so the
|
||||
/// window it opens runs on the same fixture; the app sets none.
|
||||
static Map<String, String> Function()? extraQuery;
|
||||
|
||||
/// Whether this platform can open detached windows.
|
||||
bool get supported;
|
||||
|
||||
/// Opens [route] in a new window of [size] named [title]; [tab] opens a
|
||||
/// browser tab instead (from a click, after a blocked popup).
|
||||
Future<DetachedLaunch> launch(
|
||||
DetachedRoute route, {
|
||||
required String title,
|
||||
required Size size,
|
||||
bool tab = false,
|
||||
});
|
||||
|
||||
/// Messages the detached windows send to this (main) window.
|
||||
Stream<DetachedMessage> get messages;
|
||||
|
||||
/// Keeps [json] for the window that will ask for [token].
|
||||
Future<void> put(String token, String json);
|
||||
|
||||
/// The data kept under [token], for this window; null when there is none.
|
||||
Future<String?> take(String token);
|
||||
|
||||
/// Sends [message] to the main window that opened this one; false when
|
||||
/// there is none to receive it.
|
||||
Future<bool> sendToMain(DetachedMessage message);
|
||||
|
||||
/// Closes this detached window.
|
||||
Future<void> closeSelf();
|
||||
|
||||
/// Opens the full app (the main window) at [appPath], in place of this
|
||||
/// detached window; false when this platform cannot.
|
||||
Future<bool> becomeMain(String appPath);
|
||||
}
|
||||
|
||||
/// The detached window this launch opens, or null for the main window: the
|
||||
/// browser location on the web, `--detached <path>` (or the environment) on
|
||||
/// a desktop.
|
||||
DetachedRoute? detachedLaunchRoute(List<String> args) =>
|
||||
host.launchedDetachedRoute(args);
|
||||
|
||||
/// The marker a message carries, so the main window ignores anything else.
|
||||
const detachedMessageMarker = 'pipelines.detached.v1';
|
||||
|
||||
String encodeDetachedMessage(DetachedMessage message) =>
|
||||
jsonEncode({...message, 'marker': detachedMessageMarker});
|
||||
|
||||
DetachedMessage? decodeDetachedMessage(String text) {
|
||||
try {
|
||||
final value = jsonDecode(text);
|
||||
if (value is! Map || value['marker'] != detachedMessageMarker) return null;
|
||||
return Map<String, Object?>.from(value)..remove('marker');
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
|
||||
/// Widget tests run on a desktop host but are not a desktop app: there the
|
||||
/// action stays hidden unless a test supplies a platform.
|
||||
DetachedPlatform createDetachedPlatform() => IoDetachedPlatform(
|
||||
supported:
|
||||
(Platform.isLinux || Platform.isMacOS) &&
|
||||
!Platform.environment.containsKey('FLUTTER_TEST'),
|
||||
);
|
||||
|
||||
DetachedRoute? launchedDetachedRoute(List<String> args) =>
|
||||
DetachedRoute.fromLaunch(args, Platform.environment);
|
||||
|
||||
/// Detached windows as second processes of the desktop app (Linux, macOS).
|
||||
///
|
||||
/// Flutter 3.44's multi-window API is still experimental (behind a flag and
|
||||
/// without macOS parity), so each detached window is the same executable
|
||||
/// started with `--detached <path>`; `PIPELINES_DETACHED` carries the path
|
||||
/// too, since the macOS runner does not hand its arguments to Dart. It
|
||||
/// shares the saved servers, session and preferences on disk, and has its
|
||||
/// own connection. It writes messages for the main window as lines on its
|
||||
/// standard output, which the main process reads.
|
||||
class IoDetachedPlatform extends DetachedPlatform {
|
||||
IoDetachedPlatform({bool? supported})
|
||||
: _supported = supported ?? (Platform.isLinux || Platform.isMacOS);
|
||||
|
||||
final bool _supported;
|
||||
final Map<DetachedRoute, Process> _children = {};
|
||||
final _messages = StreamController<DetachedMessage>.broadcast();
|
||||
|
||||
static const _linePrefix = '@@pipelines-window ';
|
||||
static const titleVariable = 'PIPELINES_WINDOW_TITLE';
|
||||
static const sizeVariable = 'PIPELINES_WINDOW_SIZE';
|
||||
static const parentVariable = 'PIPELINES_PARENT_PID';
|
||||
|
||||
@override
|
||||
bool get supported => _supported;
|
||||
|
||||
@override
|
||||
Future<DetachedLaunch> launch(
|
||||
DetachedRoute route, {
|
||||
required String title,
|
||||
required Size size,
|
||||
bool tab = false,
|
||||
}) async {
|
||||
if (!_supported) return DetachedLaunch.failed;
|
||||
// A window already open for the item is left as it is: another process
|
||||
// cannot be raised from here.
|
||||
if (_children.containsKey(route)) return DetachedLaunch.opened;
|
||||
final Process process;
|
||||
try {
|
||||
process = await Process.start(
|
||||
Platform.resolvedExecutable,
|
||||
[DetachedRoute.argument, route.path],
|
||||
environment: {
|
||||
DetachedRoute.environment: route.path,
|
||||
titleVariable: title,
|
||||
sizeVariable: '${size.width.round()}x${size.height.round()}',
|
||||
parentVariable: '$pid',
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
return DetachedLaunch.failed;
|
||||
}
|
||||
_children[route] = process;
|
||||
// Both streams are drained, so a chatty child never blocks on a full
|
||||
// pipe; only marked lines are messages.
|
||||
process.stdout
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter())
|
||||
.listen(_line, onError: (_) {});
|
||||
process.stderr.listen((_) {}, onError: (_) {});
|
||||
unawaited(process.exitCode.then((_) => _children.remove(route)));
|
||||
return DetachedLaunch.opened;
|
||||
}
|
||||
|
||||
void _line(String line) {
|
||||
if (!line.startsWith(_linePrefix)) return;
|
||||
final message = decodeDetachedMessage(line.substring(_linePrefix.length));
|
||||
if (message != null) _messages.add(message);
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<DetachedMessage> get messages => _messages.stream;
|
||||
|
||||
File _file(String token) =>
|
||||
File('${Directory.systemTemp.path}/pipelines-detached-$token.json');
|
||||
|
||||
@override
|
||||
Future<void> put(String token, String json) async {
|
||||
try {
|
||||
await _file(token).writeAsString(json, flush: true);
|
||||
} catch (_) {
|
||||
// The window says the diff is gone.
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> take(String token) async {
|
||||
final file = _file(token);
|
||||
try {
|
||||
final text = await file.readAsString();
|
||||
await file.delete();
|
||||
return text;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
int? get _parent => int.tryParse(Platform.environment[parentVariable] ?? '');
|
||||
|
||||
Future<bool> _parentAlive() async {
|
||||
final parent = _parent;
|
||||
if (parent == null) return false;
|
||||
try {
|
||||
return (await Process.run('kill', ['-0', '$parent'])).exitCode == 0;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> sendToMain(DetachedMessage message) async {
|
||||
if (!await _parentAlive()) return false;
|
||||
try {
|
||||
stdout.writeln('$_linePrefix${encodeDetachedMessage(message)}');
|
||||
await stdout.flush();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> closeSelf() async => exit(0);
|
||||
|
||||
/// Starts the app as an ordinary main window (it opens where it last was)
|
||||
/// for this one to close.
|
||||
@override
|
||||
Future<bool> becomeMain(String appPath) async {
|
||||
try {
|
||||
await Process.start(
|
||||
Platform.resolvedExecutable,
|
||||
const [],
|
||||
environment: {DetachedRoute.environment: '', parentVariable: ''},
|
||||
mode: ProcessStartMode.detached,
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
|
||||
DetachedPlatform createDetachedPlatform() => UnsupportedDetachedPlatform();
|
||||
|
||||
DetachedRoute? launchedDetachedRoute(List<String> args) =>
|
||||
DetachedRoute.fromLaunch(args);
|
||||
|
||||
/// A platform without windows of its own (a phone): nothing opens.
|
||||
class UnsupportedDetachedPlatform extends DetachedPlatform {
|
||||
@override
|
||||
bool get supported => false;
|
||||
|
||||
@override
|
||||
Future<DetachedLaunch> launch(
|
||||
DetachedRoute route, {
|
||||
required String title,
|
||||
required Size size,
|
||||
bool tab = false,
|
||||
}) async => DetachedLaunch.failed;
|
||||
|
||||
@override
|
||||
Stream<DetachedMessage> get messages => const Stream.empty();
|
||||
|
||||
@override
|
||||
Future<void> put(String token, String json) async {}
|
||||
|
||||
@override
|
||||
Future<String?> take(String token) async => null;
|
||||
|
||||
@override
|
||||
Future<bool> sendToMain(DetachedMessage message) async => false;
|
||||
|
||||
@override
|
||||
Future<void> closeSelf() async {}
|
||||
|
||||
@override
|
||||
Future<bool> becomeMain(String appPath) async => false;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:web/web.dart' as web;
|
||||
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
|
||||
DetachedPlatform createDetachedPlatform() => WebDetachedPlatform();
|
||||
|
||||
DetachedRoute? launchedDetachedRoute(List<String> args) =>
|
||||
DetachedRoute.parse(Uri.base.toString());
|
||||
|
||||
/// Detached windows as browser windows of the same origin: the session
|
||||
/// cookie and the local preferences are shared, and each window is its own
|
||||
/// app instance with its own connection.
|
||||
class WebDetachedPlatform extends DetachedPlatform {
|
||||
final Map<String, web.Window> _opened = {};
|
||||
StreamController<DetachedMessage>? _messages;
|
||||
JSFunction? _listener;
|
||||
|
||||
@override
|
||||
bool get supported => true;
|
||||
|
||||
@override
|
||||
Future<DetachedLaunch> launch(
|
||||
DetachedRoute route, {
|
||||
required String title,
|
||||
required Size size,
|
||||
bool tab = false,
|
||||
}) async {
|
||||
final name = _name(route);
|
||||
final open = _opened[name];
|
||||
if (open != null && !open.closed) {
|
||||
open.focus();
|
||||
return DetachedLaunch.opened;
|
||||
}
|
||||
final url = _url(route);
|
||||
final web.Window? window;
|
||||
try {
|
||||
window = tab
|
||||
? web.window.open(url, name)
|
||||
: web.window.open(
|
||||
url,
|
||||
name,
|
||||
'popup,width=${size.width.round()},height=${size.height.round()}',
|
||||
);
|
||||
} catch (_) {
|
||||
return DetachedLaunch.failed;
|
||||
}
|
||||
if (window == null) {
|
||||
return tab ? DetachedLaunch.failed : DetachedLaunch.blocked;
|
||||
}
|
||||
_opened[name] = window;
|
||||
return DetachedLaunch.opened;
|
||||
}
|
||||
|
||||
/// One browser window per item: opening it again brings that one forward.
|
||||
static String _name(DetachedRoute route) =>
|
||||
'pipelines-${route.kind.name}-'
|
||||
'${route.id.replaceAll(RegExp(r'[^A-Za-z0-9_-]'), '_')}';
|
||||
|
||||
static String _url(DetachedRoute route) {
|
||||
final base = Uri.base.resolve(route.path);
|
||||
final extra = DetachedPlatform.extraQuery?.call() ?? const {};
|
||||
if (extra.isEmpty) return base.toString();
|
||||
return base
|
||||
.replace(queryParameters: {...extra, ...base.queryParameters})
|
||||
.toString();
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<DetachedMessage> get messages {
|
||||
final existing = _messages;
|
||||
if (existing != null) return existing.stream;
|
||||
final controller = _messages = StreamController.broadcast();
|
||||
final listener = ((web.MessageEvent event) {
|
||||
if (event.origin != web.window.location.origin) return;
|
||||
final data = event.data;
|
||||
if (!data.isA<JSString>()) return;
|
||||
final message = decodeDetachedMessage((data as JSString).toDart);
|
||||
if (message != null) controller.add(message);
|
||||
}).toJS;
|
||||
_listener = listener;
|
||||
web.window.addEventListener('message', listener);
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
static String _key(String token) => 'pipelines.detached.$token';
|
||||
|
||||
@override
|
||||
Future<void> put(String token, String json) async {
|
||||
try {
|
||||
web.window.localStorage.setItem(_key(token), json);
|
||||
} catch (_) {
|
||||
// Storage full or off: the window says the diff is gone.
|
||||
}
|
||||
}
|
||||
|
||||
/// The hand-over is read once from the shared storage, then kept in this
|
||||
/// window's own session storage so a reload still has it.
|
||||
@override
|
||||
Future<String?> take(String token) async {
|
||||
final key = _key(token);
|
||||
try {
|
||||
final shared = web.window.localStorage.getItem(key);
|
||||
if (shared != null) {
|
||||
web.window.localStorage.removeItem(key);
|
||||
web.window.sessionStorage.setItem(key, shared);
|
||||
return shared;
|
||||
}
|
||||
return web.window.sessionStorage.getItem(key);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
web.Window? get _opener {
|
||||
final opener = web.window.opener;
|
||||
// The opener is a window of another realm: `instanceof Window` (isA)
|
||||
// would refuse it, so it is taken as one.
|
||||
if (opener == null) return null;
|
||||
final window = opener as web.Window;
|
||||
try {
|
||||
return window.closed ? null : window;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> sendToMain(DetachedMessage message) async {
|
||||
final opener = _opener;
|
||||
if (opener == null) return false;
|
||||
try {
|
||||
opener.postMessage(
|
||||
encodeDetachedMessage(message).toJS,
|
||||
web.window.location.origin.toJS,
|
||||
);
|
||||
opener.focus();
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> closeSelf() async => web.window.close();
|
||||
|
||||
@override
|
||||
Future<bool> becomeMain(String appPath) async {
|
||||
web.window.location.assign(appPath);
|
||||
return true;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
final listener = _listener;
|
||||
if (listener != null) {
|
||||
web.window.removeEventListener('message', listener);
|
||||
}
|
||||
unawaited(_messages?.close());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import '../app_route.dart';
|
||||
|
||||
/// What a detached window shows.
|
||||
enum DetachedKind { chat, terminal, diff }
|
||||
|
||||
/// The route of a detached window: one chat, the terminal (on one tab) or
|
||||
/// one diff, alone in its own browser window or app process, without the
|
||||
/// shell's navigation.
|
||||
///
|
||||
/// /window/chat/:sessionId one chat pane
|
||||
/// /window/terminal[?tab=:key] the terminal, on the tab [key]
|
||||
/// /window/diff/:token a diff handed over under [token]
|
||||
///
|
||||
/// A native process gets the same path as `--detached <path>` (or the
|
||||
/// `PIPELINES_DETACHED` environment variable, which macOS also passes).
|
||||
class DetachedRoute {
|
||||
const DetachedRoute._(this.kind, this.id);
|
||||
|
||||
/// One chat; null when [sessionId] is not a chat session id.
|
||||
static DetachedRoute? chat(String sessionId) =>
|
||||
AppRoute.isChatSessionId(sessionId)
|
||||
? DetachedRoute._(DetachedKind.chat, sessionId)
|
||||
: null;
|
||||
|
||||
/// The terminal on the tab [tabKey] (empty: the one selected).
|
||||
static DetachedRoute terminal([String tabKey = '']) => DetachedRoute._(
|
||||
DetachedKind.terminal,
|
||||
tabKey.length > _maxTabKey ? '' : tabKey,
|
||||
);
|
||||
|
||||
/// A diff whose files were handed over under [token].
|
||||
static DetachedRoute? diff(String token) =>
|
||||
_token.hasMatch(token) ? DetachedRoute._(DetachedKind.diff, token) : null;
|
||||
|
||||
final DetachedKind kind;
|
||||
|
||||
/// The chat session id, the terminal tab key or the diff token.
|
||||
final String id;
|
||||
|
||||
static const prefix = '/window';
|
||||
static const argument = '--detached';
|
||||
static const environment = 'PIPELINES_DETACHED';
|
||||
|
||||
static final _token = RegExp(r'^[A-Za-z0-9_-]{1,64}$');
|
||||
static const _maxTabKey = 512;
|
||||
|
||||
/// The app-relative location of this window.
|
||||
String get path => switch (kind) {
|
||||
DetachedKind.chat => '$prefix/chat/${Uri.encodeComponent(id)}',
|
||||
DetachedKind.terminal =>
|
||||
id.isEmpty
|
||||
? '$prefix/terminal'
|
||||
: '$prefix/terminal?${Uri(queryParameters: {'tab': id}).query}',
|
||||
DetachedKind.diff => '$prefix/diff/$id',
|
||||
};
|
||||
|
||||
/// The detached route [location] names (a path with its query, or a full
|
||||
/// URL), or null when it is an ordinary app location.
|
||||
static DetachedRoute? parse(String location) {
|
||||
final uri = Uri.tryParse(location.trim());
|
||||
if (uri == null) return null;
|
||||
final segments = uri.pathSegments.where((s) => s.isNotEmpty).toList();
|
||||
if (segments.length < 2 || segments.first != prefix.substring(1)) {
|
||||
return null;
|
||||
}
|
||||
return switch ((segments[1], segments.length)) {
|
||||
('chat', 3) => chat(segments[2]),
|
||||
('terminal', 2) => terminal(_query(uri)['tab'] ?? ''),
|
||||
('diff', 3) => diff(segments[2]),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// The route a native launch names: `--detached <path>` (or
|
||||
/// `--detached=<path>`) in [args], else [env]'s `PIPELINES_DETACHED`.
|
||||
static DetachedRoute? fromLaunch(
|
||||
List<String> args, [
|
||||
Map<String, String> env = const {},
|
||||
]) {
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
final arg = args[i];
|
||||
if (arg == argument && i + 1 < args.length) return parse(args[i + 1]);
|
||||
if (arg.startsWith('$argument=')) {
|
||||
return parse(arg.substring(argument.length + 1));
|
||||
}
|
||||
}
|
||||
final value = env[environment];
|
||||
return value == null || value.isEmpty ? null : parse(value);
|
||||
}
|
||||
|
||||
static Map<String, String> _query(Uri uri) {
|
||||
try {
|
||||
return uri.queryParameters;
|
||||
} on FormatException {
|
||||
return const {};
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is DetachedRoute && other.kind == kind && other.id == id;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(kind, id);
|
||||
|
||||
@override
|
||||
String toString() => path;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../features/terminal/terminal_body.dart';
|
||||
import '../../features/terminal/terminal_hub.dart';
|
||||
import '../../features/terminal/terminal_layout.dart';
|
||||
import '../../features/terminal/terminal_tab_strip.dart';
|
||||
import '../app_terminals.dart';
|
||||
import 'detached_route.dart';
|
||||
import 'detached_window_body.dart';
|
||||
|
||||
/// The terminal alone in a detached window: its tabs (the machines'
|
||||
/// terminals, which every client of the server shares) on the tab it was
|
||||
/// sent from. The device's terminal layout is read, never written (see
|
||||
/// [TerminalLayout.persist]); there is no panel or window mode to choose.
|
||||
class DetachedTerminal extends StatefulWidget {
|
||||
const DetachedTerminal({
|
||||
super.key,
|
||||
required this.terminals,
|
||||
required this.tabKey,
|
||||
required this.window,
|
||||
});
|
||||
|
||||
/// This window's terminals, over its own connection.
|
||||
final AppTerminals terminals;
|
||||
|
||||
/// The tab to select once the machines' terminals are listed.
|
||||
final String tabKey;
|
||||
final DetachedWindowControls window;
|
||||
|
||||
@override
|
||||
State<DetachedTerminal> createState() => _DetachedTerminalState();
|
||||
}
|
||||
|
||||
class _DetachedTerminalState extends State<DetachedTerminal> {
|
||||
TerminalHub get _hub => widget.terminals.hub;
|
||||
bool _placed = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_hub
|
||||
..addListener(_changed)
|
||||
..activate();
|
||||
_changed();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_hub.removeListener(_changed);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Selects the tab the window was opened on as soon as it is listed, once,
|
||||
/// and names the window after the selected tab.
|
||||
void _changed() {
|
||||
if (!_placed && widget.tabKey.isNotEmpty) {
|
||||
final tab = _hub.tabs.where((tab) => tab.key == widget.tabKey);
|
||||
if (tab.isNotEmpty) {
|
||||
_placed = true;
|
||||
_hub.select(tab.first);
|
||||
}
|
||||
}
|
||||
final title = _hub.selected?.title;
|
||||
widget.window.setTitle(
|
||||
title == null || title.isEmpty ? 'Terminal' : 'Terminal: $title',
|
||||
);
|
||||
}
|
||||
|
||||
void _bringBack() =>
|
||||
widget.window.bringBack(DetachedKind.terminal, _hub.selected?.key ?? '');
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Material(
|
||||
child: SafeArea(
|
||||
child: ListenableBuilder(
|
||||
listenable: Listenable.merge([_hub, widget.terminals.layout]),
|
||||
builder: (context, _) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
TerminalTabStrip(
|
||||
hub: _hub,
|
||||
layout: widget.terminals.layout,
|
||||
showModes: false,
|
||||
trailing: [DetachedBringBackButton(onPressed: _bringBack)],
|
||||
),
|
||||
Expanded(child: TerminalBody(hub: _hub)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'detached_route.dart';
|
||||
|
||||
/// The action that hands a detached item back to the main window.
|
||||
const detachedBringBackLabel = 'Bring back to main window';
|
||||
|
||||
/// What a detached window offers the item it shows.
|
||||
class DetachedWindowControls {
|
||||
const DetachedWindowControls({
|
||||
required this.ready,
|
||||
required this.sync,
|
||||
required this.setTitle,
|
||||
required this.close,
|
||||
required this.bringBackItem,
|
||||
});
|
||||
|
||||
/// Whether the server has been reached, so the item can be read.
|
||||
final ValueListenable<bool> ready;
|
||||
|
||||
/// Advances when the connection is replaced; open views re-subscribe.
|
||||
final ValueListenable<int> sync;
|
||||
|
||||
/// Names the window after the item (the browser or desktop title).
|
||||
final ValueChanged<String> setTitle;
|
||||
|
||||
/// Closes this window.
|
||||
final VoidCallback close;
|
||||
|
||||
/// Gives the item back to the main window and closes this one.
|
||||
final void Function(
|
||||
DetachedKind kind,
|
||||
String id,
|
||||
List<Map<String, Object?>> files,
|
||||
int initialIndex,
|
||||
)
|
||||
bringBackItem;
|
||||
|
||||
void bringBack(
|
||||
DetachedKind kind,
|
||||
String id, {
|
||||
List<Map<String, Object?>> files = const [],
|
||||
int initialIndex = 0,
|
||||
}) => bringBackItem(kind, id, files, initialIndex);
|
||||
}
|
||||
|
||||
/// Shown until the window's connection first succeeds.
|
||||
class DetachedConnecting extends StatelessWidget {
|
||||
const DetachedConnecting({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Text('Connecting…', style: Theme.of(context).textTheme.bodyMedium),
|
||||
);
|
||||
}
|
||||
|
||||
/// The "Bring back to main window" button of a window without a menu of its
|
||||
/// own (the terminal's tab strip, the diff's bar).
|
||||
class DetachedBringBackButton extends StatelessWidget {
|
||||
const DetachedBringBackButton({super.key, required this.onPressed});
|
||||
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => IconButton(
|
||||
key: const ValueKey('detached-bring-back'),
|
||||
tooltip: detachedBringBackLabel,
|
||||
onPressed: onPressed,
|
||||
icon: const Icon(Icons.login),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../shell/detached/detached_window_scope.dart';
|
||||
import '../clipboard_failures.dart' show appScaffoldMessengerKey;
|
||||
import 'detached_platform.dart';
|
||||
import 'detached_route.dart';
|
||||
|
||||
/// What a detached window hands back to the main window ("Bring back to
|
||||
/// main window"): the item, and a diff's files.
|
||||
class DetachedReturn {
|
||||
const DetachedReturn(
|
||||
this.kind,
|
||||
this.id, {
|
||||
this.files = const [],
|
||||
this.initialIndex = 0,
|
||||
});
|
||||
|
||||
final DetachedKind kind;
|
||||
final String id;
|
||||
final List<Map<String, Object?>> files;
|
||||
final int initialIndex;
|
||||
|
||||
DetachedMessage toMessage() => {
|
||||
'type': 'bring-back',
|
||||
'kind': kind.name,
|
||||
'id': id,
|
||||
if (kind == DetachedKind.diff) ...{'files': files, 'index': initialIndex},
|
||||
};
|
||||
|
||||
static DetachedReturn? fromMessage(DetachedMessage message) {
|
||||
if (message['type'] != 'bring-back') return null;
|
||||
final kind = DetachedKind.values.asNameMap()['${message['kind']}'];
|
||||
if (kind == null) return null;
|
||||
final files = message['files'];
|
||||
final index = message['index'];
|
||||
return DetachedReturn(
|
||||
kind,
|
||||
'${message['id'] ?? ''}',
|
||||
files: files is List
|
||||
? [
|
||||
for (final file in files)
|
||||
if (file is Map) Map<String, Object?>.from(file),
|
||||
]
|
||||
: const [],
|
||||
initialIndex: index is int ? index : 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Window sizes a detached item opens at.
|
||||
const detachedChatSize = Size(720, 860);
|
||||
const detachedTerminalSize = Size(960, 600);
|
||||
const detachedDiffSize = Size(1000, 820);
|
||||
|
||||
/// The main window's side of detached windows: opening them (see
|
||||
/// [DetachedWindowOpener]) and taking items back from them.
|
||||
class DetachedWindows implements DetachedWindowOpener {
|
||||
DetachedWindows({
|
||||
DetachedPlatform? platform,
|
||||
required this.onReturn,
|
||||
GlobalKey<ScaffoldMessengerState>? messenger,
|
||||
}) : platform = platform ?? DetachedPlatform.instance,
|
||||
_messenger = messenger ?? appScaffoldMessengerKey;
|
||||
|
||||
final DetachedPlatform platform;
|
||||
|
||||
/// Puts an item a detached window gave back into the main window.
|
||||
final void Function(DetachedReturn item) onReturn;
|
||||
final GlobalKey<ScaffoldMessengerState> _messenger;
|
||||
StreamSubscription<DetachedMessage>? _messages;
|
||||
|
||||
bool get supported => platform.supported;
|
||||
|
||||
void start() {
|
||||
if (!supported || _messages != null) return;
|
||||
_messages = platform.messages.listen((message) {
|
||||
final item = DetachedReturn.fromMessage(message);
|
||||
if (item != null) onReturn(item);
|
||||
});
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
unawaited(_messages?.cancel());
|
||||
_messages = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void openChat(
|
||||
String sessionId, {
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
}) {
|
||||
final route = DetachedRoute.chat(sessionId);
|
||||
if (route == null) return;
|
||||
unawaited(_open(route, title, detachedChatSize, onOpened));
|
||||
}
|
||||
|
||||
@override
|
||||
void openTerminal({
|
||||
String tabKey = '',
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
}) => unawaited(
|
||||
_open(
|
||||
DetachedRoute.terminal(tabKey),
|
||||
title,
|
||||
detachedTerminalSize,
|
||||
onOpened,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
void openDiff(
|
||||
List<Map<String, Object?>> files, {
|
||||
int initialIndex = 0,
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
}) {
|
||||
final token = _token();
|
||||
final route = DetachedRoute.diff(token)!;
|
||||
// The hand-over is written before the window opens, so its first read
|
||||
// finds it. A popup must open within the click: on the web the write is
|
||||
// synchronous, so no frame passes before it.
|
||||
final written = platform.put(
|
||||
token,
|
||||
jsonEncode({'files': files, 'index': initialIndex}),
|
||||
);
|
||||
unawaited(
|
||||
written.then((_) => _open(route, title, detachedDiffSize, onOpened)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _open(
|
||||
DetachedRoute route,
|
||||
String title,
|
||||
Size size,
|
||||
VoidCallback? onOpened,
|
||||
) async {
|
||||
switch (await platform.launch(route, title: title, size: size)) {
|
||||
case DetachedLaunch.opened:
|
||||
onOpened?.call();
|
||||
case DetachedLaunch.blocked:
|
||||
_say(
|
||||
'The browser blocked the new window. Allow pop-ups for this site, '
|
||||
'or open it in a tab.',
|
||||
action: SnackBarAction(
|
||||
label: 'Open in tab',
|
||||
onPressed: () => unawaited(_openTab(route, title, size, onOpened)),
|
||||
),
|
||||
);
|
||||
case DetachedLaunch.failed:
|
||||
_say('Could not open a new window.');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openTab(
|
||||
DetachedRoute route,
|
||||
String title,
|
||||
Size size,
|
||||
VoidCallback? onOpened,
|
||||
) async {
|
||||
final result = await platform.launch(
|
||||
route,
|
||||
title: title,
|
||||
size: size,
|
||||
tab: true,
|
||||
);
|
||||
if (result == DetachedLaunch.opened) {
|
||||
onOpened?.call();
|
||||
} else {
|
||||
_say('Could not open a new tab either.');
|
||||
}
|
||||
}
|
||||
|
||||
void _say(String text, {SnackBarAction? action}) =>
|
||||
_messenger.currentState?.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(text),
|
||||
action: action,
|
||||
duration: Duration(seconds: action == null ? 4 : 10),
|
||||
),
|
||||
);
|
||||
|
||||
static final _random = Random.secure();
|
||||
|
||||
static String _token() => base64Url
|
||||
.encode(List.generate(12, (_) => _random.nextInt(256)))
|
||||
.replaceAll('=', '');
|
||||
}
|
||||
@@ -57,7 +57,12 @@ import 'app_terminals.dart';
|
||||
import '../features/chat/chat_run_opener.dart';
|
||||
import '../features/chat/chat_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<PipelinesApp>
|
||||
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<PipelinesApp>
|
||||
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<PipelinesApp>
|
||||
_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<PipelinesApp>
|
||||
@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<PipelinesApp>
|
||||
|
||||
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.
|
||||
|
||||
@@ -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<PipelinesRoot> {
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!_onboarding && widget.detached != null) {
|
||||
return DetachedWindowApp(
|
||||
key: ValueKey(_generation),
|
||||
route: widget.detached!,
|
||||
server: _server,
|
||||
client: _client,
|
||||
chatPool: _chatPool,
|
||||
servers: _servers,
|
||||
serverId: _servers.catalog.active?.id,
|
||||
serverAddresses: widget.web
|
||||
? null
|
||||
: _servers.catalog.active?.endpoints.map(Uri.parse).toList(),
|
||||
);
|
||||
}
|
||||
if (!_onboarding) {
|
||||
return PipelinesApp(
|
||||
androidSupported: widget.nativeUpdatesSupported,
|
||||
|
||||
@@ -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<ArtifactTransferResult> saveArtifactFile(ArtifactFile file) async {
|
||||
try {
|
||||
|
||||
@@ -12,7 +12,12 @@ const ValueKey<String> runArtifactsButtonKey = ValueKey<String>(
|
||||
'run-detail-artifacts',
|
||||
);
|
||||
|
||||
const Set<String> _executingStatuses = {'queued', 'running', 'waiting'};
|
||||
const Set<String> _executingStatuses = {
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
'waiting_quota',
|
||||
};
|
||||
|
||||
/// The detail's `steps` exactly as returned by the server. The pushed page
|
||||
/// snapshots the returned list once, so it never re-derives on each rebuild.
|
||||
|
||||
@@ -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<InertHtmlView> {
|
||||
@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<InertHtmlView> {
|
||||
}
|
||||
|
||||
@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,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<void> _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<void> _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,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -82,6 +84,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<String, Object?> toJson() => {
|
||||
'path': path,
|
||||
'kind': kind.name,
|
||||
'patch': ?patch,
|
||||
if (binary) 'binary': true,
|
||||
if (truncated) 'truncated': true,
|
||||
'no_patch_reason': ?noPatchReason,
|
||||
'before_mode': ?beforeMode,
|
||||
'after_mode': ?afterMode,
|
||||
if (steps.isNotEmpty) 'steps': steps,
|
||||
};
|
||||
|
||||
/// Reads back an entry [toJson] wrote, stages included.
|
||||
static FileChange? fromHandover(Object? value) {
|
||||
final file = tryParse(value);
|
||||
if (file == null || value is! Map) return file;
|
||||
final steps = value['steps'];
|
||||
return steps is List && steps.isNotEmpty
|
||||
? file.withSteps([for (final step in steps) '$step'])
|
||||
: file;
|
||||
}
|
||||
|
||||
/// Parses one server file entry; null when it has no usable path. The
|
||||
/// capture owns the decision to skip such an entry, so it is never rendered
|
||||
/// as an anonymous row.
|
||||
|
||||
@@ -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<FileChange> 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<Widget> actions;
|
||||
|
||||
@override
|
||||
State<FileDiffPage> createState() => _FileDiffPageState();
|
||||
}
|
||||
@@ -184,6 +191,25 @@ class _FileDiffPageState extends State<FileDiffPage> {
|
||||
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<FileDiffPage> {
|
||||
),
|
||||
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<FileDiffPage> {
|
||||
_all ? Icons.article_outlined : Icons.view_agenda_outlined,
|
||||
),
|
||||
),
|
||||
...widget.actions,
|
||||
],
|
||||
),
|
||||
body: body,
|
||||
|
||||
@@ -25,6 +25,8 @@ mixin _ChatScreenFloat on State<ChatScreen>, _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<ChatScreen>, _ChatScreenWorkspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// [sessionId] went to a window of its own: its panes leave the tiling,
|
||||
/// as a floated pane does, and the list shows when none is left.
|
||||
void _releaseSession(String sessionId) {
|
||||
if (!mounted) return;
|
||||
final panes = _workspace.panes.where((p) => p.sessionId == sessionId);
|
||||
if (panes.isEmpty) return;
|
||||
for (final pane in panes.toList()) {
|
||||
_workspace.detach(pane.id);
|
||||
}
|
||||
_syncOpenWorkspace();
|
||||
if (_workspace.paneCount == 0) _back();
|
||||
}
|
||||
|
||||
void _dockSession(String sessionId) {
|
||||
if (!mounted) return;
|
||||
_workspaceVisible = true;
|
||||
@@ -75,15 +90,25 @@ mixin _ChatScreenFloat on State<ChatScreen>, _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<Widget> _floatControls(ChatWorkspacePane pane) {
|
||||
if (!_floatsHere || !_workspace.canFloat(pane.id)) return const [];
|
||||
final windows = widget.windows;
|
||||
if (windows == null || !_workspace.canFloat(pane.id)) return const [];
|
||||
return [
|
||||
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,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,12 @@ mixin _ChatScreenPaneMenu on State<ChatScreen>, _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<ChatScreen>, _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);
|
||||
|
||||
@@ -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<void> _readPasteboard(
|
||||
@@ -121,4 +124,5 @@ String chatNothingToPasteMessage(List<String> 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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../pipelines/pipeline_format.dart' show formatDuration;
|
||||
import '../../runs/domain/run_events.dart' show isTerminalRunStatus;
|
||||
import '../../runs/domain/run_quota.dart';
|
||||
|
||||
/// A `show_run` item's run, as the server records it
|
||||
/// (`internal/protocol/chat_shown.go` ChatShownRunBody). The server pushes the
|
||||
@@ -49,6 +50,7 @@ class ChatShownRun {
|
||||
|
||||
/// The status in words: the outcome of a finished run when it says more.
|
||||
String get statusLabel {
|
||||
if (isWaitingQuotaStatus(status)) return runWaitingQuotaLabel;
|
||||
final word = status.isEmpty ? 'unknown' : status;
|
||||
final label = '${word[0].toUpperCase()}${word.substring(1)}';
|
||||
return finished && outcome.isNotEmpty && outcome != status
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -14,6 +14,7 @@ IconData chatShownRunIcon(String status) => switch (status) {
|
||||
'canceled' => Icons.cancel_outlined,
|
||||
'interrupted' => Icons.pause_circle_outline,
|
||||
'waiting' => Icons.front_hand_outlined,
|
||||
'waiting_quota' => Icons.hourglass_bottom,
|
||||
'queued' => Icons.schedule,
|
||||
_ => Icons.play_circle_outline,
|
||||
};
|
||||
@@ -21,7 +22,7 @@ IconData chatShownRunIcon(String status) => switch (status) {
|
||||
Color _statusColor(ColorScheme colors, String status) => switch (status) {
|
||||
'succeeded' => colors.primary,
|
||||
'failed' || 'interrupted' => colors.error,
|
||||
'waiting' => colors.tertiary,
|
||||
'waiting' || 'waiting_quota' => colors.tertiary,
|
||||
_ => colors.onSurfaceVariant,
|
||||
};
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// The `check` stage type: a model-free stage that runs shell commands and
|
||||
// routes `pass`/`fail` (plus `error`). Its `delivery` config marks the landing
|
||||
// gate, which runs the commands in a fresh worktree and fast-forwards main on
|
||||
// pass. Pure data only; an older graph simply has no check stages.
|
||||
|
||||
/// The stage type word the server uses for a check stage.
|
||||
const String checkStageType = 'check';
|
||||
|
||||
/// Whether [stage] (a graph stage declaration) is a check stage.
|
||||
bool isCheckStage(dynamic stage) =>
|
||||
stage is Map && '${stage['type'] ?? ''}'.trim() == checkStageType;
|
||||
|
||||
/// Whether a check [stage] is the delivery (landing) gate.
|
||||
///
|
||||
/// Configs are strings on the wire (`"true"`); a JSON boolean is accepted too.
|
||||
bool isDeliveryGate(dynamic stage) {
|
||||
if (!isCheckStage(stage)) return false;
|
||||
final configs = (stage as Map)['configs'];
|
||||
if (configs is! Map) return false;
|
||||
final value = configs['delivery'];
|
||||
return value == true || '${value ?? ''}'.trim().toLowerCase() == 'true';
|
||||
}
|
||||
|
||||
/// The check stage's commands, one per non-blank line of `blocks.commands`
|
||||
/// (a list of strings is read item by item), in declared order.
|
||||
List<String> checkCommands(dynamic stage) {
|
||||
if (stage is! Map) return const <String>[];
|
||||
final blocks = stage['blocks'];
|
||||
if (blocks is! Map) return const <String>[];
|
||||
final raw = blocks['commands'];
|
||||
final lines = raw is List
|
||||
? [for (final item in raw) '${item ?? ''}']
|
||||
: '${raw ?? ''}'.split('\n');
|
||||
return [
|
||||
for (final line in lines)
|
||||
if (line.trim().isNotEmpty) line.trimRight(),
|
||||
];
|
||||
}
|
||||
|
||||
/// The short kind a graph node shows under its name: `Check` or
|
||||
/// `Delivery gate`, or null for every other stage type.
|
||||
String? checkStageCaption({required String type, required bool delivery}) {
|
||||
if (type.trim() != checkStageType) return null;
|
||||
return delivery ? 'Delivery gate' : 'Check';
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'check_stage.dart';
|
||||
import 'graph_protocol.dart';
|
||||
|
||||
/// 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<GraphNode> 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));
|
||||
|
||||
@@ -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<StageDefinitionField> stageDefinitionFields(dynamic stage) {
|
||||
if (stage is! Map) return const <StageDefinitionField>[];
|
||||
final type = effectiveStageType(stage['type']);
|
||||
final fields = <StageDefinitionField>[
|
||||
StageDefinitionField('Type', effectiveStageType(stage['type'])),
|
||||
StageDefinitionField(
|
||||
'Type',
|
||||
isDeliveryGate(stage) ? '$type (delivery gate)' : type,
|
||||
),
|
||||
];
|
||||
|
||||
// A check stage runs commands where a model stage has its prompt.
|
||||
final commands = checkCommands(stage);
|
||||
if (isCheckStage(stage) && commands.isNotEmpty) {
|
||||
fields.add(
|
||||
StageDefinitionField(
|
||||
'Commands',
|
||||
commands.join('\n'),
|
||||
block: true,
|
||||
monospace: true,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final prompt = _text(stage['prompt']);
|
||||
if (prompt.trim().isNotEmpty) {
|
||||
fields.add(StageDefinitionField('Prompt', prompt, block: true));
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -29,6 +29,7 @@ const runStatusFilters = <String>[
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
'waiting_quota',
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
|
||||
@@ -64,6 +64,7 @@ const _runStateAliases = <String, String>{
|
||||
'running': 'running',
|
||||
'queued': 'queued',
|
||||
'waiting': 'waiting',
|
||||
'waiting_quota': 'waiting_quota',
|
||||
'active': 'active',
|
||||
'succeeded': 'succeeded',
|
||||
'success': 'succeeded',
|
||||
@@ -88,6 +89,7 @@ String runStateOf(String? status) {
|
||||
/// `Running`-style title for a run state.
|
||||
String runStateLabel(String? status) {
|
||||
final state = runStateOf(status);
|
||||
if (state == 'waiting_quota') return 'Waiting for usage limit';
|
||||
return state.isEmpty
|
||||
? state
|
||||
: '${state[0].toUpperCase()}${state.substring(1)}';
|
||||
|
||||
@@ -8,12 +8,14 @@ import '../../../core/api_gateway.dart';
|
||||
///
|
||||
/// The status word alone is not enough: a stale `running` status without
|
||||
/// `executing` is not cancellable, while a run waiting on a pending session
|
||||
/// export is.
|
||||
/// export is. A run parked in `waiting_quota` has no live executor but the
|
||||
/// server cancels it directly, so it is cancellable too.
|
||||
bool canCancelRun(JsonMap? run) {
|
||||
if (run == null) return false;
|
||||
final exportPending = _number(run['export_pending_sequence']);
|
||||
return (run['executing'] == true ||
|
||||
(run['status'] == 'waiting' && exportPending > 0)) &&
|
||||
(run['status'] == 'waiting' && exportPending > 0) ||
|
||||
run['status'] == 'waiting_quota') &&
|
||||
run['cancel_requested'] != true &&
|
||||
run['cleanup_unconfirmed'] != true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import '../domain/run_quota.dart';
|
||||
|
||||
const resumeQuotaActionLabel = 'Resume now';
|
||||
const resumeQuotaActionKey = ValueKey<String>('resume-quota-run-action');
|
||||
const resumeQuotaErrorKey = ValueKey<String>('resume-quota-run-error');
|
||||
|
||||
/// Whether [run] is parked for a usage limit and may be resumed now.
|
||||
bool canResumeQuotaRun(JsonMap? run) =>
|
||||
run != null &&
|
||||
run['id'] is num &&
|
||||
isWaitingQuotaStatus(run['status']) &&
|
||||
run['cancel_requested'] != true;
|
||||
|
||||
/// "Resume now" for a run parked in `waiting_quota`: one `resume_run` request
|
||||
/// whose accepted `run_detail` reaches [onRunChanged]. A refusal is shown
|
||||
/// beside the button verbatim and leaves the button for a deliberate retry.
|
||||
class ResumeQuotaRunAction extends StatefulWidget {
|
||||
const ResumeQuotaRunAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<ResumeQuotaRunAction> createState() => _ResumeQuotaRunActionState();
|
||||
}
|
||||
|
||||
class _ResumeQuotaRunActionState extends State<ResumeQuotaRunAction> {
|
||||
bool _sending = false;
|
||||
String? _error;
|
||||
|
||||
Future<void> _resume() async {
|
||||
final id = widget.run['id'];
|
||||
if (_sending || id is! num || !canResumeQuotaRun(widget.run)) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).resumeRun(id);
|
||||
if (mounted && widget.run['id'] == id) widget.onRunChanged(run);
|
||||
} catch (error) {
|
||||
final message = '$error'.trim();
|
||||
if (mounted) {
|
||||
setState(
|
||||
() => _error = message.isEmpty
|
||||
? 'The server did not resume the run.'
|
||||
: message,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!canResumeQuotaRun(widget.run)) return const SizedBox.shrink();
|
||||
final error = _error;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
OutlinedButton(
|
||||
key: resumeQuotaActionKey,
|
||||
onPressed: _sending ? null : _resume,
|
||||
child: const Text(resumeQuotaActionLabel),
|
||||
),
|
||||
if (error != null)
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error,
|
||||
key: resumeQuotaErrorKey,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,12 @@ class RunsRepository {
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
/// Resumes a run parked in `waiting_quota` now instead of at its reset.
|
||||
Future<JsonMap> resumeRun(num id) async => _required(
|
||||
await _gateway.call('resume_run', {'run_id': id}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
/// Deletes finished runs and their recorded data. The server answers
|
||||
/// `runs_deleted` with the ids it removed, the ones it refused (with its
|
||||
/// reason) and the bytes it freed.
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// A check stage visit's recorded output: the per-command results the server
|
||||
// ran for a `check` stage, read without widget imports.
|
||||
//
|
||||
// Only an output map carrying a `checks` list is a check output; older
|
||||
// servers never send one, so every other step keeps its ordinary rendering.
|
||||
|
||||
/// How one command ended. [unknown] keeps a status this client does not know
|
||||
/// (its raw word stays in [CheckCommandResult.statusWord]).
|
||||
enum CheckCommandStatus { passed, failed, timedOut, notRun, unknown }
|
||||
|
||||
CheckCommandStatus checkCommandStatus(String word) =>
|
||||
switch (word.trim().toLowerCase()) {
|
||||
'passed' => CheckCommandStatus.passed,
|
||||
'failed' => CheckCommandStatus.failed,
|
||||
'timed_out' => CheckCommandStatus.timedOut,
|
||||
'not_run' => CheckCommandStatus.notRun,
|
||||
_ => CheckCommandStatus.unknown,
|
||||
};
|
||||
|
||||
/// The status as the row reads it; an unknown status shows its raw word.
|
||||
String checkStatusLabel(CheckCommandResult check) => switch (check.status) {
|
||||
CheckCommandStatus.passed => 'Passed',
|
||||
CheckCommandStatus.failed => 'Failed',
|
||||
CheckCommandStatus.timedOut => 'Timed out',
|
||||
CheckCommandStatus.notRun => 'Not run',
|
||||
CheckCommandStatus.unknown =>
|
||||
check.statusWord.isEmpty ? 'Unknown status' : check.statusWord,
|
||||
};
|
||||
|
||||
/// One command's recorded result.
|
||||
class CheckCommandResult {
|
||||
const CheckCommandResult({
|
||||
required this.command,
|
||||
required this.statusWord,
|
||||
this.exitCode,
|
||||
this.durationMs,
|
||||
this.output = '',
|
||||
this.truncated = false,
|
||||
});
|
||||
|
||||
final String command;
|
||||
|
||||
/// The server's status word verbatim.
|
||||
final String statusWord;
|
||||
|
||||
/// Null when not recorded (a command that never ran has none).
|
||||
final int? exitCode;
|
||||
final int? durationMs;
|
||||
final String output;
|
||||
|
||||
/// Whether the server cut [output] at its capture limit.
|
||||
final bool truncated;
|
||||
|
||||
CheckCommandStatus get status => checkCommandStatus(statusWord);
|
||||
|
||||
/// `exit 1 · 51s`, leaving out whichever fact was not recorded.
|
||||
String get meta => [
|
||||
if (exitCode != null) 'exit $exitCode',
|
||||
if (durationMs != null) formatCheckDuration(durationMs!),
|
||||
].join(' · ');
|
||||
}
|
||||
|
||||
/// A check visit's whole recorded output.
|
||||
class CheckStepOutput {
|
||||
const CheckStepOutput({
|
||||
required this.checks,
|
||||
this.summary,
|
||||
this.markdown,
|
||||
this.delivery = false,
|
||||
});
|
||||
|
||||
final List<CheckCommandResult> checks;
|
||||
|
||||
/// The server's one-line summary (`1 of 2 checks failed: go test ./...`).
|
||||
final String? summary;
|
||||
|
||||
/// The handoff document the next stage reads.
|
||||
final String? markdown;
|
||||
|
||||
/// Whether this visit was the delivery gate.
|
||||
final bool delivery;
|
||||
}
|
||||
|
||||
/// The check output recorded in [output], or null when it is not one.
|
||||
CheckStepOutput? checkStepOutput(dynamic output) {
|
||||
if (output is! Map) return null;
|
||||
final checks = output['checks'];
|
||||
if (checks is! List) return null;
|
||||
return CheckStepOutput(
|
||||
checks: [
|
||||
for (final item in checks)
|
||||
if (item is Map) _check(item),
|
||||
],
|
||||
summary: _text(output['summary']),
|
||||
markdown: _text(output['markdown']),
|
||||
delivery: output['delivery'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
CheckCommandResult _check(Map item) => CheckCommandResult(
|
||||
command: '${item['command'] ?? ''}',
|
||||
statusWord: '${item['status'] ?? ''}'.trim(),
|
||||
exitCode: _int(item['exit_code']),
|
||||
durationMs: _int(item['duration_ms']),
|
||||
output: item['output'] is String ? item['output'] as String : '',
|
||||
truncated: item['truncated'] == true,
|
||||
);
|
||||
|
||||
/// A command duration: `850ms`, `2.1s`, `51s`, `3m 05s`.
|
||||
String formatCheckDuration(int ms) {
|
||||
if (ms < 1000) return '${ms}ms';
|
||||
if (ms < 10000) {
|
||||
final tenths = (ms / 100).round();
|
||||
return tenths % 10 == 0 ? '${tenths ~/ 10}s' : '${tenths / 10}s';
|
||||
}
|
||||
final seconds = (ms / 1000).round();
|
||||
if (seconds < 60) return '${seconds}s';
|
||||
final minutes = seconds ~/ 60;
|
||||
final rest = (seconds % 60).toString().padLeft(2, '0');
|
||||
if (minutes < 60) return '${minutes}m ${rest}s';
|
||||
return '${minutes ~/ 60}h ${(minutes % 60).toString().padLeft(2, '0')}m';
|
||||
}
|
||||
|
||||
int? _int(dynamic value) {
|
||||
if (value is num) return value.toInt();
|
||||
if (value is String) return int.tryParse(value.trim());
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _text(dynamic value) {
|
||||
if (value is! String) return null;
|
||||
return value.trim().isEmpty ? null : value;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_quota.dart';
|
||||
import 'run_step_evidence.dart';
|
||||
|
||||
/// ApiGateway preserves wire envelopes; callers may also supply an extracted
|
||||
@@ -16,7 +17,7 @@ bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
|
||||
|
||||
int runLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'queued' => 0,
|
||||
'running' || 'waiting' => 1,
|
||||
'running' || 'waiting' || runStatusWaitingQuota => 1,
|
||||
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
@@ -27,8 +28,19 @@ int stepLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
/// A run parks in waiting_quota from queued or running and leaves it for
|
||||
/// queued (a deferred launch) or running (a resumed visit), so a move into or
|
||||
/// out of it between live states is never stale.
|
||||
bool _quotaHop(dynamic current, dynamic incoming, int Function(dynamic) rank) =>
|
||||
(isWaitingQuotaStatus(current) || isWaitingQuotaStatus(incoming)) &&
|
||||
rank(current) >= 0 &&
|
||||
rank(current) < 2 &&
|
||||
rank(incoming) >= 0 &&
|
||||
rank(incoming) < 2;
|
||||
|
||||
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty) return false;
|
||||
if (_quotaHop(current, incoming, rank)) return false;
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
return oldRank >= 0 &&
|
||||
@@ -39,6 +51,7 @@ bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
|
||||
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
|
||||
if (_quotaHop(current, incoming, rank)) return '$incoming';
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
if (oldRank < 0) return '$incoming';
|
||||
@@ -50,7 +63,12 @@ String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
|
||||
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
|
||||
'queued' || 'running' => true,
|
||||
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
|
||||
'waiting' ||
|
||||
runStatusWaitingQuota ||
|
||||
'succeeded' ||
|
||||
'failed' ||
|
||||
'canceled' ||
|
||||
'interrupted' => false,
|
||||
_ => current,
|
||||
};
|
||||
|
||||
@@ -119,9 +137,16 @@ JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
|
||||
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
|
||||
if (!_blank(frame[key])) merged[key] = frame[key];
|
||||
}
|
||||
for (final key in ['failure_kind', 'failure_reason']) {
|
||||
for (final key in ['failure_kind', 'failure_reason', 'failure_class']) {
|
||||
if (frame[key] != null) merged[key] = frame[key];
|
||||
}
|
||||
// A status frame for waiting_quota carries the wait; any other status
|
||||
// clears it.
|
||||
if (status != runStatusWaitingQuota) {
|
||||
merged.remove('quota_wait');
|
||||
} else if (frame['quota_wait'] is Map) {
|
||||
merged['quota_wait'] = frame['quota_wait'];
|
||||
}
|
||||
// Snapshot and terminal frames carry the measured size; others omit it.
|
||||
if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes'];
|
||||
final oldExport = _positiveInt(current['export_pending_sequence']);
|
||||
@@ -173,6 +198,8 @@ JsonMap? newRunSummaryFromFrame(JsonMap frame) {
|
||||
'current_stage': frame['current_stage'] ?? '',
|
||||
'failure_kind': frame['failure_kind'] ?? '',
|
||||
'failure_reason': frame['failure_reason'] ?? '',
|
||||
'failure_class': frame['failure_class'] ?? '',
|
||||
if (frame['quota_wait'] is Map) 'quota_wait': frame['quota_wait'],
|
||||
'resource_wait': frame['resource_wait'],
|
||||
'cancel_requested': frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
|
||||
@@ -245,6 +272,7 @@ bool runDetailNeedsFullSync(JsonMap frame) {
|
||||
final stepStatus = step is Map ? step['status'] : null;
|
||||
return isTerminalRunStatus(frame['status']) ||
|
||||
isWaitingRunStatus(frame['status']) ||
|
||||
isWaitingQuotaStatus(frame['status']) ||
|
||||
frame['cancel_requested'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true ||
|
||||
isWaitingRunStatus(stepStatus) ||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// The operator wording of each server failure class, matching
|
||||
/// `protocol.FailureClassLabel` in `internal/protocol/run_quota.go`.
|
||||
const runFailureClassLabels = <String, String>{
|
||||
'quota': 'usage limit',
|
||||
'loop_exhausted': 'loop limit reached',
|
||||
'timeout': 'timed out',
|
||||
'permission_denied': 'permission denied',
|
||||
'harness_error': 'harness error',
|
||||
'blocked': 'blocked',
|
||||
'environment': 'environment problem',
|
||||
'canceled': 'canceled',
|
||||
'interrupted': 'interrupted',
|
||||
'budget': 'budget exhausted',
|
||||
'check_failed': 'check failed',
|
||||
'other': 'failed',
|
||||
};
|
||||
|
||||
/// The wording of [run]'s `failure_class`, or null when it has none. An
|
||||
/// unknown class from a newer server is shown verbatim, as the server does.
|
||||
String? runFailureClassLabel(JsonMap run) {
|
||||
final word = '${run['failure_class'] ?? ''}'.trim().toLowerCase();
|
||||
if (word.isEmpty) return null;
|
||||
return runFailureClassLabels[word] ?? word.replaceAll('_', ' ');
|
||||
}
|
||||
|
||||
/// The run's whole-run USD budget (`protocol.RunBudget`): absent, or a zero
|
||||
/// limit, means the run has no cap.
|
||||
typedef RunBudget = ({double limit, double spent, String source});
|
||||
|
||||
RunBudget? runBudget(JsonMap run) {
|
||||
final budget = run['budget'];
|
||||
if (budget is! Map) return null;
|
||||
final limit = budget['limit_usd'];
|
||||
final spent = budget['spent_usd'];
|
||||
if (limit is! num || limit <= 0) return null;
|
||||
return (
|
||||
limit: limit.toDouble(),
|
||||
spent: spent is num ? spent.toDouble() : 0,
|
||||
source: '${budget['source'] ?? ''}'.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
/// `$1.25 of $5.00 budget`, noting a server-wide default cap.
|
||||
String? runBudgetText(JsonMap run) {
|
||||
final budget = runBudget(run);
|
||||
if (budget == null) return null;
|
||||
final text =
|
||||
'\$${budget.spent.toStringAsFixed(2)} of '
|
||||
'\$${budget.limit.toStringAsFixed(2)} budget';
|
||||
return budget.source == 'server' ? '$text (server default)' : text;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import '../../pipelines/pipeline_format.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_quota.dart';
|
||||
import 'run_tokens.dart';
|
||||
|
||||
const runStates = [
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
runStatusWaitingQuota,
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
@@ -86,6 +88,7 @@ String runStateOf(dynamic status) =>
|
||||
'queued' ||
|
||||
'running' ||
|
||||
'waiting' ||
|
||||
runStatusWaitingQuota ||
|
||||
'active' ||
|
||||
'blocked' ||
|
||||
'skipped' => '${status ?? ''}'.trim().toLowerCase(),
|
||||
@@ -208,8 +211,11 @@ RunRowFacts runRowFacts(JsonMap run, DateTime now) {
|
||||
);
|
||||
}
|
||||
|
||||
String runStatusLabel(JsonMap run) {
|
||||
String runStatusLabel(JsonMap run, {DateTime? now}) {
|
||||
final status = '${run['status'] ?? ''}';
|
||||
if (status == runStatusWaitingQuota) {
|
||||
return waitingQuotaStatusLabel(run, now: now);
|
||||
}
|
||||
if (!{'queued', 'running', 'waiting'}.contains(status)) {
|
||||
return status.isEmpty ? 'unknown' : status;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_failure_class.dart';
|
||||
import 'run_models.dart' show runStateOf;
|
||||
|
||||
/// The longest result preview a succeeded run's row shows; a longer one is
|
||||
@@ -13,16 +14,27 @@ typedef RunOutcomeLine = ({String line, String full, bool failed});
|
||||
/// The row's outcome line, or null when the run recorded nothing to show.
|
||||
///
|
||||
/// A failed run shows its failure reason, else its diagnostic's first
|
||||
/// non-blank line. A succeeded run shows its result preview only when it is
|
||||
/// non-blank line, after the server's failure class when it recorded one
|
||||
/// (`Failed · usage limit: <reason>`; the catch-all `other` adds nothing). A succeeded run shows its result preview only when it is
|
||||
/// short (at most [runResultPreviewRowLimit] characters on one line).
|
||||
RunOutcomeLine? runOutcomeLine(JsonMap run) {
|
||||
final state = runStateOf(run['status']);
|
||||
if (state == 'failed' && run['executing'] != true) {
|
||||
final reason = '${run['failure_reason'] ?? ''}'.trim();
|
||||
final diagnostic = '${run['diagnostic'] ?? ''}'.trim();
|
||||
final full = reason.isNotEmpty ? reason : diagnostic;
|
||||
if (full.isEmpty) return null;
|
||||
return (line: firstLine(full), full: full, failed: true);
|
||||
final text = reason.isNotEmpty ? reason : diagnostic;
|
||||
final label = runFailureClassLabel(run);
|
||||
if (label == null || label == runFailureClassLabels['other']) {
|
||||
if (text.isEmpty) return null;
|
||||
return (line: firstLine(text), full: text, failed: true);
|
||||
}
|
||||
final prefix = 'Failed · $label';
|
||||
if (text.isEmpty) return (line: prefix, full: prefix, failed: true);
|
||||
return (
|
||||
line: '$prefix: ${firstLine(text)}',
|
||||
full: '$prefix: $text',
|
||||
failed: true,
|
||||
);
|
||||
}
|
||||
if (state == 'succeeded') {
|
||||
final preview = '${run['result_preview'] ?? ''}'.trim();
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../pipelines/pipeline_format.dart'
|
||||
show formatLocalTimestamp, parseInstant;
|
||||
|
||||
/// The server's status word for a run parked until a provider usage limit
|
||||
/// resets (`protocol.RunStatusWaitingQuota`). It is not terminal: the server
|
||||
/// resumes the run on its own after the reset, or on `resume_run`.
|
||||
const runStatusWaitingQuota = 'waiting_quota';
|
||||
|
||||
/// The operator's words for [runStatusWaitingQuota].
|
||||
const runWaitingQuotaLabel = 'Waiting for usage limit';
|
||||
|
||||
bool isWaitingQuotaStatus(dynamic status) =>
|
||||
'${status ?? ''}'.trim().toLowerCase() == runStatusWaitingQuota;
|
||||
|
||||
/// A parked run's `quota_wait` (`protocol.RunQuotaWait`). [sequence] is the
|
||||
/// interrupted visit, 0 when the run was deferred before its first stage.
|
||||
typedef RunQuotaWait = ({
|
||||
DateTime? resetsAt,
|
||||
DateTime? resumeAt,
|
||||
int sequence,
|
||||
String stage,
|
||||
String account,
|
||||
});
|
||||
|
||||
/// The run's quota wait, or null when it carries none.
|
||||
RunQuotaWait? runQuotaWait(JsonMap run) {
|
||||
final wait = run['quota_wait'];
|
||||
if (wait is! Map) return null;
|
||||
final sequence = wait['sequence'];
|
||||
return (
|
||||
resetsAt: parseInstant('${wait['resets_at'] ?? ''}'),
|
||||
resumeAt: parseInstant('${wait['resume_at'] ?? ''}'),
|
||||
sequence: sequence is num ? sequence.toInt() : 0,
|
||||
stage: '${wait['stage'] ?? ''}'.trim(),
|
||||
account: '${wait['account'] ?? ''}'.trim(),
|
||||
);
|
||||
}
|
||||
|
||||
/// [instant] in local time: `HH:mm` on [now]'s local day, else `d MMM HH:mm`.
|
||||
String quotaClockText(DateTime instant, {DateTime? now}) {
|
||||
final local = instant.toLocal();
|
||||
final today = (now ?? DateTime.now()).toLocal();
|
||||
if (local.year == today.year &&
|
||||
local.month == today.month &&
|
||||
local.day == today.day) {
|
||||
String two(int value) => value.toString().padLeft(2, '0');
|
||||
return '${two(local.hour)}:${two(local.minute)}';
|
||||
}
|
||||
return formatLocalTimestamp(local.toUtc().toIso8601String()) ?? '';
|
||||
}
|
||||
|
||||
/// `resumes 09:01`, or null when the server sent no usable resume time.
|
||||
String? quotaResumeText(RunQuotaWait? wait, {DateTime? now}) {
|
||||
final at = wait?.resumeAt ?? wait?.resetsAt;
|
||||
return at == null ? null : 'resumes ${quotaClockText(at, now: now)}';
|
||||
}
|
||||
|
||||
/// The status line of a parked run: `Waiting for usage limit · resumes 09:01`.
|
||||
String waitingQuotaStatusLabel(JsonMap run, {DateTime? now}) {
|
||||
final resume = quotaResumeText(runQuotaWait(run), now: now);
|
||||
return resume == null
|
||||
? runWaitingQuotaLabel
|
||||
: '$runWaitingQuotaLabel · $resume';
|
||||
}
|
||||
|
||||
/// The facts under a parked run's notice: the reset time, the account that
|
||||
/// hit the limit and the interrupted stage, each only when recorded.
|
||||
String quotaWaitMeta(RunQuotaWait wait, {DateTime? now}) => [
|
||||
if (wait.resetsAt case final at?)
|
||||
'Limit resets ${quotaClockText(at, now: now)}',
|
||||
if (quotaResumeText(wait, now: now) case final resume?) 'run $resume',
|
||||
if (wait.account.isNotEmpty) 'account ${wait.account}',
|
||||
if (wait.stage.isNotEmpty) 'at ${wait.stage}',
|
||||
].join(' · ');
|
||||
@@ -19,7 +19,7 @@ List<JsonMap> runDetailChangeSteps(JsonMap run) {
|
||||
return const <JsonMap>[];
|
||||
}
|
||||
|
||||
const _executingStatuses = {'queued', 'running', 'waiting'};
|
||||
const _executingStatuses = {'queued', 'running', 'waiting', 'waiting_quota'};
|
||||
|
||||
/// Whether the run detail offers the action at all. The opened page is a
|
||||
/// snapshot of the recorded steps, so it is offered only once nothing is
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import '../actions/cancel_run_action.dart';
|
||||
import '../actions/retry_action.dart';
|
||||
import '../actions/retry_eligibility.dart';
|
||||
import 'run_decision_notice.dart';
|
||||
import 'run_quota_notice.dart';
|
||||
|
||||
/// Native actions on the loaded run, all using the app's one gateway and
|
||||
/// applying only accepted server detail through the same controller callback.
|
||||
@@ -60,6 +61,7 @@ class RunDetailActions extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged),
|
||||
RunQuotaNotice(run: run, gateway: gateway, onRunChanged: onRunChanged),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../pipelines/pipeline_format.dart';
|
||||
import '../domain/run_deletion.dart' show formatByteSize, runSizeBytes;
|
||||
import '../domain/run_failure_class.dart' show runBudgetText;
|
||||
import '../domain/run_tokens.dart';
|
||||
import 'run_detail_visit_facts.dart';
|
||||
|
||||
@@ -68,6 +69,7 @@ List<DetailSummaryRow> detailSummaryRows(JsonMap run, {DateTime? now}) {
|
||||
add('Tokens', tokenUsageDetail(usage));
|
||||
add('Cost', tokenUsageCost(usage));
|
||||
}
|
||||
add('Budget', runBudgetText(run));
|
||||
final retryOf = _number(run['retry_of'])?.toInt() ?? 0;
|
||||
if (retryOf > 0) add('Retry of', 'run $retryOf');
|
||||
// A diagnostic is a recorded document: its own whitespace is preserved, but a
|
||||
|
||||
@@ -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']);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../actions/resume_quota_action.dart';
|
||||
import '../domain/run_quota.dart';
|
||||
|
||||
/// A run parked until a usage limit resets: when the limit resets and the run
|
||||
/// resumes, the account that hit it, and "Resume now". The run's Cancel stays
|
||||
/// with the other run actions. Nothing for any other run.
|
||||
class RunQuotaNotice extends StatelessWidget {
|
||||
const RunQuotaNotice({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
this.now,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
/// The clock, for tests.
|
||||
final DateTime? now;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!isWaitingQuotaStatus(run['status'])) return const SizedBox.shrink();
|
||||
final wait = runQuotaWait(run);
|
||||
final meta = wait == null ? '' : quotaWaitMeta(wait, now: now);
|
||||
final color = Theme.of(context).colorScheme.tertiary;
|
||||
return Container(
|
||||
key: const Key('run-quota-banner'),
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.only(top: 8, bottom: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.hourglass_bottom, color: color, size: 18),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Semantics(
|
||||
header: true,
|
||||
child: const Text(
|
||||
runWaitingQuotaLabel,
|
||||
style: TextStyle(fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
if (meta.isNotEmpty) ...[
|
||||
const SizedBox(height: 2),
|
||||
Text(meta, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
ResumeQuotaRunAction(
|
||||
run: run,
|
||||
gateway: gateway,
|
||||
onRunChanged: onRunChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<void> 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<void> save() async {
|
||||
if (!persist) return;
|
||||
final revision = _revision;
|
||||
final saved = await _store.save(
|
||||
jsonEncode({
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+1
-1
@@ -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<String> args) => runPipelinesApp(args: args);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// Opens an item of the app in a window of its own: a browser window on the
|
||||
/// web, a second app process on a desktop (see `notes/detached-windows.md`).
|
||||
///
|
||||
/// Each call removes nothing itself: [onOpened] runs once the window really
|
||||
/// opened (at once, or after the operator allowed a blocked popup), and the
|
||||
/// caller then takes the item out of the main window.
|
||||
abstract interface class DetachedWindowOpener {
|
||||
void openChat(
|
||||
String sessionId, {
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
});
|
||||
|
||||
/// The terminal on [tabKey] (empty: whichever tab it selects).
|
||||
void openTerminal({
|
||||
String tabKey = '',
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
});
|
||||
|
||||
/// A diff's files, as the server's `file_changes.files[]` entries.
|
||||
void openDiff(
|
||||
List<Map<String, Object?>> files, {
|
||||
int initialIndex = 0,
|
||||
required String title,
|
||||
VoidCallback? onOpened,
|
||||
});
|
||||
}
|
||||
|
||||
/// Hands the app's [DetachedWindowOpener] to the screens that offer
|
||||
/// "Open in new window". Absent where the platform has no windows (Android,
|
||||
/// iOS) and inside a detached window itself.
|
||||
class DetachedWindowScope extends InheritedWidget {
|
||||
const DetachedWindowScope({
|
||||
super.key,
|
||||
required this.opener,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
final DetachedWindowOpener opener;
|
||||
|
||||
static DetachedWindowOpener? maybeOf(BuildContext context) =>
|
||||
context.getInheritedWidgetOfExactType<DetachedWindowScope>()?.opener;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(DetachedWindowScope oldWidget) =>
|
||||
opener != oldWidget.opener;
|
||||
}
|
||||
|
||||
/// The menus' label for the action.
|
||||
const detachedWindowLabel = 'Open in new window';
|
||||
|
||||
/// Whether [event] sends the chat with the keyboard to a new window:
|
||||
/// Alt+Shift+Y (Option+Shift+Y). Alt+Y alone is Float.
|
||||
bool detachedWindowShortcut(KeyEvent event, HardwareKeyboard keyboard) {
|
||||
if (event is KeyUpEvent || !keyboard.isAltPressed) return false;
|
||||
if (!keyboard.isShiftPressed) return false;
|
||||
if (keyboard.isControlPressed || keyboard.isMetaPressed) return false;
|
||||
// Option+Shift+Y types a symbol on a Mac: match the key's position too.
|
||||
return event.logicalKey == LogicalKeyboardKey.keyY ||
|
||||
event.physicalKey == PhysicalKeyboardKey.keyY;
|
||||
}
|
||||
|
||||
/// The shortcut as it reads on this platform.
|
||||
String detachedWindowShortcutLabel([TargetPlatform? platform]) =>
|
||||
switch (platform ?? defaultTargetPlatform) {
|
||||
TargetPlatform.macOS || TargetPlatform.iOS => 'Option+Shift+Y',
|
||||
_ => 'Alt+Shift+Y',
|
||||
};
|
||||
|
||||
/// The label with the shortcut, for the chat menus.
|
||||
String detachedChatWindowLabel() =>
|
||||
'$detachedWindowLabel (${detachedWindowShortcutLabel()})';
|
||||
@@ -3,7 +3,7 @@ import 'package:flutter/material.dart';
|
||||
/// The shared status glyph whose tooltip and accessible name say the state.
|
||||
///
|
||||
/// [state] is the normalised run state (`succeeded`, `failed`, `running`,
|
||||
/// `waiting`, `queued`, `canceled`, `interrupted`, anything else unknown);
|
||||
/// `waiting`, `waiting_quota`, `queued`, `canceled`, `interrupted`, anything else unknown);
|
||||
/// [label] is the word a person reads. Colours are the platform's dynamic
|
||||
/// system colours, so the glyph keeps its contrast in light and dark themes.
|
||||
class RunStatusIcon extends StatelessWidget {
|
||||
@@ -45,7 +45,8 @@ Color runStatusColor(String state, [ColorScheme? colorScheme]) {
|
||||
'failed' => dark ? const Color(0xFFFF453A) : const Color(0xFFFF3B30),
|
||||
'running' ||
|
||||
'active' => dark ? const Color(0xFF0A84FF) : const Color(0xFF007AFF),
|
||||
'waiting' => dark ? const Color(0xFFFFD60A) : const Color(0xFFFFCC00),
|
||||
'waiting' ||
|
||||
'waiting_quota' => dark ? const Color(0xFFFFD60A) : const Color(0xFFFFCC00),
|
||||
'interrupted' => dark ? const Color(0xFFFF9F0A) : const Color(0xFFFF9500),
|
||||
_ => const Color(0xFF8E8E93),
|
||||
};
|
||||
@@ -58,6 +59,8 @@ IconData _materialIcon(String state) => switch (state) {
|
||||
'canceled' => Icons.block,
|
||||
'interrupted' => Icons.pause_circle_outline,
|
||||
'waiting' => Icons.person_outline,
|
||||
// Parked until a usage limit resets: a timer, not a person.
|
||||
'waiting_quota' => Icons.hourglass_bottom,
|
||||
'queued' => Icons.schedule,
|
||||
_ => Icons.help_outline,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user