From 91c6132ef926e90e4604be3e7620cd73d09b6cb1 Mon Sep 17 00:00:00 2001 From: liuyu65 Date: Thu, 8 Oct 2026 15:44:37 +0800 Subject: [PATCH] =?UTF-8?q?feat(ai):=20AI=20=E7=94=9F=E6=88=90=E5=BC=BA?= =?UTF-8?q?=E5=8C=96=E2=80=94=E2=80=94=E6=B5=81=E5=BC=8F=E8=BF=9B=E5=BA=A6?= =?UTF-8?q?=E3=80=81=E5=8F=AF=E5=8F=96=E6=B6=88=E3=80=81=E8=B6=85=E6=97=B6?= =?UTF-8?q?=E3=80=81=E5=A2=9E=E9=87=8F=E4=BF=AE=E6=94=B9=E3=80=81=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E7=BA=A0=E9=94=99=E4=B8=8E=E7=BB=93=E6=9E=9C=E6=B8=85?= =?UTF-8?q?=E6=B4=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 流式接收(SSE):实时显示已用时 / 思考字符数 / 输出字符数,可随时取消 - 空闲 180 秒无数据自动超时并给出可读提示(此前可能无限等待) - 新增「修改当前工程」模式:在现有工程上增删改,不再只能整图替换 - 解析/校验失败时自动把错误反馈给模型修复(最多 2 次重试) - 结果清洗:修正非法时长与越界角度、剔除无效依赖、层号归一化,并提示修正项 - 提示词优化:layer 按并行资源分配(避免层数爆炸)、命名与 id 引用约束 - 版本号 1.1.0+11 --- BUILD-NOTES.md | 2 +- README.md | 6 +- lib/ai/ai_client.dart | 263 ++++++++++++++++++++++++++++++++++++++---- lib/ui/ai_dialog.dart | 213 +++++++++++++++++++++++++++++----- lib/ui/dialogs.dart | 2 +- pubspec.yaml | 2 +- 6 files changed, 428 insertions(+), 60 deletions(-) diff --git a/BUILD-NOTES.md b/BUILD-NOTES.md index 08e6eef..172c7d7 100644 --- a/BUILD-NOTES.md +++ b/BUILD-NOTES.md @@ -127,7 +127,7 @@ flutter pub get flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-release.apk ``` -- 发布包归档:`release\sequence_diagram_android_v1.0.9_release.apk`(**本地保留,不入库**;exe 的 `dist\` 同理)。 +- 发布包归档:`release\sequence_diagram_android_v1.1.0_release.apk`(**本地保留,不入库**;exe 的 `dist\` 同理)。 - 上架应用商店时建议在 `android\app\build.gradle.kts` 配置正式签名后再构建 AAB: `flutter build appbundle --release`。 - 应用名「时序图设计」、包名 `cc.sincos.sequence_diagram`、launcher 图标由 diff --git a/README.md b/README.md index 03aabee..accb251 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ - **深色 / 浅色双主题**:右上角 ☀ / ☾ 一键切换,语义颜色不变,导出 SVG 与屏幕一致 - **导出 SVG**:矢量、分层、带语义 `id` / `data-*` 元数据,可直接进工艺卡与 MES -## 正式版 V1.0.9 +## 正式版 V1.1.0 **可运行的 Flutter Windows 桌面正式版**(源码在 `lib/`),设计人:呆头鹅。 @@ -97,7 +97,7 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模 - **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装; - **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像: ```bash - flutter build apk --release # 产物 → release/sequence_diagram_android_v1.0.9_release.apk + flutter build apk --release # 产物 → release/sequence_diagram_android_v1.1.0_release.apk ``` - **自测**:`test/tablet_layout_test.dart` 覆盖 1280×800、2560×1600、960×600、800×480、竖屏 800×1280、600×960 等 7 种分辨率的无溢出回归; - **demo 图**:`demo/tablet-*.png`(由 `test/tablet_screenshots_test.dart` 生成)。 @@ -113,6 +113,6 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模 - **软件**:时序图设计 · Sequence Diagram Studio - **设计人**:呆头鹅 -- **版本**:V1.0.9 +- **版本**:V1.1.0 - **版权**:Copyright © 2026 呆头鹅。保留所有权利。 - **架构文档**:[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) · **使用帮助**:[`docs/HELP.md`](docs/HELP.md) diff --git a/lib/ai/ai_client.dart b/lib/ai/ai_client.dart index 9e68110..0506232 100644 --- a/lib/ai/ai_client.dart +++ b/lib/ai/ai_client.dart @@ -1,12 +1,21 @@ /// DeepSeek 大模型客户端:把自然语言描述转换为可加载的 [Project]。 /// /// 架构位置:独立于 UI 与状态层的纯服务模块,仅依赖 `dart:io`(HttpClient) -/// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [Project] 后交给 +/// 与模型层。UI 层通过 [AiGenerateDialog] 调用,拿到 [AiResult] 后交给 /// [AppController.loadProject] 载入。 /// +/// 能力: +/// - **流式接收**:SSE 增量解析,实时报告「思考 / 输出」字符数; +/// - **可取消**:通过 [AiCancelToken] 立即中断 HTTP 请求; +/// - **超时保护**:空闲超过 `idleTimeout` 自动失败并给出可读提示; +/// - **增量修改**:传入基准 [Project],让模型在现有工程上增删改而非整图重画; +/// - **自动纠错**:输出无法解析为时序图时,把错误反馈给模型自动修复重试; +/// - **结果清洗**:修正非法时长 / 越界角度,剔除指向不存在动作的依赖,归一化层号。 +/// /// 约束:不引入任何原生插件或第三方 HTTP 包,全部使用 `dart:io` 实现。 library; +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -61,6 +70,55 @@ class AiException implements Exception { String toString() => message; } +/// 流式生成进度:分别统计「思考」与「输出」已接收的字符数。 +class AiProgress { + /// 构造。 + const AiProgress({ + required this.reasoningChars, + required this.contentChars, + required this.attempt, + }); + + /// 已接收的思考(reasoning_content)字符数;非推理模型恒为 0。 + final int reasoningChars; + + /// 已接收的正式输出(content)字符数。 + final int contentChars; + + /// 第几次尝试(0 起;大于 0 表示正在自动修复上一次的输出)。 + final int attempt; +} + +/// 取消令牌:界面点击「取消生成」时置位,并触发底层 HTTP 中断。 +class AiCancelToken { + bool _cancelled = false; + void Function()? _abort; + + /// 是否已被取消。 + bool get cancelled => _cancelled; + + /// 绑定底层中断动作(关闭 HTTP 客户端 / socket)。 + void bindAbort(void Function() abort) => _abort = abort; + + /// 请求取消:先置位再触发中断,保证两侧都能观察到。 + void cancel() { + _cancelled = true; + _abort?.call(); + } +} + +/// 生成结果:清洗后的项目 + 自动修正说明(用于状态栏提示)。 +class AiResult { + /// 构造。 + const AiResult(this.project, this.warnings); + + /// 解析并清洗后的项目。 + final Project project; + + /// 自动修正项说明;无修正时为空列表。 + final List warnings; +} + /// DeepSeek 客户端。 class AiClient { AiClient._(); @@ -93,21 +151,36 @@ JSON 结构(协议 seqdiagram/1.2): 规则: 1. 时间只存于 cycle.durationMs(毫秒);角度为 0–360 度,0° 为 12 点钟方向、顺时针递增。 2. 每个动作 durationAngle > 0;startAngle + durationAngle 可以超过 360 表示跨循环。 -3. layer 从 0 开始,每个动作独占一层(圆周视图的一个同心圆环)。 +3. layer 表示**并行执行资源**(执行器 / 工位轨道),从 0 开始连续编号: + 同一时间段内并行执行的动作必须处于不同 layer;前后串行、时间不重叠的动作 + 应尽量复用同一 layer,避免层数过多(一般不超过 6 层)。 4. deps 为前置依赖数组,元素形如 { "fromId": "A1", "toId": "A2", "type": "FS", "offsetAngle": 0 }; type 取 FS(完成-启动)/ SS(起始-起始)/ FF / SF。 - 一个动作可以有**多条** deps(多输入),也可以被**多个**动作引用(多输出)。 + 一个动作可以有多条 deps(多输入),也可以被多个动作引用(多输出); + fromId / toId 必须引用 actions 中真实存在的动作 id,且不能指向自身。 5. 颜色从调色板循环取用:#4cc9f0, #7bd88f, #ffd166, #ff8a5c, #f472b6, #a78bfa, #38bdf8, #34d399。 6. 相位分区 phaseZones 用于标注工艺阶段,可重叠,允许结束角 > 360°。 -7. 只输出 JSON 本体。 +7. 动作命名简洁(不超过 8 个汉字);不要编造不存在的工位,stationId 必须引用 stations 中已有的 id。 +8. 只输出 JSON 本体,且必须是单个可直接 JSON 解析的对象。 '''; - /// 根据自然语言 [prompt] 生成项目。 + /// 根据自然语言 [prompt] 生成或修改项目(流式、可取消、带自动纠错)。 /// - /// 抛出 [AiException] 表示网络、鉴权或解析失败。 - static Future generate({ + /// - [base] 非空时进入「增量修改」模式:连同现有工程一起发送, + /// 要求模型输出修改后的完整 JSON(未涉及部分保持原样); + /// - [onProgress]:每收到一段增量内容回调一次(含思考 / 输出字符数与尝试次数); + /// - [cancelToken]:取消后立即中断请求并抛出「已取消」; + /// - 空闲超过 [idleTimeout] 无任何数据视为超时; + /// - 输出无法解析 / 校验失败时,把错误反馈给模型自动修复重试(最多 [maxRepairs] 次); + /// - 成功后返回 [AiResult](含结果清洗说明)。 + static Future generate({ required String prompt, required AiSettings settings, + Project? base, + void Function(AiProgress progress)? onProgress, + AiCancelToken? cancelToken, + Duration idleTimeout = const Duration(seconds: 180), + int maxRepairs = 2, }) async { if (settings.apiKey.trim().isEmpty) { throw AiException('请先填写 DeepSeek API Key'); @@ -116,46 +189,141 @@ JSON 结构(协议 seqdiagram/1.2): throw AiException('请输入自然语言描述'); } + final String baseJson = base == null ? '' : jsonEncode(base.toJson()); + final String firstUser = base == null + ? prompt.trim() + : '现有工程 JSON:\n$baseJson\n\n' + '修改要求:${prompt.trim()}\n\n' + '请在现有工程基础上按要求修改(增删改动作 / 相位 / 依赖等),' + '未涉及的部分保持原样,输出修改后的**完整** JSON。'; + + String? previousOutput; + String lastError = ''; + for (int attempt = 0; attempt <= maxRepairs; attempt++) { + if (cancelToken?.cancelled ?? false) throw AiException('已取消'); + final List> messages = >[ + {'role': 'system', 'content': _systemPrompt}, + {'role': 'user', 'content': firstUser}, + ]; + if (attempt > 0) { + String prev = previousOutput ?? ''; + if (prev.length > 8000) prev = prev.substring(prev.length - 8000); + messages.add({'role': 'assistant', 'content': prev}); + messages.add({ + 'role': 'user', + 'content': '你上次的输出无法解析为合法的时序图:$lastError\n' + '请修正后只输出完整的 JSON 本体(不要解释、不要 Markdown 代码块)。', + }); + } + try { + final String content = await _streamOnce( + messages: messages, + settings: settings, + attempt: attempt, + onProgress: onProgress, + cancelToken: cancelToken, + idleTimeout: idleTimeout, + ); + previousOutput = content; + final Map decoded = + jsonDecode(_extractJson(content)) as Map; + final Project project = Project.fromJson(decoded); + final (Project fixed, List warnings) = _sanitize(project); + if (fixed.actions.isEmpty) { + throw const FormatException('没有任何动作'); + } + return AiResult(fixed, warnings); + } on AiException { + rethrow; // 网络 / 鉴权 / 超时 / 取消等错误不重试 + } on FormatException catch (e) { + lastError = e.message; + if (attempt >= maxRepairs) { + throw AiException('模型输出无法解析为时序图:${e.message}'); + } + } catch (e) { + lastError = '$e'; + if (attempt >= maxRepairs) { + throw AiException('模型输出无法解析为时序图:$e'); + } + } + } + throw AiException('生成失败:$lastError'); + } + + /// 单次流式请求:返回模型输出的完整文本内容(不含思考内容)。 + static Future _streamOnce({ + required List> messages, + required AiSettings settings, + required int attempt, + void Function(AiProgress progress)? onProgress, + AiCancelToken? cancelToken, + required Duration idleTimeout, + }) async { final HttpClient client = HttpClient()..connectionTimeout = const Duration(seconds: 20); + cancelToken?.bindAbort(() => client.close(force: true)); try { final HttpClientRequest req = await client.postUrl(Uri.parse(endpoint)); req.headers.set(HttpHeaders.contentTypeHeader, 'application/json'); req.headers.set(HttpHeaders.authorizationHeader, 'Bearer ${settings.apiKey.trim()}'); req.write(jsonEncode({ 'model': settings.model, - 'messages': >[ - {'role': 'system', 'content': _systemPrompt}, - {'role': 'user', 'content': prompt.trim()}, - ], - 'stream': false, + 'messages': messages, + 'stream': true, 'temperature': 0.2, 'response_format': {'type': 'json_object'}, // 兼容支持推理强度的接口;不支持时会被忽略。 'reasoning_effort': settings.effort, })); final HttpClientResponse res = await req.close(); - final String text = await res.transform(utf8.decoder).join(); if (res.statusCode != 200) { + final String text = await res.transform(utf8.decoder).join(); throw AiException('接口返回 ${res.statusCode}:${_brief(text)}'); } - final Map json = jsonDecode(text) as Map; - final List choices = (json['choices'] as List?) ?? []; - if (choices.isEmpty) throw AiException('接口未返回内容'); - final Map msg = - ((choices.first as Map)['message'] as Map?) ?? {}; - final String content = (msg['content'] as String?) ?? ''; - if (content.trim().isEmpty) throw AiException('模型返回为空'); - final String cleaned = _extractJson(content); - try { - return Project.decode(cleaned); - } catch (e) { - throw AiException('模型输出无法解析为时序图:$e'); + final StringBuffer content = StringBuffer(); + final StringBuffer reasoning = StringBuffer(); + final Stream lines = + res.transform(utf8.decoder).transform(const LineSplitter()).timeout(idleTimeout); + await for (final String line in lines) { + if (cancelToken?.cancelled ?? false) throw AiException('已取消'); + if (!line.startsWith('data:')) continue; + final String payload = line.substring(5).trim(); + if (payload.isEmpty) continue; + if (payload == '[DONE]') break; + Map chunk; + try { + chunk = jsonDecode(payload) as Map; + } catch (_) { + continue; // 忽略无法解析的心跳 / 异常行 + } + final List choices = (chunk['choices'] as List?) ?? const []; + if (choices.isEmpty) continue; + final Map delta = + ((choices.first as Map)['delta'] as Map?) ?? + const {}; + final String piece = (delta['content'] as String?) ?? ''; + final String think = (delta['reasoning_content'] as String?) ?? ''; + if (piece.isNotEmpty) content.write(piece); + if (think.isNotEmpty) reasoning.write(think); + if (piece.isNotEmpty || think.isNotEmpty) { + onProgress?.call(AiProgress( + reasoningChars: reasoning.length, + contentChars: content.length, + attempt: attempt, + )); + } } + if (cancelToken?.cancelled ?? false) throw AiException('已取消'); + if (content.toString().trim().isEmpty) throw AiException('模型返回为空'); + return content.toString(); } on AiException { rethrow; + } on TimeoutException { + throw AiException('响应超时(${idleTimeout.inSeconds} 秒无数据),请检查网络后重试'); } on SocketException catch (e) { + if (cancelToken?.cancelled ?? false) throw AiException('已取消'); throw AiException('网络连接失败:${e.message}'); } on HttpException catch (e) { + if (cancelToken?.cancelled ?? false) throw AiException('已取消'); throw AiException('HTTP 错误:${e.message}'); } on FormatException catch (e) { throw AiException('响应格式错误:${e.message}'); @@ -164,6 +332,51 @@ JSON 结构(协议 seqdiagram/1.2): } } + /// 结果清洗:修正非法时长与越界角度、剔除指向不存在动作的依赖、归一化层号。 + /// + /// 返回修正后的项目与人类可读的修正说明(供状态栏提示)。 + static (Project, List) _sanitize(Project p) { + final Set ids = {for (final Action a in p.actions) a.id}; + int fixedDur = 0; + int droppedDeps = 0; + final List actions = []; + for (final Action a in p.actions) { + double start = a.startAngle; + double dur = a.durationAngle; + if (!start.isFinite || start < 0) start = 0; + if (start > 400) start = 400; + if (!dur.isFinite) dur = 0; + if (dur <= 0) { + dur = 5; + fixedDur++; + } else if (dur > 720) { + dur = 720; + fixedDur++; + } + final List deps = []; + for (final Dependency d in a.deps) { + if (d.fromId == a.id || !ids.contains(d.fromId) || !ids.contains(d.toId)) { + droppedDeps++; + continue; + } + deps.add(d); + } + actions.add(a.copyWith(startAngle: start, durationAngle: dur, deps: deps)); + } + // 层号归一化为连续的 0..N-1(保持相对顺序),避免稀疏层号造成空白轨道。 + final List layers = {for (final Action a in actions) a.layer}.toList()..sort(); + final Map remap = { + for (int i = 0; i < layers.length; i++) layers[i]: i, + }; + final List normalized = [ + for (final Action a in actions) a.copyWith(layer: remap[a.layer] ?? 0), + ]; + final List warnings = []; + if (fixedDur > 0) warnings.add('修正 $fixedDur 处非法时长'); + if (droppedDeps > 0) warnings.add('剔除 $droppedDeps 条无效依赖'); + return (p.copyWith(actions: normalized), warnings); + } + /// 从模型输出中剥离 Markdown 代码围栏并截取首个 JSON 对象。 static String _extractJson(String raw) { String t = raw.trim(); diff --git a/lib/ui/ai_dialog.dart b/lib/ui/ai_dialog.dart index 155edb2..a3abacd 100644 --- a/lib/ui/ai_dialog.dart +++ b/lib/ui/ai_dialog.dart @@ -1,17 +1,21 @@ /// AI 生成时序图对话框。 /// -/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)与推理强度 -/// (高 / 最高)→ 在较大的自然语言输入框中描述工艺流程 → 点击「生成」, -/// 由 [AiClient] 调用大模型并解析为 [Project],成功后载入工作台。 +/// 交互流程:填写 DeepSeek API Key → 选择模型(Flash / Pro)、推理强度 +/// (高 / 最高)与生成方式(新建工程 / 在当前工程上修改)→ 在较大的自然语言 +/// 输入框中描述工艺流程或修改要求 → 点击「生成」。 +/// +/// 生成过程为**流式**:实时显示已用时、思考与输出字符数,可随时取消; +/// 输出无法解析时自动让模型修复重试(最多两次)。 /// /// 安全:API Key 仅保存在内存(静态字段,便于本次会话内复用), /// 不写入工程文件,也不会被日志输出。 library; +import 'dart:async'; + import 'package:flutter/material.dart'; import '../ai/ai_client.dart'; -import '../model/models.dart'; import '../state/app_controller.dart'; import '../theme/tokens.dart'; import 'dialogs.dart'; @@ -45,6 +49,22 @@ class _AiGenerateDialogState extends State { 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(); @@ -54,32 +74,61 @@ class _AiGenerateDialogState extends State { @override void dispose() { + _ticker?.cancel(); _key.dispose(); _prompt.dispose(); super.dispose(); } Future _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 Project p = await AiClient.generate( + 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(p, dirty: true); - widget.controller.setStatus('AI 已生成时序图(${p.actions.length} 个动作)'); + 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; @@ -189,6 +238,27 @@ class _AiGenerateDialogState extends State { ), const SizedBox(height: 14), + // 生成方式:新建整图 / 在当前工程上修改(增量)。 + Row( + children: [ + 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: [ @@ -237,16 +307,70 @@ class _AiGenerateDialogState extends State { width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( - color: t.danger.withValues(alpha: 0.12), + color: _error == '已取消' ? t.panel2 : t.danger.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(8), - border: Border.all(color: t.danger.withValues(alpha: 0.5)), + 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) ...[ + 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: [ + Row( + children: [ + 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, + ), + ), + ], ), - child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 12, height: 1.5)), ), ], const SizedBox(height: 14), - // 操作按钮 + // 操作按钮:生成 ↔ 取消生成(流式过程中可随时中断)。 Row( children: [ Expanded( @@ -255,25 +379,37 @@ class _AiGenerateDialogState extends State { style: TextStyle(color: t.dim, fontSize: 11), ), ), - TextButton(onPressed: _busy ? null : () => Navigator.pop(context), child: const Text('取消')), - const SizedBox(width: 8), - FilledButton.icon( - onPressed: _busy ? null : _generate, - icon: _busy - ? const SizedBox( - width: 15, - height: 15, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : const Icon(Icons.auto_awesome, size: 16), - label: Text(_busy ? '生成中…' : '生成'), - style: FilledButton.styleFrom( - backgroundColor: t.accent2, - foregroundColor: Colors.white, - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), - padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), - ), + 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), + ), + ), ], ), ], @@ -301,4 +437,23 @@ class _AiGenerateDialogState extends State { ), ); } + + /// 生成方式分段按钮(新建工程 / 修改当前工程);生成中不可切换。 + 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)), + ), + ); + } } diff --git a/lib/ui/dialogs.dart b/lib/ui/dialogs.dart index 1692fa7..817a44e 100644 --- a/lib/ui/dialogs.dart +++ b/lib/ui/dialogs.dart @@ -2124,7 +2124,7 @@ class HelpDialog extends StatelessWidget { Text('时序图设计 · Sequence Diagram Studio', style: TextStyle(color: t.text, fontSize: 15, fontWeight: FontWeight.w700)), const SizedBox(height: 4), - Text('V1.0.9(${android ? '安卓版' : 'Windows 版'})', + Text('V1.1.0(${android ? '安卓版' : 'Windows 版'})', style: TextStyle(color: t.dim, fontSize: 12)), ], ), diff --git a/pubspec.yaml b/pubspec.yaml index b517b4a..77920d9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.9+10 +version: 1.1.0+11 environment: sdk: ^3.13.3