chain-studio/lib/data/fai_log.dart
flemming-it 8f5cd2528b
Some checks failed
Security / Security check (push) Failing after 1s
feat(studio): central error helpers + inline log viewer + Today CTAs
Bundles the error-UX overhaul and the inline log viewer:

  - New `FaiLog` (`~/.fai/logs/studio-errors.log`, 256 KiB rotation,
    JSON-per-line). Every operator-visible failure is appended so
    `fai admin doctor` and the new viewer can show the trail
    without the operator having to reproduce the failure.
  - New `showFaiErrorSnack` / `showFaiErrorDialog` helpers wrap
    `FaiErrorBox` in copyable surfaces; 27 ad-hoc
    `SnackBar(content: Text(e.toString()))` sites swept to use
    them (settings, doctor, audit, store, module sheet, system-AI
    editor, flow output).
  - New `FaiLogViewer` modal (`showFaiLogViewer`) renders log
    files inline with line numbers, JSON-key + `[level]` token
    colouring, Copy-all, Refresh, Open-externally. Doctor's
    daemon-paths panel grows a "View" button next to "Open" for
    every `.log` row and now also lists the Studio errors log.
  - Today carousel: CTAs now actually re-run search after a
    `filterCategory` / `runQuery` story is tapped (was only
    flipping the chip state). Fallback story list bumped to 8.
  - Editor bumped to git ref carrying 0.15.0 (type-token
    colouring + analyzer diagnostics).

Studio bumped to 0.62.0.

Signed-off-by: flemming-it <stefan.a.flemming@googlemail.com>
2026-06-04 02:08:15 +02:00

119 lines
4.1 KiB
Dart

// Central error log for Studio. Every error surfaced to the
// operator (SnackBar, error sheet, recoverable dialog) is also
// appended here so `fai doctor` and "Open log" can show what
// went wrong without the operator having to reproduce the
// failure.
//
// Path: `~/.fai/logs/studio-errors.log` (cross-platform via
// HOME / USERPROFILE). One line per event, JSON-shaped so
// `fai doctor` can parse it; humans can still read it because
// the JSON is single-line and short.
//
// Best-effort by design: a failed write to the log file must
// never break the UI layer that asked us to log. We swallow
// IO errors silently — the worst case is the operator loses
// the trail of one failure, not the failure itself.
//
// Rotation: when the file passes 256 KiB we move it to
// `studio-errors.log.1` and start fresh. One rotation level is
// enough — anything older is noise, and a Studio session
// rarely produces more than a few KiB of error text.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
class FaiLog {
FaiLog._();
static final FaiLog instance = FaiLog._();
// Serialise concurrent writes — Future-based mutex so a burst
// of errors (rare but happens during failed install retries)
// doesn't interleave half-lines on disk.
Future<void> _tail = Future.value();
static const int _rotateBytes = 256 * 1024;
String get _path {
final home =
Platform.environment['HOME'] ??
Platform.environment['USERPROFILE'] ??
'.';
return p.join(home, '.fai', 'logs', 'studio-errors.log');
}
/// Absolute path of the studio-errors log. Public so the
/// Doctor page and the in-app log viewer can read it without
/// hard-coding the layout twice.
String get path => _path;
/// Append a single error event. The [source] is a short tag
/// (`flows.run`, `daemon.logs`, …) that lets a reader group
/// related failures. [error] can be any thrown object — gRPC
/// codes, plain strings, exceptions; we serialise it via
/// [error.toString()] so the on-disk record matches what the
/// operator saw on screen.
Future<void> error(String source, Object error, {Object? context}) {
final entry = <String, Object?>{
'ts': DateTime.now().toUtc().toIso8601String(),
'level': 'error',
'source': source,
'error': error.toString(),
if (context != null) 'context': context.toString(),
};
return _append(entry);
}
/// Read the last [maxLines] lines back. Used by `fai doctor`
/// + Settings → "Recent errors" view. Returns oldest first so
/// the caller can render in chronological order.
Future<List<String>> tail({int maxLines = 50}) async {
try {
final f = File(_path);
if (!await f.exists()) return const <String>[];
final raw = await f.readAsString();
final lines = raw.split('\n').where((l) => l.isNotEmpty).toList();
if (lines.length <= maxLines) return lines;
return lines.sublist(lines.length - maxLines);
} catch (_) {
return const <String>[];
}
}
Future<void> _append(Map<String, Object?> entry) {
final next = _tail.then((_) async {
try {
final f = File(_path);
final dir = Directory(p.dirname(_path));
if (!await dir.exists()) {
await dir.create(recursive: true);
}
// Rotate before write so a hot-loop never balloons past
// the cap. Single-level rotation: keep the previous file
// as `.1`, anything older drops on the floor.
if (await f.exists()) {
final size = await f.length();
if (size >= _rotateBytes) {
final rotated = File('$_path.1');
if (await rotated.exists()) {
await rotated.delete();
}
await f.rename(rotated.path);
}
}
await f.writeAsString(
'${jsonEncode(entry)}\n',
mode: FileMode.append,
flush: false,
);
} catch (_) {
// Best-effort. A failed log write must not crash the UI.
}
});
_tail = next.catchError((_) {});
return next;
}
}