Files
EasyDesignCollection/lib/ui/ai_dialog.dart
T
admin 91c6132ef9 feat(ai): AI 生成强化——流式进度、可取消、超时、增量修改、自动纠错与结果清洗
- 流式接收(SSE):实时显示已用时 / 思考字符数 / 输出字符数,可随时取消
- 空闲 180 秒无数据自动超时并给出可读提示(此前可能无限等待)
- 新增「修改当前工程」模式:在现有工程上增删改,不再只能整图替换
- 解析/校验失败时自动把错误反馈给模型修复(最多 2 次重试)
- 结果清洗:修正非法时长与越界角度、剔除无效依赖、层号归一化,并提示修正项
- 提示词优化:layer 按并行资源分配(避免层数爆炸)、命名与 id 引用约束
- 版本号 1.1.0+11
2026-10-08 15:44:37 +08:00

460 lines
18 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// AI 生成时序图对话框。
///
/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)、推理强度
/// (高 / 最高)与生成方式(新建工程 / 在当前工程上修改)→ 在较大的自然语言
/// 输入框中描述工艺流程或修改要求 → 点击「生成」。
///
/// 生成过程为**流式**:实时显示已用时、思考与输出字符数,可随时取消;
/// 输出无法解析时自动让模型修复重试(最多两次)。
///
/// 安全:API Key 仅保存在内存(静态字段,便于本次会话内复用),
/// 不写入工程文件,也不会被日志输出。
library;
import 'dart:async';
import 'package:flutter/material.dart';
import '../ai/ai_client.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
import 'dialogs.dart';
class AiGenerateDialog extends StatefulWidget {
const AiGenerateDialog({super.key, required this.controller});
/// 全局应用控制器。
final AppController controller;
@override
State<AiGenerateDialog> createState() => _AiGenerateDialogState();
}
class _AiGenerateDialogState extends State<AiGenerateDialog> {
/// 会话内复用的 API Key(不持久化)。
static String _sessionKey = '';
/// 示例描述:与输入框灰色占位一致,可一键填入后直接编辑。
static const String _examplePrompt =
'一条装配线,循环 2.4 秒。上料后定位夹紧,夹紧完成再伺服下压 0.6 秒;'
'下压完成后并行进行超声波焊接与视觉检测;检测完成分选下料,最后清洁吹气。'
'共 3 个工位,请给出动作、相位与依赖关系。';
late final TextEditingController _key;
late final TextEditingController _prompt;
String _model = kAiModels.first.id;
String _effort = 'high';
bool _obscure = true;
bool _busy = false;
String? _error;
/// 生成方式:`new` = 新建工程(整图生成);`modify` = 在当前工程上修改。
String _mode = 'new';
/// 当前生成用的取消令牌(每次生成重建)。
AiCancelToken? _token;
/// 生成计时器(每秒刷新已用时)。
Timer? _ticker;
/// 已用时(秒)。
int _secs = 0;
/// 已接收的思考字符数(推理模型)。
int _thinkChars = 0;
/// 已接收的 JSON 输出字符数。
int _outChars = 0;
/// 当前第几次尝试(>0 表示正在自动修复上一次的输出)。
int _attempt = 0;
@override
void initState() {
super.initState();
_key = TextEditingController(text: _sessionKey);
_prompt = TextEditingController();
}
@override
void dispose() {
_ticker?.cancel();
_key.dispose();
_prompt.dispose();
super.dispose();
}
Future<void> _generate() async {
final AiCancelToken token = AiCancelToken();
setState(() {
_busy = true;
_error = null;
_secs = 0;
_thinkChars = 0;
_outChars = 0;
_attempt = 0;
_token = token;
});
_ticker = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() => _secs++);
});
try {
_sessionKey = _key.text.trim();
final AiResult r = await AiClient.generate(
prompt: _prompt.text,
settings: AiSettings(apiKey: _sessionKey, model: _model, effort: _effort),
base: _mode == 'modify' ? widget.controller.project : null,
cancelToken: token,
onProgress: (AiProgress p) {
if (!mounted) return;
setState(() {
_thinkChars = p.reasoningChars;
_outChars = p.contentChars;
_attempt = p.attempt;
});
},
);
widget.controller.loadProject(r.project, dirty: true);
final String extra = r.warnings.isEmpty ? '' : '(${r.warnings.join('、')})';
widget.controller
.setStatus('AI 已生成时序图(${r.project.actions.length} 个动作)$extra');
if (mounted) Navigator.pop(context);
} catch (e) {
if (mounted) setState(() => _error = '$e');
} finally {
_ticker?.cancel();
_ticker = null;
if (mounted) setState(() => _busy = false);
}
}
/// 取消正在进行的生成(中断 HTTP 请求)。
void _cancel() {
_token?.cancel();
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return Dialog(
backgroundColor: t.dialog,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
child: scaledDialogBox(
context,
880,
620,
Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
// 标题
Row(
children: <Widget>[
Icon(Icons.auto_awesome, size: 21, color: t.accent2),
const SizedBox(width: 8),
Text('AI 生成时序图', style: TextStyle(color: t.text, fontSize: 17, fontWeight: FontWeight.w700)),
const Spacer(),
Text('自然语言 → 时序图', style: TextStyle(color: t.dim, fontSize: 11.5)),
],
),
const Divider(height: 22),
// API Key
Text('DeepSeek API Key', style: TextStyle(color: t.sub, fontSize: 12.5)),
const SizedBox(height: 6),
TextField(
controller: _key,
obscureText: _obscure,
style: TextStyle(color: t.text, fontSize: 12.5),
decoration: InputDecoration(
isDense: true,
hintText: 'sk-...',
hintStyle: TextStyle(color: t.dim, fontSize: 12.5),
filled: true,
fillColor: t.panel2,
prefixIcon: Icon(Icons.key, size: 16, color: t.dim),
suffixIcon: IconButton(
onPressed: () => setState(() => _obscure = !_obscure),
icon: Icon(_obscure ? Icons.visibility_off : Icons.visibility, size: 16, color: t.dim),
tooltip: _obscure ? '显示' : '隐藏',
),
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
const SizedBox(height: 14),
// 模型 + 推理强度
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('模型', style: TextStyle(color: t.sub, fontSize: 12.5)),
const SizedBox(height: 6),
Container(
height: 38,
padding: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line2),
),
child: DropdownButton<String>(
value: _model,
isExpanded: true,
underline: const SizedBox.shrink(),
dropdownColor: t.dialog,
style: TextStyle(color: t.text, fontSize: 12.5),
icon: Icon(Icons.keyboard_arrow_down, size: 18, color: t.sub),
items: kAiModels
.map((AiModelOption m) =>
DropdownMenuItem<String>(value: m.id, child: Text(m.label)))
.toList(),
onChanged: (String? v) {
if (v != null) setState(() => _model = v);
},
),
),
],
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('推理强度', style: TextStyle(color: t.sub, fontSize: 12.5)),
const SizedBox(height: 6),
Row(
children: <Widget>[
Expanded(child: _effortChip(t, '高', 'high')),
const SizedBox(width: 8),
Expanded(child: _effortChip(t, '最高', 'max')),
],
),
],
),
),
],
),
const SizedBox(height: 14),
// 生成方式:新建整图 / 在当前工程上修改(增量)。
Row(
children: <Widget>[
Text('生成方式', style: TextStyle(color: t.sub, fontSize: 12.5)),
const SizedBox(width: 12),
SizedBox(width: 106, child: _modeChip(t, '新建工程', 'new')),
const SizedBox(width: 8),
SizedBox(width: 128, child: _modeChip(t, '修改当前工程', 'modify')),
const SizedBox(width: 12),
Expanded(
child: Text(
_mode == 'modify'
? '在现有工程上增删改,未涉及部分保持不变'
: '重新生成整张时序图(替换当前工程)',
style: TextStyle(color: t.dim, fontSize: 11),
),
),
],
),
const SizedBox(height: 14),
// 自然语言输入(大输入框)
Row(
children: <Widget>[
Text('用自然语言描述工艺流程', style: TextStyle(color: t.sub, fontSize: 12.5)),
const Spacer(),
// 一键把灰色示例填入输入框,便于直接修改后生成。
TextButton.icon(
onPressed: _busy
? null
: () => setState(() => _prompt.text = _examplePrompt),
icon: const Icon(Icons.edit_note, size: 17),
label: const Text('编辑示例', style: TextStyle(fontSize: 12)),
style: TextButton.styleFrom(
foregroundColor: t.accent,
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 28),
),
),
],
),
const SizedBox(height: 6),
Expanded(
child: Container(
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: t.line2),
),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: TextField(
controller: _prompt,
maxLines: null,
expands: true,
textAlignVertical: TextAlignVertical.top,
style: TextStyle(color: t.text, fontSize: 12.5, height: 1.6),
decoration: InputDecoration.collapsed(
hintText: '例如:$_examplePrompt',
hintStyle: TextStyle(color: t.dim, fontSize: 12.5, height: 1.6),
),
),
),
),
if (_error != null) ...<Widget>[
const SizedBox(height: 10),
Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: _error == '已取消' ? t.panel2 : t.danger.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: _error == '已取消' ? t.line2 : t.danger.withValues(alpha: 0.5)),
),
child: Text(_error!,
style: TextStyle(
color: _error == '已取消' ? t.sub : t.danger,
fontSize: 12,
height: 1.5)),
),
],
if (_busy) ...<Widget>[
const SizedBox(height: 10),
Container(
width: double.infinity,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: t.line2),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
SizedBox(
width: 13,
height: 13,
child: CircularProgressIndicator(strokeWidth: 2, color: t.accent),
),
const SizedBox(width: 8),
Text(
_attempt > 0
? '格式有误,正在自动修复(第 ${_attempt + 1} 次尝试)· 已用时 $_secs 秒'
: '生成中… 已用时 $_secs 秒',
style: TextStyle(color: t.sub, fontSize: 12),
),
const Spacer(),
Text(
_thinkChars > 0 || _outChars > 0
? '思考 $_thinkChars 字 · 输出 $_outChars 字'
: '等待模型响应…',
style: TextStyle(color: t.dim, fontSize: 11),
),
],
),
const SizedBox(height: 8),
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
minHeight: 4,
color: t.accent2,
backgroundColor: t.line2,
),
),
],
),
),
],
const SizedBox(height: 14),
// 操作按钮:生成 ↔ 取消生成(流式过程中可随时中断)。
Row(
children: <Widget>[
Expanded(
child: Text(
'API Key 仅保存在本机内存,不写入工程文件。',
style: TextStyle(color: t.dim, fontSize: 11),
),
),
TextButton(
onPressed: () {
if (_busy) _cancel();
Navigator.pop(context);
},
child: const Text('取消'),
),
const SizedBox(width: 8),
_busy
? FilledButton.icon(
onPressed: _cancel,
icon: const Icon(Icons.stop_circle_outlined, size: 16),
label: const Text('取消生成'),
style: FilledButton.styleFrom(
backgroundColor: t.danger,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
),
)
: FilledButton.icon(
onPressed: _generate,
icon: const Icon(Icons.auto_awesome, size: 16),
label: const Text('生成'),
style: FilledButton.styleFrom(
backgroundColor: t.accent2,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)),
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
),
),
],
),
],
),
),
),
);
}
/// 推理强度分段按钮。
Widget _effortChip(Tokens t, String label, String value) {
final bool active = _effort == value;
return InkWell(
onTap: () => setState(() => _effort = value),
borderRadius: BorderRadius.circular(8),
child: Container(
height: 38,
alignment: Alignment.center,
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.18) : t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: active ? t.accent : t.line2),
),
child: Text(label, style: TextStyle(color: active ? t.accent : t.sub, fontSize: 12.5)),
),
);
}
/// 生成方式分段按钮(新建工程 / 修改当前工程);生成中不可切换。
Widget _modeChip(Tokens t, String label, String value) {
final bool active = _mode == value;
return InkWell(
onTap: _busy ? null : () => setState(() => _mode = value),
borderRadius: BorderRadius.circular(8),
child: Container(
height: 34,
alignment: Alignment.center,
decoration: BoxDecoration(
color: active ? t.accent.withValues(alpha: 0.18) : t.panel2,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: active ? t.accent : t.line2),
),
child: Text(label, style: TextStyle(color: active ? t.accent : t.sub, fontSize: 12)),
),
);
}
}