feat: embed a Flutter G4F client with Cronet, cookie jar, and origin WebView
Port the Oracle off the Python g4f container onto on-device providers: Chromium HTTP via Cronet, a shared cookie session, IterList retry, hosted OpenAI-compat aggregators, and same-origin WebView fallbacks instead of CORS fetch.
This commit is contained in:
@@ -0,0 +1,267 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'dart:ui';
|
||||
import '../g4f/client.dart';
|
||||
import '../g4f/models.dart';
|
||||
|
||||
class OracleChatScreen extends StatefulWidget {
|
||||
const OracleChatScreen({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<OracleChatScreen> createState() => _OracleChatScreenState();
|
||||
}
|
||||
|
||||
class ChatMessage {
|
||||
final String text;
|
||||
final bool isUser;
|
||||
|
||||
ChatMessage({required this.text, required this.isUser});
|
||||
}
|
||||
|
||||
class _OracleChatScreenState extends State<OracleChatScreen> {
|
||||
final TextEditingController _controller = TextEditingController();
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
final G4FClient _client = G4FClient();
|
||||
|
||||
final List<ChatMessage> _messages = [
|
||||
ChatMessage(
|
||||
text: "Я Оракул. Мой взор проникает сквозь завесу времени. О чем ты хочешь спросить?",
|
||||
isUser: false
|
||||
),
|
||||
];
|
||||
|
||||
bool _isLoading = false;
|
||||
|
||||
void _scrollToBottom() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static const _oracleSystem = Message(
|
||||
role: Role.system,
|
||||
content:
|
||||
'Ты — Великий Оракул 999, древний архетипический разум. '
|
||||
'Стиль речи: глубокий, философский, лаконичный, без банальностей. '
|
||||
'Отвечай на языке вопрошающего. Не упоминай модели, провайдеров и технические сбои.',
|
||||
);
|
||||
|
||||
Future<void> _sendMessage() async {
|
||||
final text = _controller.text.trim();
|
||||
if (text.isEmpty || _isLoading) return;
|
||||
|
||||
setState(() {
|
||||
_messages.add(ChatMessage(text: text, isUser: true));
|
||||
_messages.add(ChatMessage(text: '', isUser: false));
|
||||
_isLoading = true;
|
||||
});
|
||||
_controller.clear();
|
||||
_scrollToBottom();
|
||||
|
||||
final apiMessages = <Message>[
|
||||
_oracleSystem,
|
||||
for (final m in _messages)
|
||||
if (m.text.trim().isNotEmpty)
|
||||
Message(
|
||||
role: m.isUser ? Role.user : Role.assistant,
|
||||
content: m.text,
|
||||
),
|
||||
];
|
||||
|
||||
try {
|
||||
final reply = await _client.chat.completions.create(
|
||||
model: G4FModels.gpt4o,
|
||||
messages: apiMessages,
|
||||
);
|
||||
if (!mounted) return;
|
||||
_setLastOracleText(
|
||||
reply.trim().isEmpty
|
||||
? 'Мой взор затуманен. Знаки молчат. Спроси ещё раз.'
|
||||
: reply.trim(),
|
||||
);
|
||||
} catch (_) {
|
||||
if (!mounted) return;
|
||||
_setLastOracleText('Мой взор затуманен. Связь прервалась.');
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isLoading = false);
|
||||
_scrollToBottom();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _setLastOracleText(String text) {
|
||||
setState(() {
|
||||
_messages[_messages.length - 1] = ChatMessage(text: text, isUser: false);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF060B19),
|
||||
appBar: AppBar(
|
||||
title: const Text("Оракул", style: TextStyle(color: Color(0xFFFFD700), fontWeight: FontWeight.w300, letterSpacing: 2.0)),
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
centerTitle: true,
|
||||
iconTheme: const IconThemeData(color: Color(0xFFFFD700)),
|
||||
),
|
||||
extendBodyBehindAppBar: true,
|
||||
body: Container(
|
||||
decoration: const BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF0D0415), Color(0xFF060B19)],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
|
||||
itemCount: _messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final msg = _messages[index];
|
||||
return _buildMessageBubble(msg);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (_isLoading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
child: SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
color: Color(0xFFFFD700),
|
||||
strokeWidth: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
_buildInputArea(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMessageBubble(ChatMessage message) {
|
||||
return Align(
|
||||
alignment: message.isUser ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(bottom: 16.0),
|
||||
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.8),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(20),
|
||||
topRight: const Radius.circular(20),
|
||||
bottomLeft: Radius.circular(message.isUser ? 20 : 5),
|
||||
bottomRight: Radius.circular(message.isUser ? 5 : 20),
|
||||
),
|
||||
child: BackdropFilter(
|
||||
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: message.isUser
|
||||
? const Color(0xFF1E293B).withOpacity(0.6)
|
||||
: const Color(0xFF2E1A47).withOpacity(0.4),
|
||||
border: Border.all(
|
||||
color: message.isUser
|
||||
? Colors.white.withOpacity(0.1)
|
||||
: const Color(0xFFFFD700).withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
message.text,
|
||||
style: TextStyle(
|
||||
color: message.isUser ? Colors.white : const Color(0xFFE5E7EB),
|
||||
fontSize: 16,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInputArea() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 24),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF0D0415).withOpacity(0.8),
|
||||
border: Border(
|
||||
top: BorderSide(
|
||||
color: const Color(0xFFFFD700).withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.05),
|
||||
borderRadius: BorderRadius.circular(30),
|
||||
border: Border.all(color: Colors.white.withOpacity(0.1)),
|
||||
),
|
||||
child: TextField(
|
||||
controller: _controller,
|
||||
style: const TextStyle(color: Colors.white),
|
||||
decoration: const InputDecoration(
|
||||
hintText: "Спроси Оракула...",
|
||||
hintStyle: TextStyle(color: Colors.white38),
|
||||
border: InputBorder.none,
|
||||
contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 14),
|
||||
),
|
||||
textInputAction: TextInputAction.send,
|
||||
onSubmitted: (_) => _sendMessage(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
GestureDetector(
|
||||
onTap: _isLoading ? null : _sendMessage,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
gradient: const RadialGradient(
|
||||
colors: [Color(0xFFFFD700), Color(0xFFB8860B)],
|
||||
center: Alignment.topLeft,
|
||||
radius: 1.0,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: const Color(0xFFFFD700).withOpacity(0.3),
|
||||
blurRadius: 12,
|
||||
spreadRadius: 2,
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.auto_awesome,
|
||||
color: Color(0xFF2E1A47),
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../data/words_data.dart';
|
||||
import '../g4f/g4f.dart';
|
||||
import '../models/history_entry_model.dart';
|
||||
import '../models/word_model.dart';
|
||||
import '../services/ai_oracle_service.dart';
|
||||
|
||||
class ProviderProbeRow {
|
||||
ProviderProbeRow({
|
||||
required this.provider,
|
||||
this.running = false,
|
||||
this.ok,
|
||||
this.text = '',
|
||||
this.error,
|
||||
this.elapsedMs = 0,
|
||||
});
|
||||
|
||||
final BaseProvider provider;
|
||||
bool running;
|
||||
bool? ok;
|
||||
String text;
|
||||
String? error;
|
||||
int elapsedMs;
|
||||
|
||||
String get name => provider.name;
|
||||
bool get isWebView => provider.isWebView;
|
||||
}
|
||||
|
||||
/// On-device comparison: the real Oracle prompt, every G4F provider, Android process.
|
||||
class ProviderBakeoffScreen extends StatefulWidget {
|
||||
const ProviderBakeoffScreen({super.key, this.autoStart = true});
|
||||
|
||||
final bool autoStart;
|
||||
|
||||
@override
|
||||
State<ProviderBakeoffScreen> createState() => _ProviderBakeoffScreenState();
|
||||
}
|
||||
|
||||
class _ProviderBakeoffScreenState extends State<ProviderBakeoffScreen> {
|
||||
static const _question = 'Что скрыто в моём нынешнем выборе?';
|
||||
|
||||
late final List<SessionWord> _words;
|
||||
late final List<Message> _messages;
|
||||
late final List<ProviderProbeRow> _rows;
|
||||
bool _running = false;
|
||||
bool _done = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_words = _pickWords();
|
||||
_messages = AiOracleService().buildInterpretationMessages(
|
||||
words: _words,
|
||||
question: _question,
|
||||
);
|
||||
_rows = [
|
||||
for (final p in G4FClient().chat.completions.providers)
|
||||
if (p.working) ProviderProbeRow(provider: p),
|
||||
];
|
||||
if (widget.autoStart) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) => _run());
|
||||
}
|
||||
}
|
||||
|
||||
List<SessionWord> _pickWords() {
|
||||
WordItem byName(String name) => kRussianTop1000Words.firstWhere(
|
||||
(w) => w.word == name,
|
||||
);
|
||||
final items = [
|
||||
byName('огонь').copyWith(sessionNumber: 17),
|
||||
byName('зеркало').copyWith(sessionNumber: 92),
|
||||
byName('порог').copyWith(sessionNumber: 112),
|
||||
];
|
||||
return [
|
||||
for (final item in items) SessionWord.fromWordItem(item),
|
||||
];
|
||||
}
|
||||
|
||||
Future<void> _run() async {
|
||||
if (_running) return;
|
||||
setState(() {
|
||||
_running = true;
|
||||
_done = false;
|
||||
for (final row in _rows) {
|
||||
row.running = false;
|
||||
row.ok = null;
|
||||
row.text = '';
|
||||
row.error = null;
|
||||
row.elapsedMs = 0;
|
||||
}
|
||||
});
|
||||
|
||||
_log('BEGIN question=$_question words=${_words.map((w) => w.word).join(",")}');
|
||||
|
||||
for (final row in _rows) {
|
||||
if (!mounted) return;
|
||||
setState(() => row.running = true);
|
||||
_log('START ${row.name} webview=${row.isWebView}');
|
||||
final sw = Stopwatch()..start();
|
||||
try {
|
||||
final model = row.provider.models.contains(G4FModels.gpt4o)
|
||||
? G4FModels.gpt4o
|
||||
: row.provider.defaultModel;
|
||||
final text = await row.provider.complete(model, _messages);
|
||||
sw.stop();
|
||||
final ok = looksLikeModelOutput(text) && text.trim().length >= 2;
|
||||
row
|
||||
..ok = ok
|
||||
..text = text.trim()
|
||||
..error = ok ? null : 'unusable'
|
||||
..elapsedMs = sw.elapsedMilliseconds
|
||||
..running = false;
|
||||
_log(
|
||||
'DONE ${row.name} ok=$ok ms=${row.elapsedMs} chars=${row.text.length}',
|
||||
);
|
||||
_log('TEXT ${row.name} ${jsonEncode(row.text)}');
|
||||
} catch (e) {
|
||||
sw.stop();
|
||||
row
|
||||
..ok = false
|
||||
..error = e.toString()
|
||||
..elapsedMs = sw.elapsedMilliseconds
|
||||
..running = false;
|
||||
_log('FAIL ${row.name} ms=${row.elapsedMs} $e');
|
||||
}
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
await _writeReport();
|
||||
_log('END ok=${_rows.where((r) => r.ok == true).length}/${_rows.length}');
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_running = false;
|
||||
_done = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _writeReport() async {
|
||||
final report = {
|
||||
'platform': Platform.operatingSystem,
|
||||
'question': _question,
|
||||
'words': [
|
||||
for (final w in _words)
|
||||
{
|
||||
'word': w.word,
|
||||
'sessionNumber': w.sessionNumber,
|
||||
'category': w.category,
|
||||
'symbolicMeaning': w.symbolicMeaning,
|
||||
}
|
||||
],
|
||||
'results': [
|
||||
for (final r in _rows)
|
||||
{
|
||||
'name': r.name,
|
||||
'webview': r.isWebView,
|
||||
'ok': r.ok,
|
||||
'ms': r.elapsedMs,
|
||||
'error': r.error,
|
||||
'text': r.text,
|
||||
}
|
||||
],
|
||||
};
|
||||
final encoded = const JsonEncoder.withIndent(' ').convert(report);
|
||||
_log('REPORT $encoded');
|
||||
try {
|
||||
final file = File('/data/data/com.example.words999.words999/cache/oracle_bakeoff.json');
|
||||
await file.parent.create(recursive: true);
|
||||
await file.writeAsString(encoded);
|
||||
_log('WROTE ${file.path}');
|
||||
} catch (e) {
|
||||
_log('WRITE_FAIL $e');
|
||||
}
|
||||
}
|
||||
|
||||
void _log(String line) {
|
||||
debugPrint('ORACLE_BAKEOFF|$line');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final okCount = _rows.where((r) => r.ok == true).length;
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF0C0E1A),
|
||||
appBar: AppBar(
|
||||
title: const Text('Сравнение провайдеров'),
|
||||
actions: [
|
||||
if (!_running)
|
||||
IconButton(
|
||||
onPressed: _run,
|
||||
icon: const Icon(Icons.refresh),
|
||||
tooltip: 'Запустить снова',
|
||||
),
|
||||
],
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),
|
||||
children: [
|
||||
_headerCard(okCount),
|
||||
const SizedBox(height: 12),
|
||||
for (final row in _rows) ...[
|
||||
_resultCard(row),
|
||||
const SizedBox(height: 10),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _headerCard(int okCount) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF151829),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFFFD54F).withValues(alpha: 0.25)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
_running
|
||||
? 'Идёт опрос на Android…'
|
||||
: _done
|
||||
? 'Готово: $okCount из ${_rows.length} ответили'
|
||||
: 'Ожидание запуска',
|
||||
style: const TextStyle(
|
||||
color: Color(0xFFFFD54F),
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Вопрос: «$_question»',
|
||||
style: const TextStyle(color: Color(0xFFE8EAF6), height: 1.35),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Знаки: ${_words.map((w) => '«${w.word.toUpperCase()}» (#${w.formattedSessionNumber})').join(' → ')}',
|
||||
style: const TextStyle(color: Color(0xFF80DEEA), height: 1.35),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
const Text(
|
||||
'Тот же system-промпт и user-промпт, что у interpretSession. Каждый провайдер вызывается отдельно, без запасного переключения.',
|
||||
style: TextStyle(color: Color(0xFF8C93B8), fontSize: 12, height: 1.35),
|
||||
),
|
||||
if (_running)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 12),
|
||||
child: LinearProgressIndicator(color: Color(0xFFFFD54F)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _resultCard(ProviderProbeRow row) {
|
||||
final Color accent;
|
||||
if (row.running) {
|
||||
accent = const Color(0xFF80DEEA);
|
||||
} else if (row.ok == true) {
|
||||
accent = const Color(0xFF81C784);
|
||||
} else if (row.ok == false) {
|
||||
accent = const Color(0xFFE57373);
|
||||
} else {
|
||||
accent = const Color(0xFF5C638A);
|
||||
}
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF151829),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: accent.withValues(alpha: 0.45)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
row.running
|
||||
? Icons.hourglass_top
|
||||
: row.ok == true
|
||||
? Icons.check_circle
|
||||
: row.ok == false
|
||||
? Icons.cancel
|
||||
: Icons.circle_outlined,
|
||||
color: accent,
|
||||
size: 18,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
row.name,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFFFFF9C4),
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
row.isWebView ? 'WebView' : 'REST',
|
||||
style: const TextStyle(color: Color(0xFF8C93B8), fontSize: 11),
|
||||
),
|
||||
if (row.elapsedMs > 0) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'${(row.elapsedMs / 1000).toStringAsFixed(1)}с',
|
||||
style: const TextStyle(color: Color(0xFF8C93B8), fontSize: 11),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (row.running)
|
||||
const Text('Ждём полный ответ…', style: TextStyle(color: Color(0xFF80DEEA)))
|
||||
else if (row.ok == true)
|
||||
SelectableText(
|
||||
row.text,
|
||||
style: const TextStyle(color: Color(0xFFE8EAF6), height: 1.4, fontSize: 14),
|
||||
)
|
||||
else if (row.ok == false)
|
||||
Text(
|
||||
row.error ?? 'ошибка',
|
||||
style: const TextStyle(color: Color(0xFFE57373), fontSize: 12, height: 1.35),
|
||||
)
|
||||
else
|
||||
const Text('в очереди', style: TextStyle(color: Color(0xFF5C638A), fontSize: 12)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user