diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 1652a229..29ff7a06 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -53,6 +53,7 @@ import '../shell/windows/window_kind.dart'; import '../shell/windows/window_manager.dart'; import '../shell/windows/window_store.dart'; import 'app_terminals.dart'; +import '../features/chat/chat_run_opener.dart'; import '../features/chat/chat_runtime.dart'; import '../features/changes/windows/diff_windows.dart'; import '../features/chat/windows/chat_windows.dart'; @@ -736,13 +737,22 @@ class _PipelinesAppState extends State const SharedPreferencesWalkthroughStore(); @override - Widget build(BuildContext context) => widget.servers == null - ? MyApp.router(routerConfig: _config) - : ServerContext( - connections: widget.servers!, - serverId: widget.serverId, - child: MyApp.router(routerConfig: _config), - ); + Widget build(BuildContext context) { + // A chat's run card (show_run) opens the run's detail. + final app = ChatRunOpener( + openRun: _openRunFromChat, + child: MyApp.router(routerConfig: _config), + ); + return widget.servers == null + ? app + : ServerContext( + connections: widget.servers!, + serverId: widget.serverId, + child: app, + ); + } + + void _openRunFromChat(int id) => _delegate.goTo(AppRoute.run(id)); /// Open a result through the exact identity the hit records. An unresolvable /// hit navigates nowhere: the screen already presents it read-only rather than diff --git a/app/lib/features/artifacts/domain/artifact_html_theme.dart b/app/lib/features/artifacts/domain/artifact_html_theme.dart new file mode 100644 index 00000000..24521553 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_html_theme.dart @@ -0,0 +1,63 @@ +/// How a recorded HTML document follows the app's light or dark theme. +/// +/// A document opts into dark mode by saying it supports it: a +/// `prefers-color-scheme` media query, a `color-scheme` declaration (CSS or +/// ``) or the `light-dark()` colour function. Such a document is shown +/// in the app's scheme; any other document keeps the light scheme on a white +/// page, because its own colours were chosen for that and may be unreadable +/// on a dark canvas. +/// +/// The frame's browser does not reliably pass the app's preference into a +/// sandboxed document (and a phone's web view knows only the system's), so +/// the scheme is written into the document itself: a leading +/// `` naming only the chosen scheme (the browser +/// paints its default canvas and text, form controls and `light-dark()` in +/// it), and each `prefers-color-scheme` query is replaced by one that is +/// always true or always false for that scheme. +library; + +final RegExp _darkAware = RegExp( + r'prefers-color-scheme|color-scheme|light-dark\(', + caseSensitive: false, +); + +final RegExp _schemeQuery = RegExp( + r'\(\s*prefers-color-scheme\s*:\s*(light|dark)\s*\)', + caseSensitive: false, +); + +final RegExp _headOpen = RegExp(r']*)?>', caseSensitive: false); + +/// A media feature that always holds, and one that never does (a negative +/// length makes the query invalid, which evaluates to false). +const String _always = '(min-width: 0px)'; +const String _never = '(max-width: -1px)'; + +/// Whether [html] declares that it styles itself for dark mode. +bool artifactHtmlSupportsDark(String html) => _darkAware.hasMatch(html); + +/// The colour scheme [html] is shown in: `dark` only when the app is dark +/// ([dark]) and the document supports it, else `light`. +String artifactHtmlScheme(String html, {required bool dark}) => + dark && artifactHtmlSupportsDark(html) ? 'dark' : 'light'; + +/// [html] fixed to its [artifactHtmlScheme] (see the library comment). +String artifactHtmlForScheme(String html, {required bool dark}) { + final scheme = artifactHtmlScheme(html, dark: dark); + final queried = html.replaceAllMapped( + _schemeQuery, + (match) => match[1]!.toLowerCase() == scheme ? _always : _never, + ); + final meta = ''; + final head = _headOpen.firstMatch(queried); + if (head != null) { + return queried.replaceRange(head.end, head.end, meta); + } + // Before everything else, but after a doctype: content ahead of the + // doctype would put the document in quirks mode. + final doctype = _doctype.firstMatch(queried); + final at = doctype?.end ?? 0; + return queried.replaceRange(at, at, meta); +} + +final RegExp _doctype = RegExp(r'^\s*]*>', caseSensitive: false); diff --git a/app/lib/features/artifacts/ui/artifact_html_view.dart b/app/lib/features/artifacts/ui/artifact_html_view.dart index 0210379f..ef69a50b 100644 --- a/app/lib/features/artifacts/ui/artifact_html_view.dart +++ b/app/lib/features/artifacts/ui/artifact_html_view.dart @@ -1,5 +1,6 @@ -import 'package:flutter/widgets.dart'; +import 'package:flutter/material.dart'; +import '../domain/artifact_html_theme.dart'; import 'artifact_fullscreen.dart'; import 'artifact_html_view_native.dart' if (dart.library.js_interop) 'artifact_html_view_web.dart' @@ -16,11 +17,19 @@ typedef ArtifactHtmlBuilder = /// live frame. The mobile web views pinch natively and offer none. const bool artifactHtmlZoomButtons = impl.inertHtmlZoomButtons; +/// Whether a recorded HTML document at [context] is shown in the dark scheme +/// (when it supports one): the app's own theme, not the system's. +bool artifactHtmlDark(BuildContext context) => + Theme.of(context).brightness == Brightness.dark; + /// Renders a recorded HTML document inertly: on the web in an iframe whose /// empty `sandbox` blocks scripts, forms, popups and navigation; on Android and /// iOS in a web view with JavaScript disabled and navigation refused. The /// document never runs code with the app's origin or credentials. /// +/// A document that supports dark mode follows the app's theme +/// ([artifactHtmlForScheme]); any other keeps a white page. +/// /// The preview stops at the floating bars instead of passing behind them: on /// the web the iframe is a platform view that takes every click over its /// area, even where a bar is drawn on top, which left the viewer's actions @@ -40,6 +49,7 @@ Widget defaultArtifactHtml(BuildContext context, String html) { html: html, interactive: fullscreen != null, zoom: fullscreen?.htmlZoom, + dark: artifactHtmlDark(context), ), ), ); diff --git a/app/lib/features/artifacts/ui/artifact_html_view_native.dart b/app/lib/features/artifacts/ui/artifact_html_view_native.dart index 23275528..fd61d5fe 100644 --- a/app/lib/features/artifacts/ui/artifact_html_view_native.dart +++ b/app/lib/features/artifacts/ui/artifact_html_view_native.dart @@ -4,6 +4,7 @@ import 'package:flutter/widgets.dart'; import 'package:webview_flutter/webview_flutter.dart'; import '../domain/artifact_html_links.dart'; +import '../domain/artifact_html_theme.dart'; import 'artifact_external_open.dart'; /// The mobile web views pinch-zoom natively (Android's built-in zoom, which @@ -29,10 +30,15 @@ class InertHtmlView extends StatefulWidget { this.interactive = false, this.zoom, this.openExternal = openArtifactExternally, + this.dark = false, }); final String html; + /// Whether the app is in its dark theme: a document that supports dark mode + /// is loaded in it ([artifactHtmlForScheme]). + final bool dark; + /// Opens a link's http(s)/mailto address outside the artifact. final ArtifactExternalOpen openExternal; final bool interactive; @@ -66,7 +72,9 @@ class _InertHtmlViewState extends State { onNavigationRequest: _decide, ), ) - ..loadHtmlString(widget.html); + ..loadHtmlString(_document); + + String get _document => artifactHtmlForScheme(widget.html, dark: widget.dark); /// Links: a place in the document scrolls there; an http(s)/mailto address /// opens in the system's handler, never inside this view; anything else @@ -91,9 +99,9 @@ class _InertHtmlViewState extends State { @override void didUpdateWidget(covariant InertHtmlView oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.html != widget.html) { + if (oldWidget.html != widget.html || oldWidget.dark != widget.dark) { _loaded = false; - _controller.loadHtmlString(widget.html); + _controller.loadHtmlString(_document); } } diff --git a/app/lib/features/artifacts/ui/artifact_html_view_web.dart b/app/lib/features/artifacts/ui/artifact_html_view_web.dart index 1cceabc2..0fa19e27 100644 --- a/app/lib/features/artifacts/ui/artifact_html_view_web.dart +++ b/app/lib/features/artifacts/ui/artifact_html_view_web.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:web/web.dart' as web; +import '../domain/artifact_html_theme.dart'; import 'artifact_html_links_web.dart'; /// The frame's document cannot be pinched: a pinch over it is a page zoom, @@ -23,6 +24,10 @@ const bool inertHtmlZoomButtons = true; /// document reflows and still scrolls inside it. In the app, Chrome returns /// the frame's document to its top when a zoom step resizes it. /// +/// The document follows the app's theme ([dark]) when it supports dark mode +/// ([artifactHtmlForScheme]); the frame's own `color-scheme` matches, so the +/// browser paints the page's canvas in that scheme rather than always white. +/// /// While another route covers this one (a menu, a sheet) the frame stops /// taking pointers: a platform view takes every click over its area, even /// where Flutter draws that menu on top. @@ -32,10 +37,14 @@ class InertHtmlView extends StatefulWidget { required this.html, this.interactive = false, this.zoom, + this.dark = false, }); final String html; + /// Whether the app is in its dark theme. + final bool dark; + /// The full-screen view's frame. Pointers already reach the frame directly /// on the web, inline as in full screen. final bool interactive; @@ -91,16 +100,20 @@ class _InertHtmlViewState extends State { _covered = covered; _style(); } + final scheme = artifactHtmlScheme(widget.html, dark: widget.dark); return HtmlElementView.fromTagName( - key: ValueKey(widget.html.hashCode), + key: ValueKey<(int, String)>((widget.html.hashCode, scheme)), tagName: 'iframe', onElementCreated: (element) { final frame = element as web.HTMLIFrameElement; frame.setAttribute('sandbox', artifactHtmlSandbox); - frame.srcdoc = artifactHtmlWithInertLinks(widget.html).toJS; + frame.srcdoc = artifactHtmlWithInertLinks( + artifactHtmlForScheme(widget.html, dark: widget.dark), + ).toJS; frame.style ..border = 'none' - ..backgroundColor = 'white'; + ..colorScheme = scheme + ..backgroundColor = scheme == 'dark' ? 'Canvas' : 'white'; _frame = frame; _style(); }, diff --git a/app/lib/features/changes/widgets/capture_section.dart b/app/lib/features/changes/widgets/capture_section.dart index bb505b4f..5b577d96 100644 --- a/app/lib/features/changes/widgets/capture_section.dart +++ b/app/lib/features/changes/widgets/capture_section.dart @@ -100,19 +100,42 @@ class StageCaptureSection extends StatelessWidget { } /// One changed file: its kind, path and line counts; tapping opens its diff. +/// [dense] draws it on one compact line (the path, then the counts), for a +/// card that lists many files in little space. class ChangeFileRow extends StatelessWidget { - const ChangeFileRow({super.key, required this.file, required this.onOpen}); + const ChangeFileRow({ + super.key, + required this.file, + required this.onOpen, + this.dense = false, + }); final FileChange file; final ValueChanged onOpen; + final bool dense; @override Widget build(BuildContext context) { final mono = nativeDiffText(DefaultTextStyle.of(context).style); - final leading = Icon(changeKindIcon(file.kind)); - final title = Text(file.path, style: mono); - final subtitle = ChangeStatText(changeFileMeta(file)); - const trailing = Icon(Icons.chevron_right); + final leading = Icon(changeKindIcon(file.kind), size: dense ? 20 : null); + final Widget title = dense + ? Row( + children: [ + Expanded( + child: Text( + file.path, + style: mono, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 12), + ChangeStatText(changeFileMeta(file)), + ], + ) + : Text(file.path, style: mono); + final subtitle = dense ? null : ChangeStatText(changeFileMeta(file)); + final trailing = dense ? null : const Icon(Icons.chevron_right); return Semantics( container: true, button: true, @@ -124,6 +147,9 @@ class ChangeFileRow extends StatelessWidget { excludeSemantics: true, onTap: () => onOpen(file), child: ListTile( + dense: dense, + visualDensity: dense ? VisualDensity.compact : null, + minLeadingWidth: dense ? 20 : null, leading: leading, title: title, subtitle: subtitle, diff --git a/app/lib/features/chat/chat_run_opener.dart b/app/lib/features/chat/chat_run_opener.dart new file mode 100644 index 00000000..c27f8d90 --- /dev/null +++ b/app/lib/features/chat/chat_run_opener.dart @@ -0,0 +1,17 @@ +import 'package:flutter/widgets.dart'; + +/// Opens a run's detail from inside a chat (a `show_run` card). The app shell +/// provides it above every chat surface; without one a run card is not +/// activatable. +class ChatRunOpener extends InheritedWidget { + const ChatRunOpener({super.key, required this.openRun, required super.child}); + + final ValueChanged openRun; + + static ValueChanged? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.openRun; + + @override + bool updateShouldNotify(ChatRunOpener oldWidget) => + openRun != oldWidget.openRun; +} diff --git a/app/lib/features/chat/domain/chat_shown_diff.dart b/app/lib/features/chat/domain/chat_shown_diff.dart index c61f5957..b7900d37 100644 --- a/app/lib/features/chat/domain/chat_shown_diff.dart +++ b/app/lib/features/chat/domain/chat_shown_diff.dart @@ -12,6 +12,8 @@ class ChatShownDiff { required this.base, required this.baseCommit, required this.head, + this.headRevision = '', + this.paths = const [], required this.committedOnly, required this.files, required this.additions, @@ -29,6 +31,12 @@ class ChatShownDiff { base: _text(body['base']), baseCommit: _text(body['base_commit']), head: _text(body['head']), + headRevision: _text(body['head_revision']), + paths: [ + if (body['paths'] case final List paths) + for (final path in paths) + if (_text(path).isNotEmpty) _text(path), + ], committedOnly: body['committed_only'] == true, files: _count(body['files']), additions: _count(body['additions']), @@ -43,6 +51,13 @@ class ChatShownDiff { final String base; final String baseCommit; final String head; + + /// The revision compared instead of the work tree (`show_diff` head), or + /// empty. + final String headRevision; + + /// The paths or globs the comparison is limited to; empty for all. + final List paths; final bool committedOnly; final int files; final int additions; @@ -57,14 +72,25 @@ class ChatShownDiff { return parts.isEmpty ? repo : parts.last; } - /// What was compared, in words: the branch against its base and whether - /// uncommitted work is included. + /// What was compared, in words: the branch (or the given revision) against + /// its base, whether uncommitted work is included, and the paths it is + /// limited to. String get comparison { + final limited = paths.isEmpty + ? '' + : ' · ${paths.length <= 3 ? paths.join(', ') : '${paths.take(3).join(', ')} +${paths.length - 3}'}'; + return '${_compared()}$limited'; + } + + String _compared() { + final where = repoName.isEmpty ? '' : '$repoName · '; + if (headRevision.isNotEmpty) { + return '$where$headRevision vs ${base.isEmpty ? 'HEAD' : base}'; + } final head = this.head.isEmpty ? 'HEAD' : this.head; final against = base.isEmpty ? (baseCommit.isEmpty ? 'no commits yet' : 'uncommitted changes') : '$head vs $base${committedOnly ? ' · committed only' : ' · with uncommitted work'}'; - final where = repoName.isEmpty ? '' : '$repoName · '; return base.isEmpty ? '$where$head · $against' : '$where$against'; } diff --git a/app/lib/features/chat/domain/chat_shown_items.dart b/app/lib/features/chat/domain/chat_shown_items.dart index 9297abb6..21843d1c 100644 --- a/app/lib/features/chat/domain/chat_shown_items.dart +++ b/app/lib/features/chat/domain/chat_shown_items.dart @@ -2,15 +2,18 @@ import '../../../core/api_gateway.dart'; import 'chat_transcript.dart'; /// Entries a chat's model showed the operator through the Pipelines tools -/// (`show_file`, `show_image`, `show_html`, `show_diff`, `notify`). +/// (`show_file`, `show_image`, `show_html`, `show_diff`, `show_run`, +/// `notify`). /// /// The server keeps them per chat, outside the harness transcript: the /// `chat_subscribe` reply carries the retained list (oldest first) and a /// pushed `chat_shown` frame carries each new or updated item. Items are keyed -/// by `id`; a later copy replaces the held one in place. +/// by `id`; a later copy replaces the held one in place. The server sends one +/// when the model replaces a card (`replace`) and when a shown run changes; +/// either keeps the item's `created_at`, so the card stays where it was. /// The recorded kinds. -const chatShownKinds = {'file', 'image', 'html', 'diff', 'notify'}; +const chatShownKinds = {'file', 'image', 'html', 'diff', 'run', 'notify'}; /// The transcript row kind an item is drawn as. const String chatShownRowKind = 'shown'; @@ -52,7 +55,7 @@ List mergeChatShownItems( /// `pipelines/show_file`. final RegExp _pipelinesTool = RegExp( r'^(?:mcp__pipelines__|pipelines_|pipelines/)' - r'(?:show_file|show_image|show_html|show_diff|notify)$', + r'(?:show_file|show_image|show_html|show_diff|show_run|notify)$', ); /// Whether [part] is a call of a Pipelines tool whose result the transcript diff --git a/app/lib/features/chat/domain/chat_shown_run.dart b/app/lib/features/chat/domain/chat_shown_run.dart new file mode 100644 index 00000000..23bf8e8e --- /dev/null +++ b/app/lib/features/chat/domain/chat_shown_run.dart @@ -0,0 +1,72 @@ +import '../../../core/api_gateway.dart'; +import '../../pipelines/pipeline_format.dart' show formatDuration; +import '../../runs/domain/run_events.dart' show isTerminalRunStatus; + +/// A `show_run` item's run, as the server records it +/// (`internal/protocol/chat_shown.go` ChatShownRunBody). The server pushes the +/// item again whenever the run changes, so this is always its latest state. +class ChatShownRun { + const ChatShownRun({ + required this.id, + required this.pipeline, + required this.title, + required this.status, + required this.outcome, + required this.currentStage, + required this.startedAt, + required this.finishedAt, + }); + + /// The run of a `run` item, or null for any other item or a malformed one. + static ChatShownRun? of(JsonMap item) { + final body = item['run']; + if (item['kind'] != 'run' || body is! Map) return null; + final id = body['id']; + if (id is! num || id <= 0) return null; + return ChatShownRun( + id: id.toInt(), + pipeline: _text(body['pipeline']), + title: _text(body['title']), + status: _text(body['status']), + outcome: _text(body['outcome']), + currentStage: _text(body['current_stage']), + startedAt: _millis(body['started_at']), + finishedAt: _millis(body['finished_at']), + ); + } + + final int id; + final String pipeline; + final String title; + final String status; + final String outcome; + final String currentStage; + final int? startedAt; + final int? finishedAt; + + /// Whether the run has ended (succeeded, failed, canceled, interrupted). + bool get finished => isTerminalRunStatus(status); + + /// The status in words: the outcome of a finished run when it says more. + String get statusLabel { + final word = status.isEmpty ? 'unknown' : status; + final label = '${word[0].toUpperCase()}${word.substring(1)}'; + return finished && outcome.isNotEmpty && outcome != status + ? '$label · $outcome' + : label; + } + + /// How long it ran, or has been running at [now] (epoch milliseconds); null + /// without a start time. + String? duration(int now) { + final start = startedAt; + if (start == null) return null; + final end = finishedAt ?? (finished ? null : now); + if (end == null) return null; + return formatDuration((end - start) ~/ 1000); + } +} + +String _text(Object? value) => '${value ?? ''}'.trim(); + +int? _millis(Object? value) => value is num && value > 0 ? value.toInt() : null; diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_card.dart index afa44f41..88b15fc1 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_card.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_card.dart @@ -8,6 +8,7 @@ import 'chat_shown_file_card.dart'; import 'chat_shown_html_card.dart'; import 'chat_shown_link_image.dart'; import 'chat_shown_notify_row.dart'; +import 'chat_shown_run_card.dart'; /// One transcript row of kind `shown` ([withChatShownItems]): what the model /// showed through a Pipelines tool, drawn by its recorded kind. [endpoint] is @@ -37,6 +38,7 @@ class ChatShownCard extends StatelessWidget { 'notify' => ChatShownNotifyRow(item: item), 'html' => ChatShownHtmlCard(item: item, htmlBuilder: htmlBuilder), 'diff' => ChatShownDiffCard(item: item), + 'run' => ChatShownRunCard(item: item), 'image' when path.isEmpty => ChatShownLinkImage( item: item, openExternal: viewer.openExternal, diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_diff_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_diff_card.dart index f60c80f2..ffd3a369 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_diff_card.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_diff_card.dart @@ -41,7 +41,6 @@ class _ChatShownDiffCardState extends State { : files.take(chatShownDiffPreviewFiles).toList(); return ChatShownSurface( label: 'Shown diff $title', - maxWidth: 720, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -92,6 +91,7 @@ class _ChatShownDiffCardState extends State { ChangeFileRow( key: ValueKey('chat-shown-diff-file-${file.path}'), file: file, + dense: true, onOpen: (file) => showFileDiffViewer(context, file, files: files), ), diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_file_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_file_card.dart index 4e44a891..02b158e6 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_file_card.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_file_card.dart @@ -32,6 +32,26 @@ DirectoryEntry chatShownEntry(JsonMap item) { ); } +/// What happened to a shown file since: the server compares the live file +/// with what was shown (or checks its snapshot still exists) when it lists a +/// chat's items. +enum ChatShownFileState { current, changed, missing } + +ChatShownFileState chatShownFileState(JsonMap item) => + switch ('${item['state'] ?? ''}') { + 'changed' => ChatShownFileState.changed, + 'missing' => ChatShownFileState.missing, + _ => ChatShownFileState.current, + }; + +/// The https address a fetched web image came from, or empty. +String chatShownSourceUrl(JsonMap item) { + final uri = Uri.tryParse('${item['url'] ?? ''}'.trim()); + return uri != null && uri.scheme == 'https' && uri.host.isNotEmpty + ? uri.toString() + : ''; +} + /// The largest logical height an inline shown image takes. const double chatShownImageMaxHeight = 280; @@ -39,6 +59,12 @@ const double chatShownImageMaxHeight = 280; /// card with its kind glyph, name and size, and the first lines of a text /// document. Activating either opens the Files viewer (preview and download) /// over the chat machine's `/files` endpoint ([endpoint]). +/// +/// A small file is a snapshot taken when it was shown, so later edits do not +/// change the card. A larger one is the live file: the card says when it has +/// changed since it was shown, and when it (or a snapshot) no longer exists, +/// in which case nothing is loaded or opened. A web image the server fetched +/// names the address it came from. class ChatShownFileCard extends StatelessWidget { const ChatShownFileCard({ super.key, @@ -54,17 +80,25 @@ class ChatShownFileCard extends StatelessWidget { @override Widget build(BuildContext context) { final entry = chatShownEntry(item); - final urls = resolveFileUrls(endpoint, entry.path); + final state = chatShownFileState(item); + final missing = state == ChatShownFileState.missing; + final urls = missing ? null : resolveFileUrls(endpoint, entry.path); final image = isThumbnailFile(entry.name) && urls != null; + final source = chatShownSourceUrl(item); final kind = artifactKindLabel( artifactKind(fileContentType(entry.name), entry.name), ); - final title = chatShownTitle(item, entry.name); - final subtitle = [ - if (title != entry.name) entry.name, - kind, - fileSizeLabel(entry.size), - ].join(' · '); + final title = chatShownTitle( + item, + source.isEmpty ? entry.name : Uri.parse(source).host, + ); + final subtitle = source.isNotEmpty + ? source + : [ + if (title != entry.name) entry.name, + kind, + fileSizeLabel(entry.size), + ].join(' · '); void open() => viewer.open(context, endpoint: endpoint, entry: entry); final heading = Padding( padding: const EdgeInsets.all(12), @@ -74,12 +108,26 @@ class ChatShownFileCard extends StatelessWidget { leading: image ? null : Icon( - fileIcon(entry), + missing ? Icons.hide_source_outlined : fileIcon(entry), size: 32, color: chatShownSecondary(context), ), ), ); + final note = switch (state) { + ChatShownFileState.current => null, + ChatShownFileState.changed => ( + Icons.update, + 'Changed since shown', + 'The file has changed since it was shown; opening it shows the ' + 'current version.', + ), + ChatShownFileState.missing => ( + Icons.hide_source_outlined, + 'No longer exists', + 'The file was moved or deleted after it was shown.', + ), + }; final body = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -91,6 +139,8 @@ class ChatShownFileCard extends StatelessWidget { fetch: viewer.fetch, ), heading, + if (note != null) + _StateNote(icon: note.$1, label: note.$2, detail: note.$3), if (!image && urls != null) ChatShownFileLines( entry: entry, @@ -99,12 +149,53 @@ class ChatShownFileCard extends StatelessWidget { ), ], ); + final isImage = image || '${item['kind']}' == 'image'; return ChatShownSurface( - label: image ? 'Shown image $title' : 'Shown file $title', - child: Semantics( - button: true, - onTap: open, - child: InkWell(onTap: open, child: body), + label: isImage ? 'Shown image $title' : 'Shown file $title', + child: missing + ? body + : Semantics( + button: true, + onTap: open, + child: InkWell(onTap: open, child: body), + ), + ); + } +} + +/// The line under a shown file's heading that says it changed or is gone. +class _StateNote extends StatelessWidget { + const _StateNote({ + required this.icon, + required this.label, + required this.detail, + }); + + final IconData icon; + final String label; + final String detail; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final color = theme.colorScheme.tertiary; + return Tooltip( + message: detail, + child: Padding( + key: const Key('chat-shown-file-state'), + padding: const EdgeInsetsDirectional.fromSTEB(12, 0, 12, 12), + child: Row( + children: [ + Icon(icon, size: 18, color: color), + const SizedBox(width: 8), + Expanded( + child: Text( + label, + style: theme.textTheme.labelMedium?.copyWith(color: color), + ), + ), + ], + ), ), ); } @@ -138,7 +229,11 @@ class _ChatShownPicture extends StatelessWidget { return ConstrainedBox( constraints: const BoxConstraints(maxHeight: chatShownImageMaxHeight), child: Image( - image: ResizeImage.resizeIfNeeded((560 * ratio).round(), null, source), + image: ResizeImage.resizeIfNeeded( + (chatShownCardMaxWidth * ratio).round(), + null, + source, + ), fit: BoxFit.contain, semanticLabel: name, loadingBuilder: (_, child, progress) => diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_html_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_html_card.dart index 8f49c2b3..b0d41cc9 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_html_card.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_html_card.dart @@ -73,7 +73,6 @@ class ChatShownHtmlCard extends StatelessWidget { ); return ChatShownSurface( label: 'Shown view $title', - maxWidth: 720, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart new file mode 100644 index 00000000..bef427c5 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_run_card.dart @@ -0,0 +1,151 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../../../../core/api_gateway.dart'; +import '../../../chat_run_opener.dart'; +import '../../../domain/chat_shown_run.dart'; +import 'chat_shown_surface.dart'; + +/// The glyph of a run status. +IconData chatShownRunIcon(String status) => switch (status) { + 'succeeded' => Icons.check_circle_outline, + 'failed' => Icons.error_outline, + 'canceled' => Icons.cancel_outlined, + 'interrupted' => Icons.pause_circle_outline, + 'waiting' => Icons.front_hand_outlined, + 'queued' => Icons.schedule, + _ => Icons.play_circle_outline, +}; + +Color _statusColor(ColorScheme colors, String status) => switch (status) { + 'succeeded' => colors.primary, + 'failed' || 'interrupted' => colors.error, + 'waiting' => colors.tertiary, + _ => colors.onSurfaceVariant, +}; + +/// A pipeline run the model showed through `show_run`: the pipeline, the +/// run's title, its status, current stage and how long it has run. The server +/// pushes the item again as the run changes; while it runs the duration ticks +/// here. Activating it opens the run ([ChatRunOpener]). +class ChatShownRunCard extends StatefulWidget { + const ChatShownRunCard({super.key, required this.item, this.now}); + + final JsonMap item; + + /// The clock, for tests. + final DateTime Function()? now; + + @override + State createState() => _ChatShownRunCardState(); +} + +class _ChatShownRunCardState extends State { + Timer? _tick; + + int get _now => (widget.now?.call() ?? DateTime.now()).millisecondsSinceEpoch; + + @override + void initState() { + super.initState(); + _schedule(); + } + + @override + void didUpdateWidget(covariant ChatShownRunCard oldWidget) { + super.didUpdateWidget(oldWidget); + _schedule(); + } + + /// Ticks once a second while the run has not finished, so its duration + /// keeps counting; a finished run's card is static. + void _schedule() { + final running = ChatShownRun.of(widget.item)?.finished == false; + if (running && _tick == null) { + _tick = Timer.periodic(const Duration(seconds: 1), (_) { + if (mounted) setState(() {}); + }); + } else if (!running) { + _tick?.cancel(); + _tick = null; + } + } + + @override + void dispose() { + _tick?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final run = ChatShownRun.of(widget.item); + if (run == null) return const SizedBox.shrink(); + final theme = Theme.of(context); + final colors = theme.colorScheme; + final secondary = chatShownSecondary(context); + final title = chatShownTitle( + widget.item, + run.title.isEmpty ? 'Run ${run.id}' : run.title, + ); + final pipeline = run.pipeline.isEmpty ? 'Run' : run.pipeline; + final duration = run.duration(_now); + final status = run.statusLabel; + final facts = [ + '#${run.id}', + if (!run.finished && run.currentStage.isNotEmpty) run.currentStage, + ?duration, + ].join(' · '); + final open = ChatRunOpener.maybeOf(context); + final body = Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 10, 12, 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + ChatShownHeading( + title: title, + subtitle: pipeline, + leading: Icon(Icons.play_lesson_outlined, color: secondary), + trailing: open == null + ? null + : Icon(Icons.chevron_right, color: secondary), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Chip( + key: const Key('chat-shown-run-status'), + avatar: Icon( + chatShownRunIcon(run.status), + color: _statusColor(colors, run.status), + ), + label: Text(status), + visualDensity: VisualDensity.compact, + ), + Text( + facts, + key: const Key('chat-shown-run-facts'), + style: theme.textTheme.bodySmall?.copyWith(color: secondary), + ), + ], + ), + ], + ), + ); + return ChatShownSurface( + label: 'Shown run $title', + child: open == null + ? body + : Semantics( + button: true, + onTap: () => open(run.id), + child: InkWell(onTap: () => open(run.id), child: body), + ), + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/shown/chat_shown_surface.dart b/app/lib/features/chat/ui/transcript/shown/chat_shown_surface.dart index 6398c9ba..02d77724 100644 --- a/app/lib/features/chat/ui/transcript/shown/chat_shown_surface.dart +++ b/app/lib/features/chat/ui/transcript/shown/chat_shown_surface.dart @@ -12,20 +12,18 @@ String chatShownTitle(JsonMap item, String fallback) { return title.isEmpty ? fallback : title; } +/// The width every shown card (file, image, view, diff, run) is held to, so +/// the entries of one transcript line up whatever their kind. +const double chatShownCardMaxWidth = 720; + /// The outlined card a shown entry sits in, on the agent's side of the -/// transcript, at most [maxWidth] wide. +/// transcript, at most [chatShownCardMaxWidth] wide. class ChatShownSurface extends StatelessWidget { - const ChatShownSurface({ - super.key, - required this.label, - required this.child, - this.maxWidth = 560, - }); + const ChatShownSurface({super.key, required this.label, required this.child}); /// The entry's accessible name ("Shown file", "Shown view", ...). final String label; final Widget child; - final double maxWidth; @override Widget build(BuildContext context) { @@ -43,7 +41,7 @@ class ChatShownSurface extends StatelessWidget { child: Align( alignment: AlignmentDirectional.centerStart, child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: maxWidth), + constraints: const BoxConstraints(maxWidth: chatShownCardMaxWidth), child: card, ), ), diff --git a/app/notes/chat-pipelines-tools.md b/app/notes/chat-pipelines-tools.md index 057609e0..44f198cd 100644 --- a/app/notes/chat-pipelines-tools.md +++ b/app/notes/chat-pipelines-tools.md @@ -100,6 +100,60 @@ The generic tool rows for `mcp__pipelines__*` (Claude), `pipelines_*` visible. OpenCode V2 runs MCP tools from its code-mode `execute` script, and that row stays visible because it can contain other code. +## Snapshots, replace, run cards and follow-ups (2026-12-02) + +- **Argument validation.** `chattools.ValidateArguments` checks every call + against the tool's declared schema (the schemas say + `additionalProperties: false`): unknown or misnamed fields, missing required + ones and wrong types are refused with the expected field list, before any + effect. Each tool then decodes its own argument struct. +- **Item ids and `replace`.** Every `show_*` result ends with the item id. + `replace: ` (an item of this chat, same kind; file and image are one + family) stores the new item over the old one with the same `id` and + `created_at` plus `updated_at`; the client merges by id, so the card is + updated where it is. +- **File snapshots.** `show_file` / `show_image` copy a file up to 5 MiB into + `/chat-shown//-/` (inside home, so + `/files` serves it): `snapshot: true`, `source` = the path named. A larger + file stays live with `mod_time` and `sha256` (hash up to 64 MiB); the + subscribe reply sets `state: changed | missing`. Snapshot directories no + retained item references are swept (after a 1 minute grace). +- **Web images.** `show_image` with an https URL is downloaded by the server: + every dialed address (redirects included, checked after DNS resolution) must + be public unicast, no proxy, https-only redirects (at most 5), 20 s timeout, + PNG/JPEG/GIF/WebP/AVIF/BMP only (SVG refused) with content that sniffs as an + image, at most 10 MiB. The bytes become the item's snapshot; `url` keeps the + address. A failure is an error to the model and records nothing. +- **`show_run`.** A `run` item with `{id, pipeline, title, status, outcome, + current_stage, workspace, started_at, finished_at}`. The run event hub's + observer (`runEventHub.observe`) tells the tool service a followed run + changed; after 400 ms it rereads the run summary, stores a changed body over + the item and pushes it. The subscribe reply rereads followed runs too; a + finished run is no longer followed. +- **`show_diff`** takes `head` (compare that revision instead of the work tree, + against `base`'s merge base or HEAD) and `paths` (at most 50 relative + paths/globs; no `..`, absolute paths, leading `-` or `:`; passed as + `:(literal)` / `:(glob)` pathspecs). +- **`schedule_followup`** queues a durable prompt with `send_at` (1 minute to 7 + days), operation id `followup-…`, sender label "Agent follow-up", at most 3 + pending per chat. It is removable like any queued prompt. Unlike an + operator's scheduled prompt, a follow-up that is not due yet does not hold + the FIFO queue: `chatQueueHead` skips it, so the operator's prompts go + through. +- **HTML theme.** A document that declares dark support + (`prefers-color-scheme`, `color-scheme` or `light-dark()`) is shown in the + app's theme (not the system's): `artifact_html_theme.dart` inserts a + `color-scheme` meta naming that scheme and rewrites each + `prefers-color-scheme` query to always/never match, and the web frame gets the + same `color-scheme` (canvas `Canvas` when dark). Any other document stays + light on white, since its colours were chosen for that. The tool description + tells the model so. +- **Cards.** Every shown card is held to one width (`chatShownCardMaxWidth`, + 720). Diff file rows are one dense line (path, counts). A run card shows + pipeline, title, status chip, `#id · stage · duration` (ticking while it + runs) and opens the run. File cards show "Changed since shown" / "No longer + exists" (a missing file loads and opens nothing). + ## Per-harness registration `server.ConfigureChatTools(store, addr)` runs at startup, before any harness diff --git a/app/test/features/artifacts/domain/artifact_html_theme_test.dart b/app/test/features/artifacts/domain/artifact_html_theme_test.dart new file mode 100644 index 00000000..23fbfcb6 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_html_theme_test.dart @@ -0,0 +1,83 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_html_theme.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_html_view.dart'; + +const _aware = '''Hi'''; + +const _plain = 'No dark styles'; + +void main() { + test('only a document that supports dark mode is shown dark', () { + expect(artifactHtmlSupportsDark(_aware), isTrue); + expect(artifactHtmlSupportsDark(_plain), isFalse); + expect( + artifactHtmlSupportsDark('

'), + isTrue, + ); + expect(artifactHtmlScheme(_aware, dark: true), 'dark'); + expect(artifactHtmlScheme(_aware, dark: false), 'light'); + expect(artifactHtmlScheme(_plain, dark: true), 'light'); + }); + + test('a dark-aware document gets the app scheme and fixed queries', () { + final dark = artifactHtmlForScheme(_aware, dark: true); + expect( + dark, + contains(' +Stage durations (follows the theme) +

Build 2m 10s
+
Test 4m 02s
+
Release 38s
+'''; + +const String _lightOnly = ''' + +Plain document (no dark styles) +

Its own colours were chosen for a light page, so it stays light.

+ + + + +
StageResult
Buildpassed
Testfailed
'''; + +int get _now => DateTime.now().millisecondsSinceEpoch; + +/// The retained entries the fixture's subscribe reply carries for `shown=2`. +JsonMap chatShownToolsFixture(Object? sessionId) => { + 'session_id': sessionId, + 'items': [ + { + 'id': 'shown-dark-html', + 'kind': 'html', + 'created_at': _at(19, 10), + 'title': 'Stage durations', + 'html': _darkAware, + 'html_bytes': _darkAware.length, + 'height_hint': 160, + }, + { + 'id': 'shown-light-html', + 'kind': 'html', + 'created_at': _at(19, 15), + 'title': 'Light-only view', + 'html': _lightOnly, + 'html_bytes': _lightOnly.length, + 'height_hint': 170, + }, + { + 'id': 'shown-run-live', + 'kind': 'run', + 'created_at': _at(19, 20), + 'run': { + 'id': 7, + 'pipeline': 'Release', + 'title': 'Publish the 4.2 release notes', + 'status': 'running', + 'current_stage': 'review', + 'started_at': _now - 754000, + }, + }, + { + 'id': 'shown-run-done', + 'kind': 'run', + 'created_at': _at(19, 25), + 'run': { + 'id': 6, + 'pipeline': 'Feature', + 'title': 'Add show_run to the chat tools', + 'status': 'failed', + 'outcome': 'tests_failed', + 'started_at': _at(1, 0), + 'finished_at': _at(9, 30), + }, + }, + { + 'id': 'shown-changed', + 'kind': 'file', + 'created_at': _at(19, 30), + 'path': '/srv/probe/release/server.log', + 'name': 'server.log', + 'size': 9437184, + 'mime': 'text/plain', + 'mod_time': _at(19, 0), + 'sha256': 'f' * 64, + 'state': 'changed', + }, + { + 'id': 'shown-missing', + 'kind': 'image', + 'created_at': _at(19, 35), + 'title': 'Old screenshot', + 'path': '/srv/probe/release/old-screenshot.png', + 'name': 'old-screenshot.png', + 'size': 8000000, + 'mime': 'image/png', + 'state': 'missing', + }, + { + 'id': 'shown-fetched', + 'kind': 'image', + 'created_at': _at(19, 40), + 'path': '/srv/probe/.local/share/pipelines/chat-shown/s/f/icon.jpg', + 'name': 'icon.jpg', + 'size': 2400, + 'mime': 'image/jpeg', + 'snapshot': true, + 'url': 'https://images.example.test/brand/icon.jpg', + }, + { + 'id': 'shown-head-diff', + 'kind': 'diff', + 'created_at': _at(19, 45), + 'title': 'Run 123 against main', + 'diff_bytes': 180, + 'diff': { + 'repo': '/srv/probe/pipelines', + 'base': 'main', + 'base_commit': '79e51834a1b2', + 'head_revision': 'pipelines/run-123', + 'paths': ['internal/chattools', '*.md'], + 'files': 2, + 'additions': 3, + 'deletions': 1, + 'changes': { + 'status': 'complete', + 'skipped': 0, + 'files': [ + { + 'path': 'internal/chattools/tools.go', + 'kind': 'modified', + 'patch': + '@@ -6,2 +6,3 @@\n \tToolShowDiff = "show_diff"\n' + '-\tToolNotify = "notify"\n+\tToolShowRun = "show_run"\n' + '+\tToolNotify = "notify"\n', + }, + { + 'path': 'README.md', + 'kind': 'modified', + 'patch': '@@ -1 +1,2 @@\n line\n+show_run\n', + }, + ], + }, + }, + }, + ], +}; diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index f21fd22e..ed38738f 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -36,6 +36,7 @@ import 'chat_question_fixture.dart'; import 'chat_shell_fixture.dart'; import 'terminal_fixture.dart'; import 'chat_shown_fixture.dart'; +import 'chat_shown_tools_fixture.dart'; import 'chat_scroll_fixture.dart'; Map _params = const {}; @@ -341,6 +342,10 @@ JsonMap? perfChatReply(JsonMap request) { 'chat_shown': chatShownFixture( (request['chat_subscribe'] as Map?)?['session_id'], ), + if (_params['shown'] == '2') + 'chat_shown': chatShownToolsFixture( + (request['chat_subscribe'] as Map?)?['session_id'], + ), }; case 'chat_prompt': // Accepted, as the server does; no reply follows, so a capture can diff --git a/internal/author/skill/SKILL.md b/internal/author/skill/SKILL.md index 5f6d0e1c..841e52d2 100644 --- a/internal/author/skill/SKILL.md +++ b/internal/author/skill/SKILL.md @@ -77,12 +77,15 @@ only when asked). Stage use: `references/format.md`. ## In a Pipelines chat A chat's agent has a `pipelines` MCP server: `show_file`, `show_image`, -`show_html`, `show_diff` (show the operator changes, e.g. before a pull request) -and `notify` (every Pipelines app the operator is signed in to plus their phone; -cleared everywhere once they read it or open the chat). Pipelines already -notifies when a reply ends or the agent asks something, so `notify` is only for -news mid-turn or after work the turn does not wait for. Show instead of -telling the operator a path. Details, limits, chat RPCs: `references/chat.md`. +`show_html` (follows the light/dark theme when it styles for dark), `show_diff` (show the +operator changes, e.g. before a pull request; `head`, `paths`), `show_run` (a +live run card), `schedule_followup` (come back to this chat later) and `notify` +(every Pipelines app the operator is signed in to plus their phone; cleared +everywhere once they read it or open the chat). Pipelines already notifies when +a reply ends or the agent asks something, so `notify` is only for news mid-turn +or after work the turn does not wait for. Show instead of telling the operator a +path; pass a result's item id as `replace` to update a card in place. Unknown +arguments are refused. Details, limits, chat RPCs: `references/chat.md`. ## References diff --git a/internal/author/skill/references/chat.md b/internal/author/skill/references/chat.md index 152877f4..bb05eeb4 100644 --- a/internal/author/skill/references/chat.md +++ b/internal/author/skill/references/chat.md @@ -5,21 +5,32 @@ the Pipelines app (desktop, web or phone), often not at this machine's terminal. ## Pipelines tools (`pipelines` MCP server) -Each call adds a persisted item to the transcript and returns one short line; a -refusal comes back as an error with the reason. Paths must resolve inside the -operator's home (absolute, `~/...`, or relative to the chat's directory). +Each `show_*` call adds a persisted item to the transcript and returns one short +line ending with the item's id; a refusal comes back as an error with the +reason. Arguments are checked against the tool's schema: an unknown or +misnamed field is refused with the list of expected fields. Paths must resolve +inside the operator's home (absolute, `~/...`, or relative to the chat's +directory). + +Every `show_*` tool takes `replace?`: the id of an item this chat showed +earlier, of the same kind (file and image count as one). The card is updated +where it is instead of a new one being added; use it for a chart or diff you +regenerate, or a file you rewrote. | Tool | Arguments | Use for | | --- | --- | --- | -| `show_file` | `path`, `title?` | Any file the operator should see: images inline, other files as a preview card. Use instead of naming a path. | -| `show_image` | `url_or_path`, `title?`, `alt?` | A home `image/*` file or an `https://` URL (no credentials, at most 2048 chars). | -| `show_html` | `html`, `title?`, `height_hint?` (120-600) | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Refused above 512 KiB. | -| `show_diff` | `path?`, `base?`, `committed_only?`, `title?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. Pipelines runs Git; do not paste the diff. | +| `show_file` | `path`, `title?`, `replace?` | Any file the operator should see: images inline, other files as a preview card. Use instead of naming a path. A file up to 5 MiB is copied when shown, so the card keeps that version; a larger one stays linked and its card says "changed since shown" or "no longer exists". | +| `show_image` | `url_or_path`, `title?`, `alt?`, `replace?` | A home `image/*` file, or an `https://` URL that Pipelines downloads and keeps (public hosts only, PNG/JPEG/GIF/WebP/AVIF/BMP, at most 10 MiB, no credentials, no redirect to plain http). A failed download is an error and nothing is shown. | +| `show_html` | `html`, `title?`, `height_hint?` (120-600), `replace?` | Self-contained HTML/SVG: diagrams, charts, tables. Sandboxed: no JavaScript, no network; inline CSS/SVG, `
`, `:hover`. Follows the operator's light/dark theme only when it declares dark support: `@media (prefers-color-scheme: dark)`, `color-scheme` or `light-dark()`; anything else is always shown light, on white. Refused above 512 KiB. | +| `show_diff` | `path?`, `base?`, `head?`, `paths?`, `committed_only?`, `title?`, `replace?` | A Git diff card when the operator asks to see the changes, or before submitting a pull request. No `base`: uncommitted work (staged, unstaged, untracked) against HEAD. `base` (e.g. `main`): everything since the merge base, which is what a PR contains, plus uncommitted work unless `committed_only`. `head` (e.g. `pipelines/run-123`): that revision instead of the work tree, against `base` or HEAD. `paths`: repository-relative files, directories or globs (`*.go`), at most 50. Pipelines runs Git; do not paste the diff. | +| `show_run` | `run_id`, `title?`, `replace?` | A live card for a run: pipeline, title, status, current stage, duration; it updates as the run progresses and opens the run when tapped. | +| `schedule_followup` | `message`, `at?` or `after_minutes?` | Queue a prompt to yourself in this chat, 1 minute to 7 days ahead (`at` is RFC 3339). It is a scheduled message from "Agent follow-up" the operator can remove; it does not hold the operator's own messages back, and is delivered when the chat is free at that time. At most 3 pending per chat. Do not wait for it in the current turn. | | `notify` | `title`, `message`, `priority?` | A notification on every Pipelines app the operator is signed in to (web tabs, desktop, Android) and their phone (ntfy); a tap opens this chat. Opening the chat, or tapping or dismissing it on any device, clears it on all of them. Pipelines already notifies when the reply ends and for questions and approvals, so use it only for news mid-turn or after background work the turn does not wait for; a turn that notified sends no separate "replied" notification. 5 per minute per chat; the result says where it went, and undelivered sends report why. | `show_diff` lists at most 300 files; a file patch over 256 KiB or a total over 1 MiB is shown partially and says so; binaries have no patch; renames show as -delete plus add. `base` is a plain revision name. Tools are absent when the +delete plus add. `base` and `head` are plain revision names, and `paths` stay +inside the repository (no `..`, absolute paths or pathspec magic). Tools are absent when the harness could not register them (logged); then name paths instead. ## References sent into the chat diff --git a/internal/chattools/mcp_test.go b/internal/chattools/mcp_test.go index a0a94525..3f05c749 100644 --- a/internal/chattools/mcp_test.go +++ b/internal/chattools/mcp_test.go @@ -75,7 +75,7 @@ func TestHandshakeListAndCall(t *testing.T) { t.Fatalf("tool without description or schema: %v", entry) } } - if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify" { + if strings.Join(names, ",") != "show_file,show_image,show_html,show_diff,notify,show_run,schedule_followup" { t.Fatalf("tools = %v", names) } if list["id"] != "l" { diff --git a/internal/chattools/tools.go b/internal/chattools/tools.go index e2a82acf..bab5060d 100644 --- a/internal/chattools/tools.go +++ b/internal/chattools/tools.go @@ -6,17 +6,35 @@ const ( ToolShowImage = "show_image" ToolShowHTML = "show_html" ToolShowDiff = "show_diff" + ToolShowRun = "show_run" ToolNotify = "notify" + // ToolScheduleFollowup queues a prompt into the calling chat for later. + ToolScheduleFollowup = "schedule_followup" ) // MaxHTMLBytes bounds one show_html document. A larger one is refused, never // truncated: a cut document would render as something the model did not write. const MaxHTMLBytes = 512 << 10 +// The shown-file bounds: a file up to MaxSnapshotBytes is copied when shown, +// and a web image up to MaxFetchedImageBytes is fetched by Pipelines. +const ( + MaxSnapshotBytes = 5 << 20 + MaxFetchedImageBytes = 10 << 20 +) + +// The schedule_followup bounds. +const ( + MinFollowupMinutes = 1 + MaxFollowupMinutes = 7 * 24 * 60 + MaxPendingFollowups = 3 + MaxFollowupTextBytes = 8 << 10 +) + // IsTool reports whether name is one of the Pipelines tools. func IsTool(name string) bool { switch name { - case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolNotify: + case ToolShowFile, ToolShowImage, ToolShowHTML, ToolShowDiff, ToolShowRun, ToolNotify, ToolScheduleFollowup: return true } return false @@ -30,6 +48,8 @@ const Instructions = "These tools act on Pipelines, the app the operator reads t "Pipelines already notifies them when your reply ends and when you ask a question or need an approval, so do not notify for those " + "(a notify replaces this turn's end-of-reply notification). It reaches every Pipelines app they are signed in to and their phone, " + "and clears everywhere once they open the chat. " + + "Use show_run to follow a pipeline run live in the chat, and schedule_followup to come back to this chat later (for example to check on a run). " + + "Every show_* result names the shown item's id: pass it as replace to update that card instead of adding another. " + "Your thinking is not shown to the operator: before asking them a question (for example with AskUserQuestion), " + "write what you found and why you are asking as a normal message, because the question form shows only the question and its options." @@ -49,6 +69,12 @@ func objectSchema(required []string, properties map[string]any) map[string]any { return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false} } +// replaceProperty is the optional id of an earlier shown item to update. +func replaceProperty() map[string]any { + return stringProperty("Optional id of an item you showed earlier in this chat (from that call's result): " + + "the card is updated in place instead of a new one being added. It must be the same kind of item.") +} + // definitions is the tools/list result, in a fixed order. func definitions() []toolDefinition { return []toolDefinition{ @@ -58,10 +84,13 @@ func definitions() []toolDefinition { Description: "Show the operator an existing file from this machine directly in the Pipelines chat: images appear inline, " + "documents (PDF, Markdown, text, CSV, HTML, and others) as a preview card they can tap to open or download. " + "Use this instead of telling the operator a path to navigate to. The file must be inside the operator's home directory. " + - "A relative path is resolved against the chat's working directory.", + "A relative path is resolved against the chat's working directory. " + + "A file up to 5 MiB is copied when shown, so the card keeps showing that version; a larger one stays linked " + + "and the card says when it changed or no longer exists. The result names the item's id for replace.", InputSchema: objectSchema([]string{"path"}, map[string]any{ - "path": stringProperty("Absolute path, ~/path, or a path relative to the chat's working directory."), - "title": stringProperty("Optional short caption shown above the file."), + "path": stringProperty("Absolute path, ~/path, or a path relative to the chat's working directory."), + "title": stringProperty("Optional short caption shown above the file."), + "replace": replaceProperty(), }), Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false}, }, @@ -69,11 +98,14 @@ func definitions() []toolDefinition { Name: ToolShowImage, Title: "Show an image in the chat", Description: "Show the operator an image inline in the Pipelines chat, from a file on this machine (inside the operator's home) " + - "or from an https:// URL. The URL is loaded by the operator's device without cookies.", + "or from an https:// URL. Pipelines downloads a URL itself (public https hosts only, at most 10 MiB, image types only) " + + "and keeps a copy, so the operator sees it even where the host refuses other sites; a failed download is reported " + + "to you and nothing is shown. The result names the item's id for replace.", InputSchema: objectSchema([]string{"url_or_path"}, map[string]any{ "url_or_path": stringProperty("An https:// image URL, or a file path as for show_file."), "title": stringProperty("Optional short caption."), "alt": stringProperty("Optional description of the image for accessibility."), + "replace": replaceProperty(), }), Annotations: map[string]any{"readOnlyHint": true}, }, @@ -83,11 +115,15 @@ func definitions() []toolDefinition { Description: "Render a self-contained HTML or SVG document inline in the Pipelines chat: diagrams, charts, tables, small visual views. " + "It is shown in a sandbox with no scripts, no network and no access to the app: use inline CSS and inline SVG, " + "
for expandable parts and CSS :hover for interaction; JavaScript does not run and external resources do not load. " + - "The operator can open it full screen. At most 512 KiB.", + "A document that supports dark mode follows the operator's light or dark theme: style for both with " + + "@media (prefers-color-scheme: dark), a color-scheme declaration or light-dark() colors (with color-scheme, " + + "unstyled text and the page use the theme's Canvas/CanvasText). A document without any of these is always shown light, on white. " + + "The operator can open it full screen. At most 512 KiB. The result names the item's id: pass it as replace to update the view.", InputSchema: objectSchema([]string{"html"}, map[string]any{ "html": stringProperty("The complete HTML (or a bare ) document."), "title": stringProperty("Optional short caption."), "height_hint": map[string]any{"type": "integer", "description": "Optional preferred inline height in logical pixels (120-600)."}, + "replace": replaceProperty(), }), Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false}, }, @@ -100,12 +136,18 @@ func definitions() []toolDefinition { "Pipelines runs Git itself, so do not paste the diff. Without base it shows uncommitted work (staged, unstaged and untracked files) against HEAD. " + "With base (the pull request's target branch, such as main or origin/main) it shows everything since the branch left base, " + "which is what the pull request would contain, plus uncommitted work unless committed_only is true. " + + "With head (a branch or commit, such as pipelines/run-123) it compares that revision instead of the working tree: " + + "against base when given (everything since head left base), else against HEAD. paths limits the diff to those files, " + + "directories or globs inside the repository. " + "The repository must be inside the operator's home directory. Very large diffs are shown partially and say so.", InputSchema: objectSchema([]string{}, map[string]any{ "path": stringProperty("Optional repository directory: absolute, ~/path, or relative to the chat's working directory. Defaults to the chat's working directory."), "base": stringProperty("Optional branch, tag or commit to compare against, such as main or origin/main. Omit to show uncommitted changes."), + "head": stringProperty("Optional branch, tag or commit to show instead of the working tree, such as pipelines/run-123."), + "paths": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "Optional repository-relative files, directories or globs (such as internal/server or *.go) to limit the diff to; at most 50."}, "committed_only": map[string]any{"type": "boolean", "description": "Only with base: show the committed changes (base...HEAD) and leave out uncommitted work."}, "title": stringProperty("Optional short caption shown above the diff."), + "replace": replaceProperty(), }), Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false}, }, @@ -124,5 +166,32 @@ func definitions() []toolDefinition { }), Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": true}, }, + { + Name: ToolShowRun, + Title: "Show a pipeline run in the chat", + Description: "Show the operator a live card for a Pipelines run: its pipeline, title, status, current stage and duration, " + + "kept current as the run progresses; tapping it opens the run. Use it after starting a run, or when the operator asks about one. " + + "The result names the item's id for replace.", + InputSchema: objectSchema([]string{"run_id"}, map[string]any{ + "run_id": map[string]any{"type": "integer", "description": "The run's numeric id (as in `pipelines status ` or pipelines/run-)."}, + "title": stringProperty("Optional short caption shown above the run."), + "replace": replaceProperty(), + }), + Annotations: map[string]any{"readOnlyHint": true, "openWorldHint": false}, + }, + { + Name: ToolScheduleFollowup, + Title: "Schedule a follow-up in this chat", + Description: "Queue a message to yourself in this chat, delivered as a new prompt at a later time (for example to check on a long run). " + + "The operator sees it in the chat as a scheduled message from the agent and can remove it. " + + "Give at (an RFC 3339 time) or after_minutes, between 1 minute and 7 days from now. At most 3 follow-ups can be pending per chat. " + + "It is delivered when the chat is free at that time, so do not wait for it in the current turn.", + InputSchema: objectSchema([]string{"message"}, map[string]any{ + "message": stringProperty("What the follow-up prompt should say: enough for you to know what to do then."), + "at": stringProperty("When to deliver it, as an RFC 3339 time such as 2026-05-01T09:30:00Z. Give this or after_minutes."), + "after_minutes": map[string]any{"type": "integer", "description": "Minutes from now to deliver it (1-10080). Give this or at."}, + }), + Annotations: map[string]any{"readOnlyHint": false, "destructiveHint": false, "openWorldHint": false}, + }, } } diff --git a/internal/chattools/validate.go b/internal/chattools/validate.go new file mode 100644 index 00000000..abfd7b56 --- /dev/null +++ b/internal/chattools/validate.go @@ -0,0 +1,134 @@ +package chattools + +import ( + "bytes" + "encoding/json" + "fmt" + "slices" + "sort" + "strings" +) + +// ValidateArguments checks a call's arguments against the tool's declared +// input schema: a JSON object holding only declared fields, every required +// one, each of its declared type (and enum). The schemas promise +// additionalProperties false, so a misnamed field is refused with a message +// naming the expected ones rather than silently ignored. +func ValidateArguments(tool string, arguments json.RawMessage) error { + schema := toolSchema(tool) + if schema == nil { + return fmt.Errorf("unknown tool %s", tool) + } + properties, _ := schema["properties"].(map[string]any) + required, _ := schema["required"].([]string) + expected := expectedFields(properties, required) + var fields map[string]json.RawMessage + decoder := json.NewDecoder(bytes.NewReader(arguments)) + if err := decoder.Decode(&fields); err != nil || fields == nil { + return fmt.Errorf("the arguments must be a JSON object; %s takes %s", tool, expected) + } + var unknown []string + for name := range fields { + if _, ok := properties[name]; !ok { + unknown = append(unknown, name) + } + } + if len(unknown) > 0 { + sort.Strings(unknown) + return fmt.Errorf("unknown %s %s; %s takes %s", plural(len(unknown), "argument", "arguments"), quoteAll(unknown), tool, expected) + } + for _, name := range required { + if raw, ok := fields[name]; !ok || string(raw) == "null" { + return fmt.Errorf("%s is required; %s takes %s", name, tool, expected) + } + } + for name, raw := range fields { + if string(raw) == "null" { + continue + } + property, _ := properties[name].(map[string]any) + if err := checkType(name, property, raw); err != nil { + return err + } + } + return nil +} + +func toolSchema(tool string) map[string]any { + for _, definition := range definitions() { + if definition.Name == tool { + return definition.InputSchema + } + } + return nil +} + +func checkType(name string, property map[string]any, raw json.RawMessage) error { + kind, _ := property["type"].(string) + switch kind { + case "string": + var text string + if json.Unmarshal(raw, &text) != nil { + return fmt.Errorf("%s must be a string", name) + } + if values, ok := property["enum"].([]string); ok && !slices.Contains(values, text) { + return fmt.Errorf("%s must be one of %s", name, strings.Join(values, ", ")) + } + case "integer": + var number json.Number + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if bytes.HasPrefix(bytes.TrimSpace(raw), []byte(`"`)) || decoder.Decode(&number) != nil { + return fmt.Errorf("%s must be an integer", name) + } + if _, err := number.Int64(); err != nil { + return fmt.Errorf("%s must be an integer", name) + } + case "boolean": + var flag bool + if json.Unmarshal(raw, &flag) != nil { + return fmt.Errorf("%s must be true or false", name) + } + case "array": + var list []string + if json.Unmarshal(raw, &list) != nil { + return fmt.Errorf("%s must be an array of strings", name) + } + } + return nil +} + +// expectedFields names a tool's fields, required ones first and marked. +func expectedFields(properties map[string]any, required []string) string { + var names []string + for _, name := range required { + names = append(names, name+" (required)") + } + var optional []string + for name := range properties { + if !slices.Contains(required, name) { + optional = append(optional, name) + } + } + sort.Strings(optional) + names = append(names, optional...) + if len(names) == 0 { + return "no arguments" + } + return strings.Join(names, ", ") +} + +func quoteAll(names []string) string { + quoted := make([]string, len(names)) + for i, name := range names { + quoted[i] = fmt.Sprintf("%q", name) + } + return strings.Join(quoted, ", ") +} + +func plural(n int, one, many string) string { + if n == 1 { + return one + } + return many +} diff --git a/internal/chattools/validate_test.go b/internal/chattools/validate_test.go new file mode 100644 index 00000000..0cdad2d6 --- /dev/null +++ b/internal/chattools/validate_test.go @@ -0,0 +1,51 @@ +package chattools + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestValidateArgumentsRefusesUnknownAndMistypedFields(t *testing.T) { + cases := []struct { + tool, args, want string + }{ + {ToolShowFile, `{"path":"a.txt"}`, ""}, + {ToolShowFile, `{"path":"a.txt","replace":"shown_1","title":"x"}`, ""}, + {ToolShowFile, `{"file":"a.txt"}`, `unknown argument "file"; show_file takes path (required), replace, title`}, + {ToolShowFile, `{}`, "path is required"}, + {ToolShowFile, `{"path":3}`, "path must be a string"}, + {ToolShowFile, `[1]`, "must be a JSON object"}, + {ToolShowImage, `{"url":"https://x/y.png"}`, `unknown argument "url"; show_image takes url_or_path (required), alt, replace, title`}, + {ToolShowHTML, `{"html":"

","height_hint":"200"}`, "height_hint must be an integer"}, + {ToolShowHTML, `{"html":"

","height_hint":200.5}`, "height_hint must be an integer"}, + {ToolShowDiff, `{"paths":"a.go"}`, "paths must be an array of strings"}, + {ToolShowDiff, `{"paths":["a.go"],"head":"main","committed_only":true}`, ""}, + {ToolShowDiff, `{"committed_only":"yes"}`, "committed_only must be true or false"}, + {ToolShowRun, `{"run_id":12}`, ""}, + {ToolShowRun, `{"id":12}`, `unknown argument "id"`}, + {ToolNotify, `{"title":"t","message":"m","priority":"urgent"}`, "priority must be one of low, default, high"}, + {ToolScheduleFollowup, `{"message":"m","after_minutes":5}`, ""}, + {ToolScheduleFollowup, `{"message":"m","in_minutes":5,"delay":1}`, `unknown arguments "delay", "in_minutes"`}, + } + for _, c := range cases { + err := ValidateArguments(c.tool, json.RawMessage(c.args)) + switch { + case c.want == "" && err != nil: + t.Errorf("%s %s: unexpected %v", c.tool, c.args, err) + case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)): + t.Errorf("%s %s: got %v, want %q", c.tool, c.args, err, c.want) + } + } +} + +func TestEveryListedToolIsATool(t *testing.T) { + for _, definition := range definitions() { + if !IsTool(definition.Name) { + t.Errorf("%s is listed but not a tool", definition.Name) + } + if definition.InputSchema["additionalProperties"] != false { + t.Errorf("%s schema allows additional properties", definition.Name) + } + } +} diff --git a/internal/pipeline/chat_tools.go b/internal/pipeline/chat_tools.go index 349b76fe..d52997a0 100644 --- a/internal/pipeline/chat_tools.go +++ b/internal/pipeline/chat_tools.go @@ -102,6 +102,70 @@ func (s *Store) AppendChatShownItem(ctx context.Context, sessionID string, item SELECT id FROM chat_shown_items WHERE session_id=? ORDER BY created_at DESC, rowid DESC LIMIT ?)`, sessionID, sessionID, protocol.ChatShownLimit); err != nil { return err } + if err := applyChatShownBudget(ctx, tx, sessionID); err != nil { + return err + } + return tx.Commit() +} + +// ReplaceChatShownItem stores item over the chat's existing item with the +// same id (found false when the chat has none), then applies the body budget. +func (s *Store) ReplaceChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) (bool, error) { + payload, err := json.Marshal(item) + if err != nil { + return false, err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return false, err + } + defer tx.Rollback() + result, err := tx.ExecContext(ctx, `UPDATE chat_shown_items SET payload=? WHERE session_id=? AND id=?`, string(payload), sessionID, item.ID) + if err != nil { + return false, err + } + if n, _ := result.RowsAffected(); n == 0 { + return false, nil + } + if err := applyChatShownBudget(ctx, tx, sessionID); err != nil { + return false, err + } + return true, tx.Commit() +} + +// ChatShownItem returns one of a chat's retained items by id. +func (s *Store) ChatShownItem(ctx context.Context, sessionID, id string) (protocol.ChatShownItem, bool, error) { + var payload string + err := s.db.QueryRowContext(ctx, `SELECT payload FROM chat_shown_items WHERE session_id=? AND id=?`, sessionID, id).Scan(&payload) + if errors.Is(err, sql.ErrNoRows) { + return protocol.ChatShownItem{}, false, nil + } + if err != nil { + return protocol.ChatShownItem{}, false, err + } + var item protocol.ChatShownItem + if err := json.Unmarshal([]byte(payload), &item); err != nil { + return protocol.ChatShownItem{}, false, err + } + return item, true, nil +} + +// RunSummaryByID returns one run's summary (found false for an unknown run). +func (s *Store) RunSummaryByID(ctx context.Context, id int64) (protocol.RunSummary, bool, error) { + var summary protocol.RunSummary + err := scanRun(s.db.QueryRowContext(ctx, runSelect+" WHERE r.id=?", id), &summary) + if errors.Is(err, sql.ErrNoRows) { + return protocol.RunSummary{}, false, nil + } + if err != nil { + return protocol.RunSummary{}, false, err + } + return summary, true, nil +} + +// applyChatShownBudget keeps HTML and diff bodies only for the newest +// documents within protocol.ChatShownHTMLBudget. +func applyChatShownBudget(ctx context.Context, tx *sql.Tx, sessionID string) error { items, err := chatShownItems(ctx, tx, sessionID) if err != nil { return err @@ -138,7 +202,7 @@ SELECT id FROM chat_shown_items WHERE session_id=? ORDER BY created_at DESC, row return err } } - return tx.Commit() + return nil } // ChatShownItems returns a chat's retained items, oldest first. diff --git a/internal/protocol/chat_shown.go b/internal/protocol/chat_shown.go index 2c6216af..1870f708 100644 --- a/internal/protocol/chat_shown.go +++ b/internal/protocol/chat_shown.go @@ -2,8 +2,8 @@ package protocol // ChatShown is the pushed frame type for an item a chat's model showed the // operator through the Pipelines tools (show_file, show_image, show_html, -// show_diff, notify). The chat_subscribe reply carries the retained list in the same -// ChatShown field. +// show_diff, show_run, notify). The chat_subscribe reply carries the retained +// list in the same ChatShown field. const ChatShown = "chat_shown" // The ChatShownItem kinds. @@ -12,6 +12,7 @@ const ( ChatShownImage = "image" ChatShownHTML = "html" ChatShownDiff = "diff" + ChatShownRun = "run" ChatShownNotify = "notify" ) @@ -23,6 +24,14 @@ const ( ChatShownHTMLBudget = 2 << 20 ) +// The ChatShownItem file states, computed when a chat's items are listed. +const ( + // ChatShownFileChanged: the live file differs from what was shown. + ChatShownFileChanged = "changed" + // ChatShownFileMissing: the file (or its snapshot) no longer exists. + ChatShownFileMissing = "missing" +) + // ChatShownFrame is one chat's shown items, oldest first. type ChatShownFrame struct { SessionID string `json:"session_id"` @@ -30,17 +39,29 @@ type ChatShownFrame struct { } // ChatShownItem is one entry. A file or image Path is an absolute path on the -// chat's own machine, served by that machine's /files endpoint; URL is an -// https image address the client loads without credentials. +// chat's own machine, served by that machine's /files endpoint. When Snapshot +// is set, Path is a copy Pipelines took when the item was shown (Source is the +// path the model named; URL the https address an image was fetched from); +// otherwise Path is the live file, and ModTime and SHA256 record what was +// shown so State can say it changed since. A web image without Path is an +// older entry the client loads from URL itself. A replaced item keeps its ID +// and CreatedAt (its place in the transcript) and sets UpdatedAt. type ChatShownItem struct { ID string `json:"id"` Kind string `json:"kind"` CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at,omitempty"` Title string `json:"title,omitempty"` Path string `json:"path,omitempty"` Name string `json:"name,omitempty"` Size int64 `json:"size,omitempty"` Mime string `json:"mime,omitempty"` + Snapshot bool `json:"snapshot,omitempty"` + Source string `json:"source,omitempty"` + ModTime int64 `json:"mod_time,omitempty"` + SHA256 string `json:"sha256,omitempty"` + // State is ChatShownFileChanged or ChatShownFileMissing, else empty. + State string `json:"state,omitempty"` URL string `json:"url,omitempty"` Alt string `json:"alt,omitempty"` HTML string `json:"html,omitempty"` @@ -49,6 +70,8 @@ type ChatShownItem struct { // of its patches, counted against ChatShownHTMLBudget. Diff *ChatShownDiffBody `json:"diff,omitempty"` DiffBytes int `json:"diff_bytes,omitempty"` + // Run is a show_run item's run, kept current as the run changes. + Run *ChatShownRunBody `json:"run,omitempty"` // HeightHint is the model's preferred inline height in logical pixels. HeightHint int `json:"height_hint,omitempty"` Expired bool `json:"expired,omitempty"` @@ -62,15 +85,33 @@ type ChatShownItem struct { Channels []string `json:"channels,omitempty"` } +// ChatShownRunBody is the run a show_run item follows. StartedAt and +// FinishedAt are epoch milliseconds (FinishedAt zero while it runs). +type ChatShownRunBody struct { + ID int64 `json:"id"` + Pipeline string `json:"pipeline"` + Title string `json:"title,omitempty"` + Status string `json:"status"` + Outcome string `json:"outcome,omitempty"` + CurrentStage string `json:"current_stage,omitempty"` + Workspace string `json:"workspace,omitempty"` + StartedAt int64 `json:"started_at,omitempty"` + FinishedAt int64 `json:"finished_at,omitempty"` +} + // ChatShownDiffBody is one Git comparison a chat's model showed: the work tree -// (or HEAD when CommittedOnly) of Repo against BaseCommit, which is HEAD when -// Base is empty and the merge base with Base otherwise. Changes uses the same -// per-file shape as a run's recorded changes; it is nil once Expired. +// (or HEAD when CommittedOnly, or HeadRevision when set) of Repo against +// BaseCommit, which is HEAD when Base is empty and the merge base with Base +// otherwise. Paths, when set, limits the comparison to those paths or globs. +// Changes uses the same per-file shape as a run's recorded changes; it is nil +// once Expired. type ChatShownDiffBody struct { Repo string `json:"repo"` Base string `json:"base,omitempty"` BaseCommit string `json:"base_commit,omitempty"` Head string `json:"head,omitempty"` + HeadRevision string `json:"head_revision,omitempty"` + Paths []string `json:"paths,omitempty"` CommittedOnly bool `json:"committed_only,omitempty"` Files int `json:"files"` Additions int `json:"additions"` diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 5664a17f..25a35787 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -92,6 +92,9 @@ type chatHub struct { // shown holds the items chats showed through the Pipelines tools; the // subscribe reply carries a chat's retained list. nil records none. shown chatShownStore + // shownRefresh brings listed items up to date (file states, followed + // runs) before a subscribe reply carries them; nil leaves them as stored. + shownRefresh func(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem // autoSwitch records the usage-limit refusals the server already // continued on another Claude account (chat_auto_switch.go). autoSwitch chatAutoSwitchState diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index fbf5b099..2f5d26a6 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -8,6 +8,7 @@ import ( "log" "net/url" "path/filepath" + "strings" "time" "git.a-wan.net/alan/pipelines/internal/opencode" @@ -100,8 +101,10 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat } // A prompt scheduled for later is always queued: never run or steered now. scheduled := p.sendAt.After(h.clock()) - busy := scheduled || room.running || len(room.queue) > 0 || room.observedTurn - queuedAhead := scheduled || len(room.queue) > 0 + // Agent follow-ups that are not due yet hold nothing up. + head, _ := chatQueueHead(room.queue, h.clock()) + busy := scheduled || room.running || head >= 0 || room.observedTurn + queuedAhead := scheduled || head >= 0 h.mu.Unlock() if !busy { busy = brokerTurnRunning(broker, sessionID) @@ -154,6 +157,35 @@ func (h *chatHub) admitPrompt(ctx context.Context, sessionID string, broker chat return chatAdmitQueued, nil } +// chatFollowupPrefix starts the operation id of a prompt an agent scheduled +// for itself (schedule_followup). Such a prompt is the one exception to the +// queue's FIFO order: until it is due it steps aside, so the operator's own +// prompts are never held behind an agent's reminder for hours. +const chatFollowupPrefix = "followup-" + +// isFollowup reports whether p is an agent's scheduled follow-up. +func (p *chatQueuedPrompt) isFollowup() bool { + return strings.HasPrefix(p.operationID, chatFollowupPrefix) +} + +// chatQueueHead is the index of the prompt the runner considers next: the +// first one that is not an agent follow-up still waiting for its time, or -1 +// when there is none. followupWait is how long until the earliest of the +// skipped follow-ups is due (zero when none was skipped). +func chatQueueHead(queue []*chatQueuedPrompt, now time.Time) (int, time.Duration) { + var followupWait time.Duration + for i, p := range queue { + if p.isFollowup() && p.sendAt.After(now) { + if wait := p.sendAt.Sub(now); followupWait == 0 || wait < followupWait { + followupWait = wait + } + continue + } + return i, followupWait + } + return -1, followupWait +} + func errChatQueueFull(sessionID string) error { return errors.New("session " + sessionID + " already has the maximum number of prompts queued") } diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 37513763..85a69615 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -801,12 +801,20 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{}, return nil, nil, false } var wait time.Duration + head, followupWait := chatQueueHead(room.queue, h.clock()) if len(room.queue) > 0 { switch now := h.clock(); { - case room.queue[0].sendAt.After(now): + case head < 0: + // Only agent follow-ups that are not due yet: sleep until the + // first of them. + wait = min(followupWait, chatQueueScheduleRecheck) + case room.queue[head].sendAt.After(now): // A scheduled head waits for its time; the queue is FIFO, so // later prompts wait behind it. A timer wakes the runner then. - wait = min(room.queue[0].sendAt.Sub(now), chatQueueScheduleRecheck) + wait = min(room.queue[head].sendAt.Sub(now), chatQueueScheduleRecheck) + if followupWait > 0 { + wait = min(wait, followupWait) + } case room.observedTurn: wait = chatQueueBusyPoll if !room.running { @@ -826,9 +834,9 @@ func (h *chatHub) nextPrompt(room *chatRoom) (*chatQueuedPrompt, chan struct{}, h.mu.Lock() if busy { wait = chatQueueBusyPoll - } else if len(room.queue) > 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[0].sendAt.After(h.clock()) { - p := room.queue[0] - room.queue = room.queue[1:] + } else if index, _ := chatQueueHead(room.queue, h.clock()); index >= 0 && !room.observedTurn && room.ctx.Err() == nil && !room.queue[index].sendAt.After(h.clock()) { + p := room.queue[index] + room.queue = append(room.queue[:index:index], room.queue[index+1:]...) room.running = true room.nativeTurnID = "" room.turnDone = make(chan struct{}) diff --git a/internal/server/chat_tools_diff.go b/internal/server/chat_tools_diff.go index d8a4ede3..4fbd91d2 100644 --- a/internal/server/chat_tools_diff.go +++ b/internal/server/chat_tools_diff.go @@ -32,10 +32,56 @@ const ( type showDiffRequest struct { Path string Base string + Head string + Paths []string CommittedOnly bool Title string } +// showDiffMaxPaths bounds the paths argument. +const showDiffMaxPaths = 50 + +// showDiffPathspecs turns the model's paths into Git pathspecs confined to the +// repository: each must be relative, without a .. component, option prefix, +// pathspec magic or control character. A path with glob characters matches as +// a glob (":(glob)"), any other literally. +func showDiffPathspecs(paths []string) ([]string, []string, error) { + if len(paths) > showDiffMaxPaths { + return nil, nil, fmt.Errorf("paths has %d entries; the limit is %d", len(paths), showDiffMaxPaths) + } + var specs, kept []string + for _, raw := range paths { + path := strings.TrimSpace(raw) + if path == "" { + continue + } + if len(path) > 500 || strings.HasPrefix(path, "-") || strings.HasPrefix(path, ":") || filepath.IsAbs(path) || strings.HasPrefix(path, "~") { + return nil, nil, fmt.Errorf("paths entry %q must be a path inside the repository, relative to its top", raw) + } + for _, r := range path { + if unicode.IsControl(r) { + return nil, nil, fmt.Errorf("paths entry %q contains a control character", raw) + } + } + for _, part := range strings.Split(filepath.ToSlash(path), "/") { + if part == ".." { + return nil, nil, fmt.Errorf("paths entry %q leaves the repository", raw) + } + } + path = strings.TrimSuffix(filepath.ToSlash(filepath.Clean(path)), "/") + if path == "." { + continue + } + kept = append(kept, path) + if strings.ContainsAny(path, "*?[") { + specs = append(specs, ":(glob)"+path) + } else { + specs = append(specs, ":(literal)"+path) + } + } + return specs, kept, nil +} + // runShowDiff compares a repository inside the operator's home and records // the per-file patches as one diff item. func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in showDiffRequest) (*protocol.ChatShownItem, chattools.Result) { @@ -49,6 +95,17 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in if base != "" && !validGitRevision(base) { return fail(fmt.Errorf("base %q is not a branch, tag or commit name", base)) } + headName := strings.TrimSpace(in.Head) + if headName != "" && !validGitRevision(headName) { + return fail(fmt.Errorf("head %q is not a branch, tag or commit name", headName)) + } + if headName != "" && in.CommittedOnly { + return fail(errors.New("committed_only does not apply with head, which is always committed")) + } + pathspecs, paths, err := showDiffPathspecs(in.Paths) + if err != nil { + return fail(err) + } directory, err := s.resolveDiffDirectory(ctx, sessionID, in.Path) if err != nil { return fail(err) @@ -70,8 +127,23 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in } else if head != "" { body.Head = shortCommit(head) } + current := head + if headName != "" { + target, err := git.output("rev-parse", "--verify", "--quiet", "--end-of-options", headName+"^{commit}") + if err != nil { + return fail(fmt.Errorf("head %q is not a commit in %s", headName, git.directory)) + } + head, headErr = strings.TrimSpace(target), nil + body.Head, body.HeadRevision = headName, headName + } + body.Paths = paths var compare string switch { + case headName != "" && base == "": + if current == "" { + return fail(errors.New("this repository has no HEAD commit to compare " + headName + " with; pass base")) + } + compare = current case base != "": if headErr != nil || head == "" { return fail(errors.New("this repository has no commits yet, so there is nothing to compare with " + base)) @@ -94,11 +166,12 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in body.BaseCommit = shortCommit(compare) } revisions := []string{compare} - if in.CommittedOnly { + worktree := !in.CommittedOnly && headName == "" + if !worktree { revisions = append(revisions, head) } - changes, err := collectGitDiff(git, revisions, !in.CommittedOnly) + changes, err := collectGitDiff(git, revisions, worktree, pathspecs) if err != nil { return fail(err) } @@ -118,6 +191,10 @@ func (s *chatToolService) runShowDiff(ctx context.Context, sessionID string, in func showDiffSummary(body protocol.ChatShownDiffBody) string { against := "HEAD" switch { + case body.HeadRevision != "" && body.Base != "": + against = fmt.Sprintf("%s (merge base %s), showing %s", body.Base, body.BaseCommit, body.HeadRevision) + case body.HeadRevision != "": + against = fmt.Sprintf("HEAD (%s), showing %s", body.BaseCommit, body.HeadRevision) case body.Base != "" && body.CommittedOnly: against = fmt.Sprintf("%s (merge base %s), committed changes only", body.Base, body.BaseCommit) case body.Base != "": @@ -125,6 +202,9 @@ func showDiffSummary(body protocol.ChatShownDiffBody) string { case body.BaseCommit == "": against = "an empty repository" } + if len(body.Paths) > 0 { + against += ", limited to " + strings.Join(body.Paths, ", ") + } if body.Files == 0 { return fmt.Sprintf("Shown in the operator's Pipelines chat: no changes in %s against %s.", body.Repo, against) } diff --git a/internal/server/chat_tools_diff_collect.go b/internal/server/chat_tools_diff_collect.go index 4a3f8b85..7fc58228 100644 --- a/internal/server/chat_tools_diff_collect.go +++ b/internal/server/chat_tools_diff_collect.go @@ -20,15 +20,15 @@ type gitDiffEntry struct { // work tree against it; two: those commits) plus, when includeUntracked, the // untracked files Git does not ignore, and reads each file's patch within the // show_diff bounds. -func collectGitDiff(git gitRunner, revisions []string, includeUntracked bool) (*protocol.StageFileChanges, error) { +func collectGitDiff(git gitRunner, revisions []string, includeUntracked bool, pathspecs []string) (*protocol.StageFileChanges, error) { nameArgs := append([]string{"diff", "--name-status", "-z", "--no-renames"}, revisions...) - names, err := git.output(append(nameArgs, "--")...) + names, err := git.output(append(append(nameArgs, "--"), pathspecs...)...) if err != nil { return nil, err } entries := parseNameStatus(names) if includeUntracked { - others, err := git.output("ls-files", "--others", "--exclude-standard", "-z") + others, err := git.output(append([]string{"ls-files", "--others", "--exclude-standard", "-z", "--"}, pathspecs...)...) if err != nil { return nil, err } diff --git a/internal/server/chat_tools_diff_options_test.go b/internal/server/chat_tools_diff_options_test.go new file mode 100644 index 00000000..9c8fef94 --- /dev/null +++ b/internal/server/chat_tools_diff_options_test.go @@ -0,0 +1,60 @@ +package server + +import ( + "os/exec" + "strings" + "testing" +) + +func TestShowDiffHeadAndPaths(t *testing.T) { + f := newChatToolFixture(t) + repo := showDiffRepo(t, f.home) + token := f.token(t, chatToolSessionScope+"ses_o") + if out, err := exec.Command("git", "-C", repo, "switch", "-q", "--discard-changes", "main").CombinedOutput(); err != nil { + t.Fatalf("switch to main: %v %s", err, out) + } + + // head instead of the work tree: feature against HEAD (main). + r := f.call(token, "show_diff", `{"path":"`+repo+`","head":"feature"}`) + if r.IsError { + t.Fatal(r.Text) + } + item := diffItem(t, f, "ses_o") + if got := diffPaths(item); len(got) != 2 || got["a.txt"] != "modified" || got["b.txt"] != "added" { + t.Fatalf("head compares the revision, without untracked files: %v", got) + } + if item.Diff.HeadRevision != "feature" || item.Diff.Head != "feature" || !strings.Contains(r.Text, "showing feature") { + t.Fatalf("summary: %+v %s", item.Diff, r.Text) + } + + // head against a base, limited to a path and a glob. + if r := f.call(token, "show_diff", `{"path":"`+repo+`","head":"feature","base":"main","paths":["b.txt"]}`); r.IsError { + t.Fatal(r.Text) + } + item = diffItem(t, f, "ses_o") + if got := diffPaths(item); len(got) != 1 || got["b.txt"] != "added" || len(item.Diff.Paths) != 1 { + t.Fatalf("paths limits the diff: %v %+v", got, item.Diff) + } + if r := f.call(token, "show_diff", `{"path":"`+repo+`","paths":["*.txt"]}`); r.IsError { + t.Fatal(r.Text) + } + if got := diffPaths(diffItem(t, f, "ses_o")); len(got) != 1 || got["u.txt"] != "added" { + t.Fatalf("a glob matches untracked work too: %v", got) + } + + for _, tc := range []struct{ args, want string }{ + {`{"path":"` + repo + `","head":"--output=/tmp/x"}`, "head \"--output=/tmp/x\" is not a branch"}, + {`{"path":"` + repo + `","head":"nope"}`, "is not a commit"}, + {`{"path":"` + repo + `","head":"feature","base":"main","committed_only":true}`, "committed_only does not apply"}, + {`{"path":"` + repo + `","paths":["../outside"]}`, "leaves the repository"}, + {`{"path":"` + repo + `","paths":["/etc/passwd"]}`, "must be a path inside the repository"}, + {`{"path":"` + repo + `","paths":[":(top)x"]}`, "must be a path inside the repository"}, + {`{"path":"` + repo + `","paths":["-x"]}`, "must be a path inside the repository"}, + {`{"path":"` + repo + `","paths":"a.txt"}`, "paths must be an array of strings"}, + } { + r := f.call(token, "show_diff", tc.args) + if !r.IsError || !strings.Contains(r.Text, tc.want) { + t.Errorf("%s: want refusal %q, got %+v", tc.args, tc.want, r) + } + } +} diff --git a/internal/server/chat_tools_fetch.go b/internal/server/chat_tools_fetch.go new file mode 100644 index 00000000..528b6e49 --- /dev/null +++ b/internal/server/chat_tools_fetch.go @@ -0,0 +1,214 @@ +package server + +import ( + "bytes" + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "mime" + "net" + "net/http" + "net/netip" + "net/url" + "path" + "strings" + "syscall" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// show_image downloads a web image on the server, so the operator's device +// never has to fetch a cross-origin address (which many hosts refuse), and +// keeps the bytes as the item's snapshot. The download is SSRF-safe: https +// only, every connection (redirects included) to a public unicast address +// checked after DNS resolution, no proxy, no credentials, a timeout, at most +// chattools.MaxFetchedImageBytes, and only raster image types whose bytes +// agree with the declared type. + +const shownImageFetchTimeout = 20 * time.Second + +// shownImageTypes are the image types fetched, by extension. SVG is refused: +// served from the app's origin it could carry script. +var shownImageTypes = map[string]string{ + "image/png": ".png", + "image/jpeg": ".jpg", + "image/gif": ".gif", + "image/webp": ".webp", + "image/avif": ".avif", + "image/bmp": ".bmp", +} + +// shownImageFetcher downloads web images. allowed decides which resolved +// addresses may be dialed; tlsConfig is for tests. +type shownImageFetcher struct { + allowed func(netip.Addr) bool + tlsConfig *tls.Config +} + +// publicAddress admits only global unicast addresses that are not private, +// loopback, link-local, shared (CGNAT), documentation or otherwise special. +func publicAddress(addr netip.Addr) bool { + addr = addr.Unmap() + if !addr.IsValid() || !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || + addr.IsLinkLocalUnicast() || addr.IsMulticast() || addr.IsUnspecified() { + return false + } + for _, prefix := range shownBlockedPrefixes { + if prefix.Contains(addr) { + return false + } + } + return true +} + +var shownBlockedPrefixes = []netip.Prefix{ + netip.MustParsePrefix("0.0.0.0/8"), + netip.MustParsePrefix("100.64.0.0/10"), + netip.MustParsePrefix("192.0.0.0/24"), + netip.MustParsePrefix("192.0.2.0/24"), + netip.MustParsePrefix("198.18.0.0/15"), + netip.MustParsePrefix("198.51.100.0/24"), + netip.MustParsePrefix("203.0.113.0/24"), + netip.MustParsePrefix("240.0.0.0/4"), + netip.MustParsePrefix("64:ff9b::/96"), + netip.MustParsePrefix("64:ff9b:1::/48"), + netip.MustParsePrefix("2001::/23"), + netip.MustParsePrefix("2001:db8::/32"), + netip.MustParsePrefix("2002::/16"), +} + +var errShownAddressRefused = errors.New("the image host resolves to a private or local address, which Pipelines does not fetch from") + +func (f shownImageFetcher) client() *http.Client { + allowed := f.allowed + if allowed == nil { + allowed = publicAddress + } + dialer := &net.Dialer{Timeout: 10 * time.Second, Control: func(_, address string, _ syscall.RawConn) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + return err + } + addr, err := netip.ParseAddr(host) + if err != nil || !allowed(addr) { + return errShownAddressRefused + } + return nil + }} + transport := &http.Transport{ + Proxy: nil, + DialContext: dialer.DialContext, + TLSClientConfig: f.tlsConfig, + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: 15 * time.Second, + MaxIdleConns: 1, + DisableKeepAlives: true, + } + return &http.Client{Transport: transport, Timeout: shownImageFetchTimeout, CheckRedirect: func(request *http.Request, via []*http.Request) error { + if len(via) >= 5 { + return errors.New("the image URL redirects too many times") + } + if request.URL.Scheme != "https" { + return fmt.Errorf("the image URL redirects to a non-https address (%s)", request.URL.Redacted()) + } + return nil + }} +} + +// fetchShownImage downloads the https image at raw and records it as a +// snapshot image item (id is the item's id). +func (s *chatToolService) fetchShownImage(ctx context.Context, sessionID, id, raw string) (protocol.ChatShownItem, error) { + address, err := shownImageURL(raw) + if err != nil { + return protocol.ChatShownItem{}, err + } + data, mediaType, err := s.fetch.get(ctx, address) + if err != nil { + return protocol.ChatShownItem{}, err + } + name := shownImageName(address, shownImageTypes[mediaType]) + path, size, err := s.writeSnapshot(sessionID, id, name, bytes.NewReader(data)) + if err != nil { + return protocol.ChatShownItem{}, fmt.Errorf("Pipelines downloaded the image but could not keep it: %v", err) + } + return protocol.ChatShownItem{Kind: protocol.ChatShownImage, Path: path, Name: name, Size: size, Mime: mediaType, Snapshot: true, URL: address}, nil +} + +// get downloads one image and returns its bytes and media type. +func (f shownImageFetcher) get(ctx context.Context, address string) ([]byte, string, error) { + ctx, cancel := context.WithTimeout(ctx, shownImageFetchTimeout) + defer cancel() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil) + if err != nil { + return nil, "", errors.New("the image URL is not valid") + } + request.Header.Set("Accept", "image/png,image/jpeg,image/gif,image/webp,image/avif,image/bmp;q=0.9") + request.Header.Set("User-Agent", "Pipelines-image-fetch/1") + response, err := f.client().Do(request) + if err != nil { + if errors.Is(err, errShownAddressRefused) { + return nil, "", errShownAddressRefused + } + var redirect *url.Error + if errors.As(err, &redirect) && redirect.Err != nil && strings.Contains(redirect.Err.Error(), "redirect") { + return nil, "", redirect.Err + } + return nil, "", fmt.Errorf("the image could not be downloaded: %v", shownFetchError(err)) + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, "", fmt.Errorf("the image host answered %s", response.Status) + } + mediaType, _, _ := mime.ParseMediaType(response.Header.Get("Content-Type")) + if _, ok := shownImageTypes[mediaType]; !ok { + if mediaType == "" { + mediaType = "no content type" + } + return nil, "", fmt.Errorf("the URL is %s, not a PNG, JPEG, GIF, WebP, AVIF or BMP image", mediaType) + } + if response.ContentLength > chattools.MaxFetchedImageBytes { + return nil, "", fmt.Errorf("the image is %s; the limit is 10 MiB", humanBytes(response.ContentLength)) + } + data, err := io.ReadAll(io.LimitReader(response.Body, chattools.MaxFetchedImageBytes+1)) + if err != nil { + return nil, "", fmt.Errorf("the image download failed: %v", shownFetchError(err)) + } + if len(data) > chattools.MaxFetchedImageBytes { + return nil, "", errors.New("the image is larger than the 10 MiB limit") + } + if len(data) == 0 { + return nil, "", errors.New("the image is empty") + } + if sniffed := http.DetectContentType(data); strings.HasPrefix(sniffed, "text/") || sniffed == "application/octet-stream" && mediaType != "image/avif" { + return nil, "", fmt.Errorf("the URL says it is %s but its content is not an image", mediaType) + } + return data, mediaType, nil +} + +func shownFetchError(err error) error { + var urlErr *url.Error + if errors.As(err, &urlErr) { + return urlErr.Err + } + return err +} + +// shownImageName is the image's file name from its URL path, with the +// extension of its type. +func shownImageName(address, extension string) string { + base := "image" + if parsed, err := url.Parse(address); err == nil { + if name := path.Base(parsed.Path); name != "." && name != "/" && name != "" { + base = strings.TrimSuffix(name, path.Ext(name)) + } + } + base = safeSnapshotName(base) + if len(base) > 120 { + base = truncateUTF8(base, 120) + } + return base + extension +} diff --git a/internal/server/chat_tools_fetch_test.go b/internal/server/chat_tools_fetch_test.go new file mode 100644 index 00000000..3c2cf18a --- /dev/null +++ b/internal/server/chat_tools_fetch_test.go @@ -0,0 +1,101 @@ +package server + +import ( + "bytes" + "net/http" + "net/http/httptest" + "net/netip" + "strconv" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/chattools" +) + +var testPNG = append([]byte("\x89PNG\r\n\x1a\n"), bytes.Repeat([]byte{0}, 32)...) + +// imageServer is a loopback https host the fixture's fetcher may reach. +func (f *chatToolFixture) imageServer(t *testing.T) *httptest.Server { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("/a.png", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(testPNG) + }) + mux.HandleFunc("/page", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte("")) + }) + mux.HandleFunc("/drawing.svg", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/svg+xml") + _, _ = w.Write([]byte("")) + }) + mux.HandleFunc("/fake.png", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write([]byte("")) + }) + mux.HandleFunc("/big.png", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "image/png") + w.Header().Set("Content-Length", strconv.Itoa(chattools.MaxFetchedImageBytes+1)) + _, _ = w.Write(append(testPNG, make([]byte, chattools.MaxFetchedImageBytes+1-len(testPNG))...)) + }) + mux.HandleFunc("/to-http", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://"+r.Host+"/a.png", http.StatusFound) + }) + mux.HandleFunc("/to-png", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/a.png", http.StatusFound) + }) + server := httptest.NewTLSServer(mux) + t.Cleanup(server.Close) + f.service.fetch = shownImageFetcher{ + allowed: func(addr netip.Addr) bool { return addr.IsLoopback() }, + tlsConfig: server.Client().Transport.(*http.Transport).TLSClientConfig, + } + return server +} + +func TestShowImageFetchesOnlyRealImagesWithinBounds(t *testing.T) { + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_w") + web := f.imageServer(t) + if r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/to-png"}`); r.IsError { + t.Fatalf("an https redirect is followed: %v", r) + } + for path, want := range map[string]string{ + "/page": "text/html, not a PNG", + "/drawing.svg": "image/svg+xml, not a PNG", + "/fake.png": "content is not an image", + "/big.png": "the limit is 10 MiB", + "/to-http": "redirects to a non-https address", + "/missing.png": "answered 404", + } { + r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+path+`"}`) + if !r.IsError || !strings.Contains(r.Text, want) { + t.Errorf("%s: got %v, want %q", path, r, want) + } + } + if got := f.items(t, "ses_w"); len(got) != 1 { + t.Fatalf("only the real image is recorded: %+v", got) + } +} + +func TestShowImageRefusesPrivateAndLocalHosts(t *testing.T) { + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_s") + web := f.imageServer(t) + f.service.fetch.allowed = publicAddress + r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/a.png"}`) + if !r.IsError || !strings.Contains(r.Text, "private or local address") { + t.Fatalf("a loopback host must be refused: %v", r) + } + for _, refused := range []string{"127.0.0.1", "10.1.2.3", "172.16.0.1", "192.168.1.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "224.0.0.1", "::1", "fc00::1", "fe80::1", "::ffff:127.0.0.1", "::ffff:10.0.0.1", "2001:db8::1", "198.18.0.1"} { + if publicAddress(netip.MustParseAddr(refused)) { + t.Errorf("%s must not be fetched from", refused) + } + } + for _, allowed := range []string{"93.184.216.34", "1.1.1.1", "2606:4700:4700::1111"} { + if !publicAddress(netip.MustParseAddr(allowed)) { + t.Errorf("%s is a public address", allowed) + } + } +} diff --git a/internal/server/chat_tools_followup.go b/internal/server/chat_tools_followup.go new file mode 100644 index 00000000..0785c396 --- /dev/null +++ b/internal/server/chat_tools_followup.go @@ -0,0 +1,111 @@ +package server + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// schedule_followup puts a prompt into the calling chat's own durable queue +// with a send_at, under the sender label chatFollowupClient. The operator sees +// it as a scheduled message from the agent and can remove it like any queued +// prompt; until it is due it does not hold the operator's prompts back +// (chatQueueHead). + +// chatFollowupClient is the sender label of an agent's follow-up prompt. +const chatFollowupClient = "Agent follow-up" + +func (s *chatToolService) runScheduleFollowup(ctx context.Context, sessionID, message, at string, afterMinutes *int64) chattools.Result { + fail := func(format string, args ...any) chattools.Result { + return chattools.Result{Text: "Nothing was scheduled: " + fmt.Sprintf(format, args...), IsError: true} + } + message = strings.TrimSpace(message) + if message == "" { + return fail("message is empty.") + } + if len(message) > chattools.MaxFollowupTextBytes { + return fail("message is %s; the limit is 8 KiB.", humanBytes(int64(len(message)))) + } + at = strings.TrimSpace(at) + now := s.now() + var sendAt time.Time + switch { + case at != "" && afterMinutes != nil: + return fail("give either at or after_minutes, not both.") + case afterMinutes != nil: + if *afterMinutes < chattools.MinFollowupMinutes || *afterMinutes > chattools.MaxFollowupMinutes { + return fail("after_minutes must be between %d and %d (7 days).", chattools.MinFollowupMinutes, chattools.MaxFollowupMinutes) + } + sendAt = now.Add(time.Duration(*afterMinutes) * time.Minute) + case at != "": + parsed, err := time.Parse(time.RFC3339, at) + if err != nil { + return fail("at must be an RFC 3339 time with a zone, such as %s.", now.Add(time.Hour).UTC().Format(time.RFC3339)) + } + // A few seconds of slack for a time computed as "one minute from now". + if parsed.Before(now.Add(time.Duration(chattools.MinFollowupMinutes)*time.Minute - 5*time.Second)) { + return fail("at must be at least %d minute from now (it is %s).", chattools.MinFollowupMinutes, now.UTC().Format(time.RFC3339)) + } + if parsed.After(now.Add(time.Duration(chattools.MaxFollowupMinutes) * time.Minute)) { + return fail("at must be at most 7 days from now.") + } + sendAt = parsed + default: + return fail("give at (an RFC 3339 time) or after_minutes.") + } + if s.hub == nil || s.broker == nil { + return fail("follow-ups are not available on this server.") + } + pending := 0 + for _, prompt := range s.hub.queueFrame(sessionID).Prompts { + if strings.HasPrefix(prompt.OperationID, chatFollowupPrefix) { + pending++ + } + } + if pending >= chattools.MaxPendingFollowups { + return fail("this chat already has %d follow-ups pending (the limit is %d); the operator can remove one, or wait for one to be delivered.", pending, chattools.MaxPendingFollowups) + } + var token [8]byte + _, _ = rand.Read(token[:]) + operationID := chatFollowupPrefix + hex.EncodeToString(token[:]) + text := fmt.Sprintf("[Follow-up you scheduled at %s with schedule_followup] %s", now.UTC().Format(time.RFC3339), message) + if err := s.hub.queueFollowup(ctx, s.broker, sessionID, operationID, text, sendAt); err != nil { + return fail("%v", err) + } + return chattools.Result{Text: fmt.Sprintf("Scheduled: Pipelines will send this chat your follow-up at %s (in %s), when the chat is free; the operator sees it queued and can remove it. Do not wait for it now.", + sendAt.UTC().Format(time.RFC3339), sendAt.Sub(now).Round(time.Minute))} +} + +// queueFollowup queues an agent's follow-up prompt for sendAt: durably, under +// the follow-up sender label, shown to every attached client as scheduled. +func (h *chatHub) queueFollowup(ctx context.Context, broker chatBroker, sessionID, operationID, text string, sendAt time.Time) error { + p := &chatQueuedPrompt{ + text: text, + operationID: operationID, + messageID: h.nextUserMessageID(), + client: chatFollowupClient, + noSteer: true, + sendAt: sendAt, + } + h.rememberOp(sessionID, operationID) + admission, err := h.admitPrompt(ctx, sessionID, broker, p) + if admission == chatAdmitRefused { + h.forgetOp(sessionID, operationID) + return err + } + h.broadcastUser(protocol.ChatEventFrame{ + SessionID: sessionID, + MessageID: p.messageID, + Kind: protocol.ChatEventUser, + Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "usr", Text: text}, + Client: chatFollowupClient, + OperationID: operationID, + }, "") + return nil +} diff --git a/internal/server/chat_tools_followup_test.go b/internal/server/chat_tools_followup_test.go new file mode 100644 index 00000000..b578d0cd --- /dev/null +++ b/internal/server/chat_tools_followup_test.go @@ -0,0 +1,67 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "path/filepath" + "strings" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// schedule_followup queues a durable, removable prompt under the agent's +// follow-up label, and a pending follow-up never holds the operator's own +// prompt back. +func TestScheduleFollowupQueuesWithoutBlockingTheOperator(t *testing.T) { + store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) + broker := newChannelChat() + server := startQueueServer(t, broker, store) + token, err := store.ChatToolToken(context.Background(), chatToolSessionScope+"ses_1") + if err != nil { + t.Fatal(err) + } + call := func(arguments string) map[string]any { + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"schedule_followup","arguments":` + arguments + `}}` + request, _ := http.NewRequestWithContext(server.ctx, http.MethodPost, server.srv.URL+chatToolPath+token, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + var out struct { + Result map[string]any `json:"result"` + } + _ = json.NewDecoder(response.Body).Decode(&out) + return out.Result + } + if result := call(`{"message":"check the run","after_minutes":30}`); result["isError"] != false { + t.Fatalf("schedule_followup = %v", result) + } + rows, err := store.ChatQueuedPrompts(context.Background(), "ses_1") + if err != nil || len(rows) != 1 || !strings.HasPrefix(rows[0].OperationID, chatFollowupPrefix) || rows[0].Client != chatFollowupClient || rows[0].SendAt.IsZero() || !strings.Contains(rows[0].Text, "check the run") { + t.Fatalf("stored follow-up = %+v %v", rows, err) + } + + conn := dialChatConn(t, server.ctx, server.srv) + if ack := sendPrompt(t, server.ctx, conn, "p1", "hello", "op-1"); ack.ChatQueued { + t.Fatalf("the operator's prompt waited behind a pending follow-up: %+v", ack) + } + waitFor(t, "operator prompt delivered", func() bool { return broker.promptCount() == 1 }) + endTurn(broker) + + call(`{"message":"two","after_minutes":60}`) + call(`{"message":"three","after_minutes":90}`) + if result := call(`{"message":"four","after_minutes":120}`); result["isError"] != true { + t.Fatalf("a fourth pending follow-up must be refused: %v", result) + } + writeChat(t, server.ctx, conn, protocol.Message{Type: protocol.ChatUnqueue, ID: "rm", ChatUnqueue: &protocol.ChatUnqueueRequest{SessionID: "ses_1", OperationID: rows[0].OperationID}}) + if removed := readUntil(t, server.ctx, conn, protocol.ChatUnqueue); removed.ChatQueue == nil || removed.ChatQueue.Removed != rows[0].OperationID || len(removed.ChatQueue.Prompts) != 2 { + t.Fatalf("the operator removes a follow-up: %+v", removed.ChatQueue) + } + if n := broker.promptCount(); n != 1 { + t.Fatalf("no follow-up is delivered before its time: %v", broker.promptTexts()) + } +} diff --git a/internal/server/chat_tools_items_test.go b/internal/server/chat_tools_items_test.go new file mode 100644 index 00000000..ac899ebc --- /dev/null +++ b/internal/server/chat_tools_items_test.go @@ -0,0 +1,224 @@ +package server + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func shownID(t *testing.T, r chattools.Result) string { + t.Helper() + _, rest, ok := strings.Cut(r.Text, "Item id: ") + if r.IsError || !ok { + t.Fatalf("the result names the item id: %v", r) + } + return strings.Fields(rest)[0] +} + +func TestUnknownOrMisnamedArgumentsAreRefused(t *testing.T) { + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_v") + for _, tc := range []struct{ tool, args, want string }{ + {"show_file", `{"file":"a.txt"}`, `unknown argument "file"; show_file takes path (required), replace, title`}, + {"show_html", `{"html":"

","heigth_hint":200}`, `unknown argument "heigth_hint"`}, + {"show_image", `{"path":"a.png"}`, "show_image takes url_or_path (required)"}, + {"show_run", `{"run_id":"7"}`, "run_id must be an integer"}, + {"notify", `{"title":"t","body":"m"}`, `unknown argument "body"`}, + } { + r := f.call(token, tc.tool, tc.args) + if !r.IsError || !strings.Contains(r.Text, tc.want) { + t.Errorf("%s %s: got %v, want %q", tc.tool, tc.args, r, tc.want) + } + } + if len(f.items(t, "ses_v")) != 0 || len(f.notified) != 0 { + t.Fatal("a refused call does nothing") + } +} + +func TestReplaceUpdatesAnItemInPlace(t *testing.T) { + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_p") + other := f.token(t, chatToolSessionScope+"ses_q") + first := shownID(t, f.call(token, "show_html", `{"html":"

v1

","title":"Chart"}`)) + shownID(t, f.call(token, "show_html", `{"html":"

later

"}`)) + created := f.items(t, "ses_p")[0].CreatedAt + f.service.now = func() time.Time { return time.UnixMilli(created + 5000) } + + r := f.call(token, "show_html", `{"html":"

v2

","title":"Chart","replace":"`+first+`"}`) + if r.IsError || !strings.Contains(r.Text, "Updated item "+first+" in place") { + t.Fatalf("replace: %v", r) + } + items := f.items(t, "ses_p") + if len(items) != 2 || items[0].ID != first || items[0].HTML != "

v2

" || items[0].CreatedAt != created || items[0].UpdatedAt != created+5000 { + t.Fatalf("the replaced item keeps its id and place: %+v", items) + } + for _, tc := range []struct{ token, tool, args, want string }{ + {token, "show_diff", `{"replace":"` + first + `"}`, "is a html item; show_diff can only replace diff"}, + {token, "show_html", `{"html":"x","replace":"shown_nope"}`, "is not an item shown in this chat"}, + {other, "show_html", `{"html":"x","replace":"` + first + `"}`, "is not an item shown in this chat"}, + } { + if r := f.call(tc.token, tc.tool, tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) { + t.Errorf("%s: got %v, want %q", tc.args, r, tc.want) + } + } + if len(f.items(t, "ses_q")) != 0 { + t.Fatal("another chat's item cannot be replaced") + } +} + +func TestShownFilesAreSnapshotsOrTrackedForChanges(t *testing.T) { + f := newChatToolFixture(t) + token := f.token(t, chatToolSessionScope+"ses_n") + small := filepath.Join(f.home, "small.txt") + large := filepath.Join(f.home, "large.log") + gone := filepath.Join(f.home, "gone.log") + write := func(path string, size int, fill byte) { + t.Helper() + if err := os.WriteFile(path, []byte(strings.Repeat(string(fill), size)), 0o600); err != nil { + t.Fatal(err) + } + } + write(small, 10, 'a') + write(large, chattools.MaxSnapshotBytes+1, 'b') + write(gone, chattools.MaxSnapshotBytes+1, 'c') + smallID := shownID(t, f.call(token, "show_file", `{"path":"`+small+`"}`)) + shownID(t, f.call(token, "show_file", `{"path":"`+large+`"}`)) + shownID(t, f.call(token, "show_file", `{"path":"`+gone+`"}`)) + items := f.items(t, "ses_n") + if !items[0].Snapshot || items[1].Snapshot || items[1].SHA256 == "" || items[1].ModTime == 0 { + t.Fatalf("small files are copied, large ones tracked: %+v", items) + } + + write(small, 12, 'z') + later := time.Now().Add(time.Minute) + write(large, chattools.MaxSnapshotBytes+1, 'B') + if err := os.Chtimes(large, later, later); err != nil { + t.Fatal(err) + } + if err := os.Remove(gone); err != nil { + t.Fatal(err) + } + frame := f.hub.shownFrame("ses_n") + if frame == nil || len(frame.Items) != 3 { + t.Fatalf("frame = %+v", frame) + } + if got := []string{frame.Items[0].State, frame.Items[1].State, frame.Items[2].State}; got[0] != "" || got[1] != protocol.ChatShownFileChanged || got[2] != protocol.ChatShownFileMissing { + t.Fatalf("states = %q (the snapshot still shows what was shown)", got) + } + if data, _ := os.ReadFile(frame.Items[0].Path); string(data) != strings.Repeat("a", 10) { + t.Fatalf("the snapshot keeps the shown version: %q", data) + } + + // Replacing a snapshot item copies the new version; the old copy is swept + // once it is past the grace period. + oldDir := filepath.Dir(items[0].Path) + f.service.now = func() time.Time { return time.Now().Add(2 * shownSnapshotGrace) } + if r := f.call(token, "show_file", `{"path":"`+small+`","replace":"`+smallID+`"}`); r.IsError { + t.Fatal(r.Text) + } + replaced := f.items(t, "ses_n")[0] + if data, _ := os.ReadFile(replaced.Path); replaced.ID != smallID || string(data) != strings.Repeat("z", 12) { + t.Fatalf("replaced snapshot = %+v %q", replaced, data) + } + if _, err := os.Stat(oldDir); !os.IsNotExist(err) { + t.Fatalf("the replaced snapshot is swept: %v", err) + } +} + +type fakeShownRuns map[int64]protocol.RunSummary + +func (f fakeShownRuns) RunSummaryByID(_ context.Context, id int64) (protocol.RunSummary, bool, error) { + run, ok := f[id] + return run, ok, nil +} + +func TestShowRunFollowsTheRun(t *testing.T) { + previous := shownRunRefreshDelay + shownRunRefreshDelay = 10 * time.Millisecond + t.Cleanup(func() { shownRunRefreshDelay = previous }) + f := newChatToolFixture(t) + runs := fakeShownRuns{7: {ID: 7, Name: "feature", Title: "Add the run card", Status: "running", CurrentStage: "implement", CreatedAt: "2026-12-01T10:00:00Z"}} + f.service.runs = runs + token := f.token(t, chatToolSessionScope+"ses_r") + if r := f.call(token, "show_run", `{"run_id":99}`); !r.IsError || !strings.Contains(r.Text, "there is no run 99") { + t.Fatalf("an unknown run is refused: %v", r) + } + r := f.call(token, "show_run", `{"run_id":7}`) + if r.IsError || !strings.Contains(r.Text, "run 7 of feature, running at stage implement") { + t.Fatalf("show_run: %v", r) + } + item := f.items(t, "ses_r")[0] + if item.Kind != protocol.ChatShownRun || item.Run == nil || item.Run.Title != "Add the run card" || item.Run.StartedAt != time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC).UnixMilli() { + t.Fatalf("run item = %+v", item) + } + + runs[7] = protocol.RunSummary{ID: 7, Name: "feature", Title: "Add the run card", Status: "succeeded", Outcome: "done", CreatedAt: "2026-12-01T10:00:00Z", FinishedAt: "2026-12-01T10:30:00Z"} + f.service.observeRun(protocol.RunEventFrame{RunID: 7, Status: "succeeded"}) + deadline := time.Now().Add(5 * time.Second) + for { + item = f.items(t, "ses_r")[0] + if item.Run.Status == "succeeded" { + break + } + if time.Now().After(deadline) { + t.Fatalf("the run item was not updated: %+v", item.Run) + } + time.Sleep(10 * time.Millisecond) + } + if item.Run.FinishedAt == 0 || item.Run.Outcome != "done" { + t.Fatalf("finished run = %+v", item.Run) + } + f.service.watch.mu.Lock() + followed := len(f.service.watch.items[7]) + f.service.watch.mu.Unlock() + if followed != 0 { + t.Fatal("a finished run is no longer followed") + } +} + +func TestScheduleFollowupBounds(t *testing.T) { + f := newChatToolFixture(t) + now := time.Date(2026, 12, 2, 12, 0, 0, 0, time.UTC) + f.service.now = func() time.Time { return now } + token := f.token(t, chatToolSessionScope+"ses_b") + for _, tc := range []struct{ args, want string }{ + {`{"message":"check","after_minutes":0}`, "after_minutes must be between 1 and 10080"}, + {`{"message":"check","after_minutes":10081}`, "after_minutes must be between 1 and 10080"}, + {`{"message":"check","at":"2026-12-02T12:00:30Z"}`, "at least 1 minute from now"}, + {`{"message":"check","at":"2026-12-09T12:01:00Z"}`, "at most 7 days"}, + {`{"message":"check","at":"tomorrow"}`, "RFC 3339"}, + {`{"message":"check","at":"2026-12-02T13:00:00Z","after_minutes":5}`, "not both"}, + {`{"message":"check"}`, "give at"}, + {`{"message":" ","after_minutes":5}`, "message is empty"}, + {`{"message":"check","after_minutes":5}`, "not available on this server"}, + } { + if r := f.call(token, "schedule_followup", tc.args); !r.IsError || !strings.Contains(r.Text, tc.want) { + t.Errorf("%s: got %v, want %q", tc.args, r, tc.want) + } + } +} + +func TestFollowupsStepAsideUntilDue(t *testing.T) { + now := time.Now() + followup := &chatQueuedPrompt{operationID: chatFollowupPrefix + "a", sendAt: now.Add(time.Hour)} + operator := &chatQueuedPrompt{operationID: "op-1"} + scheduled := &chatQueuedPrompt{operationID: "op-2", sendAt: now.Add(time.Minute)} + if head, wait := chatQueueHead([]*chatQueuedPrompt{followup, operator}, now); head != 1 || wait != time.Hour { + t.Fatalf("a pending follow-up lets the operator's prompt through: %d %v", head, wait) + } + if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now); head != -1 { + t.Fatal("a queue of pending follow-ups has nothing to deliver") + } + if head, _ := chatQueueHead([]*chatQueuedPrompt{followup}, now.Add(2*time.Hour)); head != 0 { + t.Fatal("a due follow-up is delivered") + } + if head, _ := chatQueueHead([]*chatQueuedPrompt{scheduled, operator}, now); head != 0 { + t.Fatal("an operator's scheduled prompt still holds the queue (FIFO)") + } +} diff --git a/internal/server/chat_tools_run.go b/internal/server/chat_tools_run.go index 00ed2b09..9df28669 100644 --- a/internal/server/chat_tools_run.go +++ b/internal/server/chat_tools_run.go @@ -11,46 +11,48 @@ import ( "git.a-wan.net/alan/pipelines/internal/protocol" ) -// run executes one tool for sessionID. A non-nil item is recorded and shown; -// the result is the short text the model reads. -func (s *chatToolService) run(ctx context.Context, sessionID, tool string, arguments json.RawMessage) (*protocol.ChatShownItem, chattools.Result) { +// run executes one tool for sessionID, whose arguments already passed +// chattools.ValidateArguments. id is the shown item's id (a replaced item's +// own); a non-nil item is recorded and shown, and the result is the short +// text the model reads. +func (s *chatToolService) run(ctx context.Context, sessionID, tool, id string, arguments json.RawMessage) (*protocol.ChatShownItem, chattools.Result) { fail := func(format string, args ...any) (*protocol.ChatShownItem, chattools.Result) { return nil, chattools.Result{Text: fmt.Sprintf(format, args...), IsError: true} } - var in struct { - Path string `json:"path"` - URLOrPath string `json:"url_or_path"` - Title string `json:"title"` - Alt string `json:"alt"` - HTML string `json:"html"` - HeightHint int `json:"height_hint"` - Message string `json:"message"` - Priority string `json:"priority"` - Base string `json:"base"` - Committed bool `json:"committed_only"` - } - if err := json.Unmarshal(arguments, &in); err != nil { - return fail("The arguments must be a JSON object matching the %s schema: %v", tool, err) - } - title := boundedLine(in.Title, 200) + decode := func(into any) error { return json.Unmarshal(arguments, into) } switch tool { case chattools.ToolShowFile: + var in struct { + Path string `json:"path"` + Title string `json:"title"` + } + if err := decode(&in); err != nil { + return fail("Nothing was shown: %v", err) + } file, err := s.resolveShownFile(ctx, sessionID, in.Path) if err != nil { return fail("Nothing was shown: %v", err) } - item := file.item(protocol.ChatShownFile, title) - return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: %s (%s).", file.name, humanBytes(file.size))} + item := s.fileItem(sessionID, id, file, protocol.ChatShownFile, boundedLine(in.Title, 200)) + return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: %s (%s%s).", file.name, humanBytes(file.size), shownKeptNote(item))} case chattools.ToolShowImage: + var in struct { + URLOrPath string `json:"url_or_path"` + Title string `json:"title"` + Alt string `json:"alt"` + } + if err := decode(&in); err != nil { + return fail("Nothing was shown: %v", err) + } + title, alt := boundedLine(in.Title, 200), boundedLine(in.Alt, 500) source := strings.TrimSpace(in.URLOrPath) - alt := boundedLine(in.Alt, 500) if strings.Contains(source, "://") { - address, err := shownImageURL(source) + item, err := s.fetchShownImage(ctx, sessionID, id, source) if err != nil { return fail("Nothing was shown: %v", err) } - item := protocol.ChatShownItem{Kind: protocol.ChatShownImage, Title: title, URL: address, Alt: alt} - return &item, chattools.Result{Text: "Shown in the operator's Pipelines chat: the image at " + address + "."} + item.Title, item.Alt = title, alt + return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image at %s (%s, %s, downloaded by Pipelines).", item.URL, item.Mime, humanBytes(item.Size))} } file, err := s.resolveShownFile(ctx, sessionID, source) if err != nil { @@ -59,10 +61,18 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum if !strings.HasPrefix(file.mime, "image/") { return fail("Nothing was shown: %s is %s, not an image; use show_file for documents.", file.name, file.mime) } - item := file.item(protocol.ChatShownImage, title) + item := s.fileItem(sessionID, id, file, protocol.ChatShownImage, title) item.Alt = alt - return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image %s (%s).", file.name, humanBytes(file.size))} + return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat: the image %s (%s%s).", file.name, humanBytes(file.size), shownKeptNote(item))} case chattools.ToolShowHTML: + var in struct { + HTML string `json:"html"` + Title string `json:"title"` + HeightHint int `json:"height_hint"` + } + if err := decode(&in); err != nil { + return fail("Nothing was shown: %v", err) + } if strings.TrimSpace(in.HTML) == "" { return fail("Nothing was shown: html is empty.") } @@ -72,16 +82,62 @@ func (s *chatToolService) run(ctx context.Context, sessionID, tool string, argum if !utf8.ValidString(in.HTML) { return fail("Nothing was shown: html is not valid UTF-8.") } - item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: title, HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)} - return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled).", humanBytes(int64(len(in.HTML))))} + item := protocol.ChatShownItem{Kind: protocol.ChatShownHTML, Title: boundedLine(in.Title, 200), HTML: in.HTML, HTMLBytes: len(in.HTML), HeightHint: clampHeightHint(in.HeightHint)} + return &item, chattools.Result{Text: fmt.Sprintf("Shown in the operator's Pipelines chat (%s, sandboxed: scripts and network are disabled; it follows the operator's light or dark theme only if it styles itself for dark mode).", humanBytes(int64(len(in.HTML))))} case chattools.ToolShowDiff: - return s.runShowDiff(ctx, sessionID, showDiffRequest{Path: in.Path, Base: in.Base, CommittedOnly: in.Committed, Title: title}) + var in struct { + Path string `json:"path"` + Base string `json:"base"` + Head string `json:"head"` + Paths []string `json:"paths"` + Committed bool `json:"committed_only"` + Title string `json:"title"` + } + if err := decode(&in); err != nil { + return fail("Nothing was shown: %v", err) + } + return s.runShowDiff(ctx, sessionID, showDiffRequest{Path: in.Path, Base: in.Base, Head: in.Head, Paths: in.Paths, CommittedOnly: in.Committed, Title: boundedLine(in.Title, 200)}) + case chattools.ToolShowRun: + var in struct { + RunID int64 `json:"run_id"` + Title string `json:"title"` + } + if err := decode(&in); err != nil { + return fail("Nothing was shown: %v", err) + } + return s.runShowRun(ctx, in.RunID, boundedLine(in.Title, 200)) + case chattools.ToolScheduleFollowup: + var in struct { + Message string `json:"message"` + At string `json:"at"` + AfterMinutes *int64 `json:"after_minutes"` + } + if err := decode(&in); err != nil { + return fail("Nothing was scheduled: %v", err) + } + return nil, s.runScheduleFollowup(ctx, sessionID, in.Message, in.At, in.AfterMinutes) case chattools.ToolNotify: - return s.runNotify(ctx, sessionID, title, in.Message, in.Priority) + var in struct { + Title string `json:"title"` + Message string `json:"message"` + Priority string `json:"priority"` + } + if err := decode(&in); err != nil { + return fail("Not sent: %v", err) + } + return s.runNotify(ctx, sessionID, boundedLine(in.Title, 200), in.Message, in.Priority) } return fail("Unknown tool %s.", tool) } +// shownKeptNote says how a shown file is kept: a copy, or the live file. +func shownKeptNote(item protocol.ChatShownItem) string { + if item.Snapshot { + return "; Pipelines keeps a copy of this version" + } + return "; shown from the live file, so the card notes later changes" +} + func (s *chatToolService) runNotify(ctx context.Context, sessionID, title, message, priority string) (*protocol.ChatShownItem, chattools.Result) { message = boundedLine(message, 2000) if title == "" || message == "" { diff --git a/internal/server/chat_tools_runs.go b/internal/server/chat_tools_runs.go new file mode 100644 index 00000000..32a12b06 --- /dev/null +++ b/internal/server/chat_tools_runs.go @@ -0,0 +1,175 @@ +package server + +import ( + "context" + "fmt" + "log" + "sync" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// show_run records a card that follows one run. Its body is the run's summary +// when shown; the run event hub tells the service when a followed run changes +// (observeRun), and the service rereads the run, stores the new body over the +// item and pushes it to the chat. A subscribe reply rereads every followed +// run too, so a card is current after a restart that lost the watches. + +// shownRunRefreshDelay coalesces a run's bursts of events into one reread. +var shownRunRefreshDelay = 400 * time.Millisecond + +// runWatches maps a followed run to the items (id to session) showing it. +type runWatches struct { + mu sync.Mutex + items map[int64]map[string]string + timers map[int64]*time.Timer +} + +func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title string) (*protocol.ChatShownItem, chattools.Result) { + fail := func(text string) (*protocol.ChatShownItem, chattools.Result) { + return nil, chattools.Result{Text: "Nothing was shown: " + text, IsError: true} + } + if runID <= 0 { + return fail("run_id must be a positive run number.") + } + if s.runs == nil { + return fail("this server does not record runs.") + } + summary, found, err := s.runs.RunSummaryByID(ctx, runID) + if err != nil { + return fail(err.Error()) + } + if !found { + return fail(fmt.Sprintf("there is no run %d.", runID)) + } + body := shownRunBody(summary) + item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body} + text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status) + if body.CurrentStage != "" && !shownRunTerminal(body.Status) { + text += " at stage " + body.CurrentStage + } + return &item, chattools.Result{Text: text + "; the card follows the run live."} +} + +func shownRunBody(summary protocol.RunSummary) protocol.ChatShownRunBody { + return protocol.ChatShownRunBody{ + ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome, + CurrentStage: summary.CurrentStage, Workspace: summary.Workspace, + StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt), + } +} + +func shownRunTime(value string) int64 { + for _, layout := range []string{time.RFC3339, "2006-01-02 15:04:05"} { + if parsed, err := time.Parse(layout, value); err == nil { + return parsed.UnixMilli() + } + } + return 0 +} + +func shownRunTerminal(status string) bool { + switch status { + case "succeeded", "failed", "canceled", "interrupted": + return true + } + return false +} + +// watchRun follows runID for the item. +func (s *chatToolService) watchRun(runID int64, sessionID, itemID string) { + w := &s.watch + w.mu.Lock() + defer w.mu.Unlock() + if w.items == nil { + w.items = map[int64]map[string]string{} + } + if w.items[runID] == nil { + w.items[runID] = map[string]string{} + } + w.items[runID][itemID] = sessionID +} + +// observeRun is the run event hub's observer: a followed run's change is +// reread once its burst of events settles. +func (s *chatToolService) observeRun(frame protocol.RunEventFrame) { + w := &s.watch + w.mu.Lock() + defer w.mu.Unlock() + if len(w.items[frame.RunID]) == 0 { + return + } + if w.timers == nil { + w.timers = map[int64]*time.Timer{} + } + if w.timers[frame.RunID] != nil { + return + } + runID := frame.RunID + w.timers[runID] = time.AfterFunc(shownRunRefreshDelay, func() { + w.mu.Lock() + delete(w.timers, runID) + followers := make(map[string]string, len(w.items[runID])) + for id, session := range w.items[runID] { + followers[id] = session + } + w.mu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for itemID, sessionID := range followers { + if s.shown == nil { + return + } + item, found, err := s.shown.ChatShownItem(ctx, sessionID, itemID) + if err != nil || !found || item.Run == nil { + s.unwatchRun(runID, itemID) + continue + } + s.refreshRunItem(ctx, sessionID, item, true) + } + }) +} + +func (s *chatToolService) unwatchRun(runID int64, itemID string) { + s.watch.mu.Lock() + defer s.watch.mu.Unlock() + delete(s.watch.items[runID], itemID) + if len(s.watch.items[runID]) == 0 { + delete(s.watch.items, runID) + } +} + +// refreshRunItem rereads a run item's run; a changed body is stored and pushed +// to the chat. A finished run is no longer followed. +func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string, item protocol.ChatShownItem, push bool) protocol.ChatShownItem { + if item.Run == nil || s.runs == nil { + return item + } + summary, found, err := s.runs.RunSummaryByID(ctx, item.Run.ID) + if err != nil || !found { + return item + } + body := shownRunBody(summary) + if shownRunTerminal(body.Status) { + s.unwatchRun(body.ID, item.ID) + } else { + s.watchRun(body.ID, sessionID, item.ID) + } + if body == *item.Run { + return item + } + item.Run = &body + if s.shown != nil { + if _, err := s.shown.ReplaceChatShownItem(ctx, sessionID, item); err != nil { + log.Printf("chat tools session=%s: update run item %s: %v", sessionID, item.ID, err) + return item + } + } + if push && s.hub != nil { + s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown, + ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{item}}}, "") + } + return item +} diff --git a/internal/server/chat_tools_service.go b/internal/server/chat_tools_service.go index ee78eb42..f4746d3e 100644 --- a/internal/server/chat_tools_service.go +++ b/internal/server/chat_tools_service.go @@ -5,8 +5,11 @@ import ( "crypto/rand" "encoding/hex" "encoding/json" + "errors" + "fmt" "log" "net/http" + "slices" "strings" "sync" "time" @@ -19,6 +22,13 @@ import ( type chatShownStore interface { AppendChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) error ChatShownItems(ctx context.Context, sessionID string) ([]protocol.ChatShownItem, error) + ChatShownItem(ctx context.Context, sessionID, id string) (protocol.ChatShownItem, bool, error) + ReplaceChatShownItem(ctx context.Context, sessionID string, item protocol.ChatShownItem) (bool, error) +} + +// chatShownRunStore reads the runs show_run follows (pipeline.Store). +type chatShownRunStore interface { + RunSummaryByID(ctx context.Context, id int64) (protocol.RunSummary, bool, error) } // chatToolCorrelationWait is how long a call on a shared (instance) endpoint @@ -37,11 +47,25 @@ type chatToolService struct { notify chatToolNotifier limiter *chatNotifyLimiter now func() time.Time + // runs reads the runs show_run follows; broker delivers follow-ups. + runs chatShownRunStore + broker chatBroker + // snapshotRoot is where shown files are copied; it must lie inside the + // operator's home, where /files serves it. + snapshotRoot func() (string, error) + // fetch is how web images are downloaded (tests replace its guard). + fetch shownImageFetcher + watch runWatches } func newChatToolService(tokens chatToolTokenStore, shown chatShownStore, hub *chatHub, registry operatorRegistry) *chatToolService { - return &chatToolService{tokens: tokens, shown: shown, hub: hub, registry: registry, home: OperatorHomeDirectory, - notify: hub.publishToolNotification, limiter: newChatNotifyLimiter(5, time.Minute), now: time.Now} + s := &chatToolService{tokens: tokens, shown: shown, hub: hub, registry: registry, home: OperatorHomeDirectory, + notify: hub.publishToolNotification, limiter: newChatNotifyLimiter(5, time.Minute), now: time.Now, + snapshotRoot: defaultSnapshotRoot, fetch: shownImageFetcher{allowed: publicAddress}} + if hub != nil { + hub.shownRefresh = s.refreshShown + } + return s } // registerChatTools serves the MCP endpoint on mux. The route exists only on @@ -67,27 +91,93 @@ func (s *chatToolService) Call(ctx context.Context, token, tool string, argument if refusal != "" { return chattools.Result{Text: refusal, IsError: true} } - item, result := s.run(ctx, sessionID, tool, arguments) + if err := chattools.ValidateArguments(tool, arguments); err != nil { + return chattools.Result{Text: "Nothing was done: " + err.Error() + ".", IsError: true} + } + var common struct { + Replace string `json:"replace"` + } + _ = json.Unmarshal(arguments, &common) + id := newChatShownID() + var previous *protocol.ChatShownItem + if replace := strings.TrimSpace(common.Replace); replace != "" { + target, err := s.replaceTarget(ctx, sessionID, tool, replace) + if err != nil { + return chattools.Result{Text: "Nothing was shown: " + err.Error(), IsError: true} + } + previous, id = &target, target.ID + } + item, result := s.run(ctx, sessionID, tool, id, arguments) if item == nil { return result } if item.ID == "" { - item.ID = newChatShownID() + item.ID = id + } + now := s.now().UnixMilli() + item.CreatedAt = now + if previous != nil { + item.CreatedAt, item.UpdatedAt = previous.CreatedAt, now } - item.CreatedAt = s.now().UnixMilli() if s.shown != nil { - if err := s.shown.AppendChatShownItem(ctx, sessionID, *item); err != nil { + var err error + if previous != nil { + var found bool + if found, err = s.shown.ReplaceChatShownItem(ctx, sessionID, *item); err == nil && !found { + err = errors.New("the item to replace is no longer retained") + } + } else { + err = s.shown.AppendChatShownItem(ctx, sessionID, *item) + } + if err != nil { log.Printf("chat tools session=%s: record %s: %v", sessionID, tool, err) return chattools.Result{Text: "Pipelines could not record this item: " + err.Error(), IsError: true} } + s.sweepSnapshots(ctx, sessionID) + } + if item.Run != nil { + s.watchRun(item.Run.ID, sessionID, item.ID) } if s.hub != nil { s.hub.fanout(sessionID, protocol.Message{Type: protocol.ChatShown, ChatShown: &protocol.ChatShownFrame{SessionID: sessionID, Items: []protocol.ChatShownItem{*item}}}, "") } + if tool != chattools.ToolNotify { + if previous != nil { + result.Text += " Updated item " + item.ID + " in place." + } else { + result.Text += " Item id: " + item.ID + " (pass it as replace to update this card)." + } + } return result } +// replaceTarget is the item a replace id names: one this chat's model showed, +// of a kind the tool can update. +func (s *chatToolService) replaceTarget(ctx context.Context, sessionID, tool, id string) (protocol.ChatShownItem, error) { + if s.shown == nil { + return protocol.ChatShownItem{}, errors.New("items cannot be replaced on this server") + } + item, found, err := s.shown.ChatShownItem(ctx, sessionID, id) + if err != nil { + return protocol.ChatShownItem{}, err + } + if !found { + return protocol.ChatShownItem{}, fmt.Errorf("replace %q is not an item shown in this chat (use the id from an earlier show_* result here)", id) + } + kinds := map[string][]string{ + chattools.ToolShowFile: {protocol.ChatShownFile, protocol.ChatShownImage}, + chattools.ToolShowImage: {protocol.ChatShownFile, protocol.ChatShownImage}, + chattools.ToolShowHTML: {protocol.ChatShownHTML}, + chattools.ToolShowDiff: {protocol.ChatShownDiff}, + chattools.ToolShowRun: {protocol.ChatShownRun}, + }[tool] + if !slices.Contains(kinds, item.Kind) { + return protocol.ChatShownItem{}, fmt.Errorf("replace %q is a %s item; %s can only replace %s", id, item.Kind, tool, strings.Join(kinds, " or ")) + } + return item, nil +} + // session resolves the chat a call belongs to. A session token names it; a // shared harness instance token is attributed to the one chat whose stream // shows this exact call running, and refused when none or several do. @@ -188,5 +278,8 @@ func (h *chatHub) shownFrame(sessionID string) *protocol.ChatShownFrame { if len(items) == 0 { return nil } + if h.shownRefresh != nil { + items = h.shownRefresh(ctx, sessionID, items) + } return &protocol.ChatShownFrame{SessionID: sessionID, Items: items} } diff --git a/internal/server/chat_tools_snapshot.go b/internal/server/chat_tools_snapshot.go new file mode 100644 index 00000000..8324eca1 --- /dev/null +++ b/internal/server/chat_tools_snapshot.go @@ -0,0 +1,235 @@ +package server + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strings" + "time" + + "git.a-wan.net/alan/pipelines/internal/chattools" + "git.a-wan.net/alan/pipelines/internal/paths" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A shown file up to chattools.MaxSnapshotBytes is copied into the chat's +// snapshot directory (//-/) when it is +// shown, so the card keeps showing that version however the file changes +// later. The copy lives inside the operator's home, so the /files endpoint +// serves it like any other file. A larger file stays linked: the item records +// its size, modification time and hash, and the subscribe reply says when it +// changed or no longer exists. + +// shownHashLimit bounds the live files whose content hash is recorded and +// rechecked; a larger one is compared by size and modification time alone. +const shownHashLimit = 64 << 20 + +// shownSnapshotGrace keeps an unreferenced snapshot directory this long, so a +// copy taken for an item that is being recorded is never swept. +const shownSnapshotGrace = time.Minute + +func defaultSnapshotRoot() (string, error) { + data, err := paths.Data() + if err != nil { + return "", err + } + return filepath.Join(data, "chat-shown"), nil +} + +// fileItem records file as a shown item: a snapshot copy when it is small +// enough and the copy succeeds, else the live file with what identifies it. +func (s *chatToolService) fileItem(sessionID, id string, file shownFile, kind, title string) protocol.ChatShownItem { + item := protocol.ChatShownItem{Kind: kind, Title: title, Path: file.path, Name: file.name, Size: file.size, Mime: file.mime} + if file.size <= chattools.MaxSnapshotBytes { + source, err := os.Open(file.path) + if err == nil { + path, size, copyErr := s.writeSnapshot(sessionID, id, file.name, io.LimitReader(source, chattools.MaxSnapshotBytes+1)) + source.Close() + if copyErr == nil { + item.Path, item.Size, item.Snapshot, item.Source = path, size, true, file.path + return item + } + err = copyErr + } + log.Printf("chat tools session=%s: snapshot %s: %v; showing the live file", sessionID, file.path, err) + } + if info, err := os.Stat(file.path); err == nil { + item.ModTime = info.ModTime().UnixMilli() + } + if file.size <= shownHashLimit { + item.SHA256, _ = fileSHA256(file.path) + } + return item +} + +// writeSnapshot stores content as a new snapshot of item id and returns its +// path and size. It refuses content over the snapshot bound and a root that +// is not inside the operator's home. +func (s *chatToolService) writeSnapshot(sessionID, id, name string, content io.Reader) (string, int64, error) { + if sessionID == "" || filepath.Base(sessionID) != sessionID || filepath.Base(id) != id || id == "" { + return "", 0, errors.New("invalid snapshot owner") + } + if s.snapshotRoot == nil { + return "", 0, errors.New("no snapshot directory") + } + root, err := s.snapshotRoot() + if err != nil { + return "", 0, err + } + var nonce [4]byte + _, _ = rand.Read(nonce[:]) + dir := filepath.Join(root, sessionID, id+"-"+hex.EncodeToString(nonce[:])) + if err := os.MkdirAll(dir, 0o700); err != nil { + return "", 0, err + } + if err := s.insideHome(dir); err != nil { + _ = os.RemoveAll(dir) + return "", 0, err + } + path := filepath.Join(dir, safeSnapshotName(name)) + out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + _ = os.RemoveAll(dir) + return "", 0, err + } + size, err := io.Copy(out, content) + if err == nil && size > chattools.MaxSnapshotBytes { + err = fmt.Errorf("the file grew past %s while it was copied", humanBytes(chattools.MaxSnapshotBytes)) + } + if closeErr := out.Close(); err == nil { + err = closeErr + } + if err != nil { + _ = os.RemoveAll(dir) + return "", 0, err + } + return path, size, nil +} + +// insideHome refuses a directory /files would not serve. +func (s *chatToolService) insideHome(dir string) error { + home, err := s.home() + if err != nil { + return err + } + realHome, err := filepath.EvalSymlinks(filepath.Clean(home)) + if err != nil { + return err + } + if _, _, err := resolveInsideHome(realHome, dir); err != nil { + return errors.New("the snapshot directory " + dir + " is not inside the operator's home") + } + return nil +} + +func safeSnapshotName(name string) string { + name = strings.Map(func(r rune) rune { + if r == '/' || r == '\\' || r < 0x20 || r == 0x7f { + return '_' + } + return r + }, strings.TrimSpace(name)) + if name == "" || name == "." || name == ".." { + return "file" + } + return truncateUTF8(name, 200) +} + +func fileSHA256(path string) (string, error) { + file, err := os.Open(path) + if err != nil { + return "", err + } + defer file.Close() + digest := sha256.New() + if _, err := io.Copy(digest, io.LimitReader(file, shownHashLimit+1)); err != nil { + return "", err + } + return hex.EncodeToString(digest.Sum(nil)), nil +} + +// sweepSnapshots removes a chat's snapshot directories that no retained item +// references any more (pruned by the item limit, or replaced). +func (s *chatToolService) sweepSnapshots(ctx context.Context, sessionID string) { + if s.snapshotRoot == nil || s.shown == nil || filepath.Base(sessionID) != sessionID { + return + } + root, err := s.snapshotRoot() + if err != nil { + return + } + dir := filepath.Join(root, sessionID) + entries, err := os.ReadDir(dir) + if err != nil { + return + } + items, err := s.shown.ChatShownItems(ctx, sessionID) + if err != nil { + return + } + kept := map[string]bool{} + for _, item := range items { + if item.Snapshot && item.Path != "" { + kept[filepath.Dir(item.Path)] = true + } + } + for _, entry := range entries { + path := filepath.Join(dir, entry.Name()) + info, err := entry.Info() + if err != nil || kept[path] || s.now().Sub(info.ModTime()) < shownSnapshotGrace { + continue + } + if err := os.RemoveAll(path); err != nil { + log.Printf("chat tools session=%s: remove snapshot %s: %v", sessionID, path, err) + } + } +} + +// shownFileState says whether a file item's file still shows what was shown: +// missing when it (or its snapshot) is gone, changed when the live file's +// size, or modification time and content, differ. +func shownFileState(item protocol.ChatShownItem) string { + if item.Path == "" || (item.Kind != protocol.ChatShownFile && item.Kind != protocol.ChatShownImage) { + return "" + } + info, err := os.Stat(item.Path) + if err != nil || !info.Mode().IsRegular() { + return protocol.ChatShownFileMissing + } + if item.Snapshot { + return "" + } + if info.Size() != item.Size { + return protocol.ChatShownFileChanged + } + if item.ModTime == 0 || info.ModTime().UnixMilli() == item.ModTime { + return "" + } + if item.SHA256 != "" && info.Size() <= shownHashLimit { + if digest, err := fileSHA256(item.Path); err == nil && digest == item.SHA256 { + return "" + } + } + return protocol.ChatShownFileChanged +} + +// refreshShown brings a chat's listed items up to date for its subscribe +// reply: each file's state, and each followed run's latest summary. +func (s *chatToolService) refreshShown(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem { + out := make([]protocol.ChatShownItem, len(items)) + for i, item := range items { + item.State = shownFileState(item) + if item.Run != nil { + item = s.refreshRunItem(ctx, sessionID, item, false) + } + out[i] = item + } + return out +} diff --git a/internal/server/chat_tools_test.go b/internal/server/chat_tools_test.go index 81881dfb..b8deb0ab 100644 --- a/internal/server/chat_tools_test.go +++ b/internal/server/chat_tools_test.go @@ -33,6 +33,9 @@ func newChatToolFixture(t *testing.T) *chatToolFixture { f.hub.shown = store f.service = newChatToolService(store, store, f.hub, store) f.service.home = func() (string, error) { return f.home, nil } + f.service.snapshotRoot = func() (string, error) { + return filepath.Join(f.home, ".local", "share", "pipelines", "chat-shown"), nil + } f.service.notify = func(_ context.Context, sessionID string, notice chatToolNotice) chatToolDelivery { f.notified = append(f.notified, sessionID+": "+notice.Title) return chatToolDelivery{App: true, Phone: true} @@ -135,9 +138,12 @@ func TestShowFileStaysInsideHome(t *testing.T) { } realHome, _ := filepath.EvalSymlinks(f.home) got := f.items(t, "ses_f") - if len(got) != 1 || got[0].Path != filepath.Join(realHome, "work", "report.md") || got[0].Name != "report.md" || got[0].Size != 9 || !strings.HasPrefix(got[0].Mime, "text/") { + if len(got) != 1 || got[0].Source != filepath.Join(realHome, "work", "report.md") || !got[0].Snapshot || got[0].Name != "report.md" || got[0].Size != 9 || !strings.HasPrefix(got[0].Mime, "text/") { t.Fatalf("item = %+v", got) } + if copied, err := os.ReadFile(got[0].Path); err != nil || string(copied) != "# Report\n" || !strings.HasPrefix(got[0].Path, f.home) { + t.Fatalf("the snapshot %s inside home holds the shown content: %q %v", got[0].Path, copied, err) + } if r := f.call(token, "show_file", `{"path":"report.md"}`); r.IsError { t.Fatalf("a relative path resolves against the chat's directory: %v", r) } @@ -167,7 +173,8 @@ func TestShowImageAcceptsHomeImagesAndHTTPSOnly(t *testing.T) { if r := f.call(token, "show_image", `{"url_or_path":"`+image+`","alt":"A plot"}`); r.IsError { t.Fatal(r.Text) } - if r := f.call(token, "show_image", `{"url_or_path":"https://example.com/a.png","title":"Remote"}`); r.IsError { + web := f.imageServer(t) + if r := f.call(token, "show_image", `{"url_or_path":"`+web.URL+`/a.png","title":"Remote"}`); r.IsError { t.Fatal(r.Text) } for _, refused := range []string{"http://example.com/a.png", "https://user:pw@example.com/a.png", "javascript:alert(1)", "file:///etc/passwd", filepath.Join(f.home, "notes.txt")} { @@ -176,9 +183,12 @@ func TestShowImageAcceptsHomeImagesAndHTTPSOnly(t *testing.T) { } } got := f.items(t, "ses_i") - if len(got) != 2 || got[0].Kind != protocol.ChatShownImage || got[0].Mime != "image/png" || got[0].Alt != "A plot" || got[1].URL != "https://example.com/a.png" || got[1].Path != "" { + if len(got) != 2 || got[0].Kind != protocol.ChatShownImage || got[0].Mime != "image/png" || got[0].Alt != "A plot" || got[1].URL != web.URL+"/a.png" || !got[1].Snapshot || got[1].Name != "a.png" || got[1].Mime != "image/png" { t.Fatalf("items = %+v", got) } + if data, err := os.ReadFile(got[1].Path); err != nil || string(data) != string(testPNG) { + t.Fatalf("the fetched image is kept as a snapshot: %v", err) + } } func TestShowHTMLSizeLimitAndRetention(t *testing.T) { diff --git a/internal/server/runevents.go b/internal/server/runevents.go index 92fbd5f0..ddf8bfd8 100644 --- a/internal/server/runevents.go +++ b/internal/server/runevents.go @@ -40,6 +40,19 @@ type runEventHub struct { runs map[int64]*runCoalescer now func() time.Time interval time.Duration + // observer sees every emitted delta, subscribed or not (the chat tools' + // run cards follow runs through it). It must not block. + observer func(protocol.RunEventFrame) +} + +// observe installs the delta observer. +func (h *runEventHub) observe(observer func(protocol.RunEventFrame)) { + if h == nil { + return + } + h.mu.Lock() + h.observer = observer + h.mu.Unlock() } // runCoalescer merges a run's rapid field updates into the latest pending delta @@ -180,6 +193,11 @@ func (h *runEventHub) emit(frame protocol.RunEventFrame, terminal bool) { return } h.mu.Lock() + if observer := h.observer; observer != nil { + h.mu.Unlock() + observer(frame) + h.mu.Lock() + } if !h.anySubscriberLocked(frame.Workspace) { h.mu.Unlock() return diff --git a/internal/server/websocket.go b/internal/server/websocket.go index 19ae6388..b44124b5 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -187,7 +187,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin if len(stores) > 0 { // The Pipelines chat tools' MCP endpoint, for harnesses on this machine. hub.shown = stores[0] - registerChatTools(mux, newChatToolService(stores[0], stores[0], hub, registry), build.Version) + tools := newChatToolService(stores[0], stores[0], hub, registry) + tools.runs = stores[0] + tools.broker = options.Chat + events.observe(tools.observeRun) + registerChatTools(mux, tools, build.Version) } mux.HandleFunc("GET /discovery", serveServerDiscovery) mux.HandleFunc("GET /files", serveHomeFile)