feat(studio): typed flow outputs + on-disk docs + UX polish

Documentation system (the original "whole docs system is broken"
complaint):
- Studio reads inline docs from disk via the new
  getInstalledModuleDocs RPC. No network, no auth, no provider
  lock-in.
- store.dart probes for MODULE.md eagerly when a module-detail
  sheet opens (a single file stat). The Documentation section
  only renders when the bundle actually shipped docs.
- Shared FaiTheme.markdownStyle helper used by Welcome's
  DocReaderSheet and Store's DocsPanel so every inline doc
  reads in the same typography. The shared style forces
  code.backgroundColor = transparent to suppress the per-span
  bands flutter_markdown's default code style draws on dark
  themes.

Flow run dialog:
- Run-button gating now strips the @version suffix from
  installed capabilities before the contains() check. Without
  this fix the button stayed disabled for every flow with
  dependencies, even after a successful install.
- Studio derives a MIME type from the picked file's extension
  (small per-suffix map; .pdf, .docx, .txt, .json, ...) and
  forwards it to the hub. Fixes "unsupported MIME type:
  application/octet-stream" from text.extract.
- Dialog title tracks the future's state: running -> "extract
  laeuft", success -> "extract -- Ergebnis", failure ->
  "extract -- fehlgeschlagen".
- Output rendering moved from String stringification to a
  sealed FlowOutput type (Text / Json / Bytes / File / Unknown).
  A new FaiFlowOutput widget dispatches per variant: markdown
  for text/markdown (heuristic), pretty JSON for proto Struct,
  inline image preview + Save-As for bytes, Open for file URIs.

Byte sizes:
- New humanBytes() helper renders 23.3 kB / 1.04 MB style values
  with three significant digits, matching Finder / GNOME Files.
  Wired into flow-card pills, picked-file readouts, and the
  bytes-payload preview line.

Signed-off-by: flemming-it <sf@flemming.it>
Signed-off-by: flemming-it <stefan.a.flemming@googlemail.com>
This commit is contained in:
flemming-it 2026-05-25 11:17:58 +02:00
parent 081ffd7233
commit 34f2b7b313
14 changed files with 849 additions and 296 deletions

85
lib/data/flow_output.dart Normal file
View file

@ -0,0 +1,85 @@
// FlowOutput typed representation of one entry in
// `SubmitResponse.outputs`. Lets Studio render text vs. JSON vs.
// bytes vs. file with the right widget instead of stringifying
// everything into `<bytes: >` placeholders.
import 'dart:convert';
import 'dart:typed_data';
import 'package:fai_dart_sdk/fai_dart_sdk.dart' show Payload;
/// One named output of a flow run. Sealed via factory constructors
/// callers pattern-match with `switch` on the runtime type to
/// pick a renderer. Variants:
///
/// - [FlowOutputText] : plain text. `mimeType` may be set
/// (e.g. `text/markdown`) so the
/// renderer can pick a Markdown widget.
/// - [FlowOutputJson] : a proto Struct, already pretty-
/// printed as JSON so the UI can render
/// it directly.
/// - [FlowOutputBytes] : raw bytes + MIME. The renderer
/// decides whether to inline a preview
/// (e.g. images) and exposes a
/// Save-As affordance otherwise.
/// - [FlowOutputFile] : a URI the host already wrote to. The
/// renderer offers an Open action.
/// - [FlowOutputUnknown] : oneof was empty / unset. Never
/// expected in practice but kept so
/// the UI never panics on a future
/// schema bump.
sealed class FlowOutput {
const FlowOutput();
factory FlowOutput.fromPayload(Payload p) {
if (p.hasText()) {
return FlowOutputText(text: p.text);
}
if (p.hasJson()) {
// proto Struct toProto3Json gives a Dart-side
// Map/List/primitive tree. We re-encode with an indent so
// the UI can show the operator-friendly form directly.
final tree = p.json.toProto3Json();
const encoder = JsonEncoder.withIndent(' ');
return FlowOutputJson(pretty: encoder.convert(tree));
}
if (p.hasBytes()) {
return FlowOutputBytes(
bytes: Uint8List.fromList(p.bytes.data),
mimeType: p.bytes.mimeType,
);
}
if (p.hasFile()) {
return FlowOutputFile(uri: p.file.uri, mimeType: p.file.mimeType);
}
return const FlowOutputUnknown();
}
}
class FlowOutputText extends FlowOutput {
final String text;
const FlowOutputText({required this.text});
}
class FlowOutputJson extends FlowOutput {
/// Already indented JSON, ready for SelectableText / Markdown
/// code-block rendering.
final String pretty;
const FlowOutputJson({required this.pretty});
}
class FlowOutputBytes extends FlowOutput {
final Uint8List bytes;
final String mimeType;
const FlowOutputBytes({required this.bytes, required this.mimeType});
}
class FlowOutputFile extends FlowOutput {
final String uri;
final String mimeType;
const FlowOutputFile({required this.uri, required this.mimeType});
}
class FlowOutputUnknown extends FlowOutput {
const FlowOutputUnknown();
}

