import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; import '../conversation/chat_thread_fixtures.dart'; /// A gateway for one open conversation (session `s`) that answers the shell /// command requests from recorded state and lets a test push their frames. class ShellGateway implements ApiGateway { final calls = <({String type, JsonMap fields})>[]; final _frames = StreamController.broadcast(); List runs = const []; String? refusal; int _serial = 0; @override Stream get frames => _frames.stream; List bodies(String type) => [ for (final call in calls) if (call.type == type) (call.fields['chat_shell_run_request'] ?? call.fields['chat_prompt'] ?? call.fields['chat_query']) as JsonMap, ]; @override Future call(String type, [JsonMap fields = const {}]) async { calls.add((type: type, fields: fields)); final body = fields['chat_shell_run_request'] as JsonMap? ?? const {}; switch (type) { case 'chat_messages': return chatPage(const []); case 'chat_shell_runs': return {'chat_shell_runs': runs}; case 'chat_shell_run': if (refusal != null) throw StateError(refusal!); return { 'chat_shell_run': shellRecord( 'run_${++_serial}', command: '${body['command']}', ), }; case 'chat_shell_run_output': return { 'chat_shell_run': runs.firstWhere((r) => r['id'] == body['run_id']), }; } return {}; } void emitRun(JsonMap run) => _frames.add({ 'type': 'chat_shell_run_event', 'chat_shell_run_event': { 'session_id': 's', 'run_id': run['id'], 'run': run, }, }); void emitOutput(String id, String text, int offset) => _frames.add({ 'type': 'chat_shell_run_event', 'chat_shell_run_event': { 'session_id': 's', 'run_id': id, 'output': text, 'offset': offset, 'end': offset + text.length, }, }); void close() => _frames.close(); } JsonMap shellRecord( String id, { String command = 'make test', String status = 'running', int? exitCode, String output = '', int durationMs = 0, }) => { 'id': id, 'session_id': 's', 'command': command, 'directory': '/home/op/project', 'status': status, 'exit_code': ?exitCode, 'started_at': 1000, 'ended_at': ?(status == 'running' ? null : 1000 + durationMs), 'duration_ms': durationMs, 'output': output, 'output_bytes': output.length, }; Widget shellThread(ShellGateway gateway, {bool cupertino = false}) { final thread = ChatThreadView( gateway: gateway, sessionId: 's', syncToken: 0, onBack: () {}, drafts: MemoryChatDraftStore(), ); return cupertino ? CupertinoApp(home: CupertinoPageScaffold(child: thread)) : MaterialApp(home: Scaffold(body: thread)); }