import 'dart:async'; import '../domain/chat_commands.dart'; /// Loads the session's harness commands (skills) for the composer palette the /// first time a slash draft asks for them, and keeps them once found. /// /// An empty reply is not final: the server answers at once from what it knows /// and starts the session's CLI in the background, so the commands may arrive /// on a later ask. An empty or failed load is retried after [retryAfter] on the /// next slash draft; meanwhile the palette offers the recorded commands alone. class ChatHarnessCommandLoader { ChatHarnessCommandLoader( this._load, { this.retryAfter = const Duration(seconds: 3), }); final Future> Function()? _load; final Duration retryAfter; List _commands = const []; bool _loading = false; DateTime? _lastEmpty; /// The commands loaded so far, empty until a load found some. List get commands => _commands; /// Starts a load unless commands are known, one is running, or the last one /// came back empty too recently; [onLoaded] runs when commands arrive. void request(void Function() onLoaded) { final load = _load; if (load == null || _commands.isNotEmpty || _loading) return; final lastEmpty = _lastEmpty; if (lastEmpty != null && DateTime.now().difference(lastEmpty) < retryAfter) { return; } _loading = true; unawaited(() async { try { final commands = await load(); if (commands.isEmpty) { _lastEmpty = DateTime.now(); return; } _commands = List.unmodifiable(commands); onLoaded(); } catch (_) { // The palette's recorded commands still work, and a typed skill can // still be sent through the unknown-command offer. _lastEmpty = DateTime.now(); } finally { _loading = false; } }()); } }