33
lib/data/format.dart Normal file
View file

@ -0,0 +1,33 @@
// Display-only formatters shared across pages. Pure functions,
// no I/O, no locale fall-through locale-specific labels (the
// unit word itself, e.g. "Bytes" vs. "bytes") stay in `.arb`;
// these helpers only handle the numeric formatting.
/// Render a byte count with an SI suffix that stays at three
/// significant digits ("23.3 kB", "1.04 MB", "847 B"). Uses 1000
/// as the base, not 1024 matches macOS Finder / GNOME Files
/// and is what most operators expect when they read "kB".
///
/// Returns plain `n B` for values under 1000 so small flows
/// and tiny inputs stay precise instead of becoming "0.5 kB".
String humanBytes(int bytes) {
if (bytes < 1000) return '$bytes B';
const units = ['kB', 'MB', 'GB', 'TB', 'PB'];
var v = bytes.toDouble() / 1000.0;
var unitIndex = 0;
while (v >= 1000 && unitIndex < units.length - 1) {
v /= 1000.0;
unitIndex++;
}
// Pick decimals so the rendered number stays at 3 significant
// figures: 9.99 / 99.9 / 999 same approach Finder uses.
final String formatted;
if (v >= 100) {
formatted = v.toStringAsFixed(0);
} else if (v >= 10) {
formatted = v.toStringAsFixed(1);
} else {
formatted = v.toStringAsFixed(2);
}
return '$formatted ${units[unitIndex]}';
}

View file

@ -11,6 +11,9 @@ import 'package:fai_dart_sdk/fai_dart_sdk.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'flow_output.dart';
export 'flow_output.dart';
class HubService {
HubService._();
static final HubService instance = HubService._();
@ -346,17 +349,26 @@ class HubService {
return (name: r.name, version: r.version);
}
/// Fetch a module's README markdown via the hub. Errors come
/// back as `errorKind` strings (not exceptions) so callers can
/// render fallback UI without try/catch ceremony.
Future<({String errorKind, String text, String sourceUrl})>
fetchModuleDocs(String name, {String locale = ''}) async {
final r = await _client.fetchModuleDocs(name, locale: locale);
return (
errorKind: r.errorKind,
text: r.text,
sourceUrl: r.sourceUrl,
);
/// Read the installed module's `MODULE.md` (or
/// `MODULE.<locale>.md`) from disk under
/// `~/.fai/modules/<module>/`. Air-gap friendly, no network.
///
/// `state` is one of:
/// - `'found'` `text` holds the markdown
/// - `'no_docs'` module installed but bundle had no docs
/// - `'not_installed'` module isn't installed at all
Future<({String state, String text, String sourcePath})>
readInstalledModuleDocs(String name, {String locale = ''}) async {
final r = await _client.getInstalledModuleDocs(name, locale: locale);
final String state;
if (r.notInstalled) {
state = 'not_installed';
} else if (r.text.isEmpty) {
state = 'no_docs';
} else {
state = 'found';
}
return (state: state, text: r.text, sourcePath: r.sourcePath);
}
/// Snapshot of every configured MCP server.
@ -560,35 +572,31 @@ class HubService {
/// land as text Payloads, byte values as bytes Payloads
/// flows that mix both (e.g. extract taking a `document:
/// bytes` plus a text-shaped option) flow through one RPC.
/// Returns the named outputs as a map of UI-friendly strings.
Future<Map<String, String>> runSavedFlow({
/// [fileMimeTypes] is keyed the same as [fileInputs]; missing
/// entries fall back to `application/octet-stream`. Modules
/// often gate on MIME (the `text.extract` module refuses
/// octet-stream), so callers should provide a real type.
/// Returns the named outputs as a map of typed [FlowOutput]
/// values so each page can render text / JSON / bytes / file
/// with the right widget.
Future<Map<String, FlowOutput>> runSavedFlow({
required String name,
Map<String, String> textInputs = const {},
Map<String, Uint8List> fileInputs = const {},
Map<String, String> fileMimeTypes = const {},
}) async {
final r = await _client.runSavedFlow(
name: name,
textInputs: textInputs,
fileInputs: fileInputs,
fileMimeTypes: fileMimeTypes,
);
return {
for (final entry in r.outputs.entries)
entry.key: _payloadToText(entry.value),
entry.key: FlowOutput.fromPayload(entry.value),
};
}
String _payloadToText(Payload p) {
if (p.hasText()) return p.text;
if (p.hasJson()) return p.json.toString();
if (p.hasBytes()) {
return '<bytes: ${p.bytes.data.length} bytes, ${p.bytes.mimeType}>';
}
if (p.hasFile()) {
return '<file: ${p.file.uri}>';
}
return '<unknown payload variant>';
}
Future<List<AuditEvent>> recentEvents({
int limit = 50,
List<String> types = const [],