diff --git a/SOURCE-SHA256.json b/SOURCE-SHA256.json index d0192de..41f6eed 100644 --- a/SOURCE-SHA256.json +++ b/SOURCE-SHA256.json @@ -56,20 +56,20 @@ "serverbox/README.gpu-console.md": "9382da5e514c692c85cdbba18375689b45f09033bd8ba17f8db2c9b5226875a4", "serverbox/SOURCE.json": "db8f26cf434db5f91438decee35ae5e5367a4a7611ec3a992bdaaff6661b1f7f", "serverbox/lib/app.dart": "11e6ba26315e67706cafd9c0aeb8fbf9c3e86a2799d0f489d8ab3dc57cbc3303", - "serverbox/lib/core/gpu_queue/presentation.dart": "74bc53db1737c028b5f0f16a59776b8884f29369e8e6bf340ec8c886eebcec43", + "serverbox/lib/core/gpu_queue/presentation.dart": "325fdbf339b578bf9d5067a0eec33a6c680edeaa78b8c0929c3252a42838fe60", "serverbox/lib/core/gpu_queue/protocol.dart": "5e17ea93d9bafc7df9872ffd3b902d7cd8b2a6fc2fefcb0fa137e8a24e5f0e95", "serverbox/lib/core/utils/gpu_queue.dart": "d03bc0fb6b834f0b6b34e9c842d45290abb70eee52192d10744d643d6e78d3be", "serverbox/lib/core/utils/gpu_queue_theme.dart": "56f24afdb62cb6d19a405e0d04ed1af0834cb3b317ebd63b3c81fb836af0d860", - "serverbox/lib/view/page/gpu_queue/page.dart": "794a27f7de9ff79b3567c79a2e24e7d8ac2225a71893aad9e403b0ce8bf5c12c", - "serverbox/lib/view/page/gpu_queue/workspace.dart": "68fcf52b443137a414ed41ed94d112664b1ff01b5eede3f8b575907e70daefd9", + "serverbox/lib/view/page/gpu_queue/page.dart": "d045200ec56d8751c0516b65d332cfa54d7e9b3e699eb666b35b81259de0047c", + "serverbox/lib/view/page/gpu_queue/workspace.dart": "775c3091acc280569327c3f9f2234bb26d1ec4d8acfae7253773edb34bca6e6b", "serverbox/lib/view/page/overview/gpu.dart": "316680cf4887df41b7fbabee78d35c2925d6245bed45060fa6dd2e3a73fe4050", "serverbox/lib/view/page/server/detail/bar_actions.dart": "5e1e70040a6fe5e782a94691198f4311ada7196a44da240bf8f5fefe33b3281e", "serverbox/lib/view/page/setting/about.dart": "91f55cb7948bf3df042b56cf16cbfc2e4fc2816021f1157c59840d6090a1f591", "serverbox/lib/view/page/setting/entry.dart": "ba2458b4597053dfed03c774f014068dd193d45862a41c334fc5b44c48f5acd0", "serverbox/test/unit/app/gpu_queue_test.dart": "e3514fe355b58f3a86d1cb83ccff58129532d5da132013f76cfdcc9bfeb7e854", - "serverbox/test/unit/app/queue_presentation_test.dart": "cca2e944a9e71ea305647e094d506a62de4d53793c5054c8bab584545b1584f7", + "serverbox/test/unit/app/queue_presentation_test.dart": "bf1c73790b9947d7a50c6c17e336af528f434d4fed1287b0c6a72d8c101c96d2", "serverbox/test/unit/app/queue_protocol_test.dart": "f80ddb23f95e2f70b6068728cf4ee1151a8e0c86dc28ae60aa21708b0fb26ee5", - "serverbox/test/unit/app/queue_workspace_widget_test.dart": "2fa3fe900cbe57113651c951d69523d4671de41c261e708a064e76e5bb32b0f5", + "serverbox/test/unit/app/queue_workspace_widget_test.dart": "2ee524ec4bb7f95a4f94d6278155e9b1a14a103d5514709a0e9e8c849c95699b", "skills/inspire-queue/SKILL.md": "c8e1aacb4d38e79aa9e930e9e60c8db2147d4ea8a058996dd19e35b9a15b1161", "tests/browser_check.py": "f5885e5acf430749364699e81fdecf257906f898c971d39f837ae70811b14cd4", "tests/browser_monitor_check.py": "47c5a064bcd92dcab4d3f7f824e65134afb44e48e8313ed5a268ea5573df6c04", diff --git a/serverbox/lib/core/gpu_queue/presentation.dart b/serverbox/lib/core/gpu_queue/presentation.dart index 7953255..d871f2f 100644 --- a/serverbox/lib/core/gpu_queue/presentation.dart +++ b/serverbox/lib/core/gpu_queue/presentation.dart @@ -1,5 +1,45 @@ import 'package:server_box/core/gpu_queue/protocol.dart'; +enum QueueTaskAction { + start('开始运行'), + editMode('切回编辑模式'), + withdrawDraft('撤回草稿'), + removeFromQueue('移出队列'), + moveUp('队列向前移动'), + moveDown('队列向后移动'), + logs('查看实时日志'), + stop('停止任务'), + latestReady('前往最新待启动版本'), + close('确认异常结案'), + copyError('复制报错给 Agent 排查'), + latest('查看最新版本'), + copySummary('复制任务摘要'), + results('查看结果文件'), + directory('打开工作目录'), + deleteRecord('删除历史记录'); + + const QueueTaskAction(this.label); + final String label; +} + +class QueueTaskActionCardData { + const QueueTaskActionCardData({ + required this.conclusion, + this.detail, + this.reason, + this.primary, + this.secondary = const [], + this.versionId, + this.progress = const [], + }); + + final String conclusion; + final String? detail, reason, versionId; + final QueueTaskAction? primary; + final List secondary; + final List<({String label, double? fraction})> progress; +} + /// Human-readable queue data. Missing values stay missing, and historical GPU /// readings never become live metrics merely because an SSH session is open. abstract final class QueuePresentation { @@ -107,10 +147,17 @@ abstract final class QueuePresentation { static String taskUpdated(Map task) { final at = taskTime(task['updated_at']) ?? taskSortTime(task); if (at == null) return '时间未提供'; - final label = taskTime(task['updated_at']) != null ? '更新' - : at == taskTime(task['created_at']) ? '提交' : '活动'; + final label = taskTime(task['updated_at']) != null + ? '更新' + : at == taskTime(task['created_at']) + ? '提交' + : '活动'; + return '$label ${_taskTimestamp(at)}'; + } + + static String _taskTimestamp(DateTime at) { String two(int value) => value.toString().padLeft(2, '0'); - return '$label ${at.year}-${two(at.month)}-${two(at.day)} ' + return '${at.year}-${two(at.month)}-${two(at.day)} ' '${two(at.hour)}:${two(at.minute)}:${two(at.second)} UTC'; } @@ -119,7 +166,15 @@ abstract final class QueuePresentation { static const runningStates = {'running', 'starting', 'stopping'}; static const retiredDraftStates = {'superseded', 'withdrawn'}; - static bool reviewClosed(Map task) => task['review_closed'] == true; + static bool reviewClosed(Map task) { + final receipts = task['control_receipts']; + return task['review_closed'] == true || + receipts is List && + receipts.any( + (receipt) => + receipt is Map && receipt['outcome'] == 'review_closed', + ); + } static bool needsAttention(Map task) => !reviewClosed(task) && attentionStates.contains(task['state']); static bool canCleanup(Map task) => @@ -185,6 +240,208 @@ abstract final class QueuePresentation { }[state] ?? (state == null ? '等待执行' : '状态待核查'); + static String taskSummary(Map task) => + 'Inspire Queue 任务 ${task['id']}(版本 ${version(task)})\n' + '状态:${taskLabel(task)}\n' + '资源:${compactRequirements(task)}\n' + '${taskUpdated(task)}'; + + static QueueTaskActionCardData taskActionCard( + Map task, { + bool auto = false, + bool connected = true, + int? queueRank, + }) { + final state = task['state']; + final control = task['control_action']; + final action = control is Map ? control['action'] : null; + final phase = _text(task['phase']); + final latest = _text(task['latest_task_id']); + final latestReady = _text(task['latest_ready_id']); + const summary = QueueTaskAction.copySummary; + if (reviewClosed(task)) { + final successor = latestReady != task['id'] ? latestReady : null; + return QueueTaskActionCardData( + conclusion: '异常已结案,原任务和产物已保留。', + detail: nextAction(task), + primary: successor == null ? null : QueueTaskAction.latestReady, + versionId: successor, + secondary: [QueueTaskAction.logs, summary], + ); + } + switch (state) { + case 'ready': + return QueueTaskActionCardData( + conclusion: '准备就绪,点击开始后将复用或申请所需 GPU。', + detail: auto ? '当前正在自动监看。切回编辑模式后可手动开始。' : null, + primary: auto ? null : QueueTaskAction.start, + secondary: [ + if (auto) QueueTaskAction.editMode, + if (action == 'withdraw') QueueTaskAction.withdrawDraft, + ], + ); + case 'queued': + case 'waiting_gpu': + case 'checking_resources': + case 'dispatching': + final waiting = switch (state) { + 'waiting_gpu' => '正在等待满足要求的 GPU 资源。', + 'checking_resources' => '正在探测已有 GPU 并核对可用资源。', + 'dispatching' => '正在核对计算投放回执。', + _ => '已获启动授权,正在等待调度。', + }; + return QueueTaskActionCardData( + conclusion: state == 'queued' && queueRank != null + ? '当前排在第 $queueRank 位,等待调度。' + : phase ?? waiting, + detail: state == 'queued' && queueRank != null && phase != '等待执行' + ? phase + : null, + secondary: [ + if (action == 'withdraw') QueueTaskAction.removeFromQueue, + if (action == 'stop') QueueTaskAction.stop, + if (queueRank != null) ...[ + QueueTaskAction.moveUp, + QueueTaskAction.moveDown, + ], + ], + ); + case 'starting': + case 'running': + case 'stopping': + final progress = task['progress'] is Map + ? task['progress'] as Map + : const {}; + final names = task['steps'] is List ? task['steps'] as List : const []; + final records = task['step_records'] is List + ? task['step_records'] as List + : const []; + final running = records.indexWhere( + (record) => record is Map && record['state'] == 'running', + ); + final stepIndex = running >= 0 + ? running + : task['stage'] ?? progress['step_index']; + final name = + stepIndex is int && stepIndex >= 0 && stepIndex < names.length + ? _text(names[stepIndex]) + : null; + final counters = + progress['source'] == 'training_log' && + (stepIndex == null || progress['step_index'] == stepIndex) + ? [ + _taskProgress( + progress['epoch'], + progress['total_epochs'], + 'Epoch', + ), + _taskProgress( + progress['step'], + progress['total_steps'], + 'Step', + ), + ].nonNulls.toList() + : const <({String label, double? fraction})>[]; + final times = [ + taskTime(progress['updated_at']), + taskTime(task['phase_updated_at']), + taskSortTime(task), + ].nonNulls.toList()..sort(); + final updated = times.lastOrNull; + return QueueTaskActionCardData( + conclusion: switch (state) { + 'starting' => phase ?? '执行端正在核验环境并启动任务。', + 'stopping' => phase ?? '已请求停止,正在等待执行端确认。', + _ => name == null ? phase ?? '任务正在运行。' : '正在执行:$name', + }, + detail: [ + if (state == 'starting' && name != null) '下一步骤:$name', + if (state == 'running' && name != null && phase != null && + phase != '正在执行任务步骤') + phase, + if (!connected) '连接中断,显示上次快照。', + if (updated != null) '最近更新 ${_taskTimestamp(updated)}', + ].join('\n'), + progress: counters, + primary: QueueTaskAction.logs, + secondary: [ + if (action == 'stop') QueueTaskAction.stop, + if (action == 'close') QueueTaskAction.close, + ], + ); + case 'failed': + case 'interrupted': + case 'execution_unknown': + case 'blocked': + final unresolved = + state == 'execution_unknown' || + state == 'blocked' || + action == 'stop'; + final successor = latestReady != task['id'] ? latestReady : null; + return QueueTaskActionCardData( + conclusion: switch (state) { + 'failed' => '任务执行失败,后续步骤已停止。', + 'interrupted' => '任务执行已中断。', + _ => '执行回执待核查。', + }, + reason: _text(task['failureReason']) ?? phase, + detail: unresolved + ? '原执行可能仍占用 GPU,后续任务可能需要等待资源。' + : '这一版不会自动重跑,后续任务按队列调度。', + primary: successor != null + ? QueueTaskAction.latestReady + : action == 'close' + ? QueueTaskAction.close + : null, + versionId: successor, + secondary: [ + QueueTaskAction.copyError, + if (action == 'close' && successor != null) + QueueTaskAction.close, + if (action == 'stop') QueueTaskAction.stop, + ], + ); + case 'withdrawn': + case 'superseded': + final successor = latest != task['id'] ? latest : null; + return QueueTaskActionCardData( + conclusion: state == 'withdrawn' ? '草稿已撤回,未占用 GPU。' : '草稿已被新版本替代。', + primary: successor == null ? null : QueueTaskAction.latest, + versionId: successor, + secondary: [summary], + ); + case 'completed': + final elapsed = _text(task['elapsed']); + return QueueTaskActionCardData( + conclusion: '全部步骤已完成。', + detail: elapsed == null ? '总耗时未提供' : '总耗时 $elapsed', + primary: QueueTaskAction.results, + secondary: [QueueTaskAction.directory, QueueTaskAction.deleteRecord], + ); + default: + return QueueTaskActionCardData( + conclusion: nextAction(task), + secondary: [if (action == 'close') QueueTaskAction.close, summary], + ); + } + } + + static String? _text(Object? value) => + value is String && value.trim().isNotEmpty ? value.trim() : null; + + static ({String label, double? fraction})? _taskProgress( + Object? value, + Object? total, + String label, + ) { + final current = _number(value), count = _number(total); + if (current == null) return null; + if (count == null || count == 0 || current > count) { + return (label: '$label $current', fraction: null); + } + return (label: '$label $current / $count', fraction: current / count); + } + static DateTime? sampleTime(Map resource) { final at = _number(resource['telemetry']?['at']); if (at == null || at <= 0 || at > 8640000000000) return null; diff --git a/serverbox/lib/view/page/gpu_queue/page.dart b/serverbox/lib/view/page/gpu_queue/page.dart index d44ab97..547eca0 100644 --- a/serverbox/lib/view/page/gpu_queue/page.dart +++ b/serverbox/lib/view/page/gpu_queue/page.dart @@ -991,13 +991,7 @@ class _GpuQueuePageState extends ConsumerState bool wide, ) { setState(() { - if (_selected != task['id']) { - _detailTab = task['state'] == 'failed' - ? 1 - : task['state'] == 'completed' - ? 2 - : 0; - } + if (_selected != task['id']) _detailTab = 0; _selected = task['id']; }); if (!wide) { @@ -1028,9 +1022,21 @@ class _GpuQueuePageState extends ConsumerState .where((r) => r['id'] == QueueTarget.instance(task)) .firstOrNull; final enabled = queue.connected && !queue.acting && !queue.loading; - final retiredDraft = QueuePresentation.retiredDraftStates.contains(task['state']); + final state = task['state']; + final retiredDraft = QueuePresentation.retiredDraftStates.contains(state); + final pending = queue.tasks.where(_reorderable).toList(); + final queueIndex = pending.indexWhere((t) => t['id'] == task['id']); + final card = QueuePresentation.taskActionCard( + task, + auto: queue.auto, + connected: queue.connected, + queueRank: queueIndex < 0 ? null : queueIndex + 1, + ); final previous = task['previous_task_id']; final latest = task['latest_task_id']; + final successor = queue.tasks + .where((t) => t['id'] == card.versionId) + .firstOrNull; Widget versionLink(String label, Object id) { final linked = queue.tasks.where((t) => t['id'] == id).firstOrNull; final text = '$label · $id'; @@ -1040,11 +1046,11 @@ class _GpuQueuePageState extends ConsumerState child: Text(text), ); } + final control = task['control_action']; - final controlLabel = control is Map - ? (control['action'] == 'withdraw' && control['state'] == 'ready' - ? '撤回草稿' - : QueuePresentation.controlLabels[control['action']]) + final capabilities = queue.snapshot['capabilities']; + VoidCallback? confirm(String label) => enabled && control is Map + ? () => _confirmControl(queue, task, control, label) : null; final receipts = (task['control_receipts'] as List? ?? []).whereType(); final steps = (task['step_records'] as List? ?? []) @@ -1055,14 +1061,28 @@ class _GpuQueuePageState extends ConsumerState padding: const EdgeInsets.all(24), children: children, ); + void selectTab(int tab, StateSetter updateDetail) { + setState(() => _detailTab = tab); + updateDetail(() {}); + } + + final openDirectory = target == null || directory == null + ? null + : () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SftpPage( + args: SftpPageArgs(spi: target, initPath: directory), + ), + ), + ); + final openSuccessor = successor == null + ? null + : () => _openTask(successor, service, queue, servers, !mobile); return StatefulBuilder( builder: (context, updateDetail) => QueueDetailPane( task: task, tab: _detailTab, - onTab: (tab) { - setState(() => _detailTab = tab); - updateDetail(() {}); - }, + onTab: (tab) => selectTab(tab, updateDetail), onClose: () { if (mobile) { Navigator.pop(context); @@ -1074,76 +1094,88 @@ class _GpuQueuePageState extends ConsumerState index: _detailTab, children: [ page('overview', [ + QueueTaskActionCard( + data: card, + actions: { + QueueTaskAction.start: enabled && !queue.auto + ? () => _start(queue, task) + : null, + QueueTaskAction.editMode: () => queue.setAuto(false), + QueueTaskAction.withdrawDraft: confirm( + QueueTaskAction.withdrawDraft.label, + ), + QueueTaskAction.removeFromQueue: confirm( + QueueTaskAction.removeFromQueue.label, + ), + QueueTaskAction.moveUp: + enabled && !queue.auto && queueIndex > 0 + ? () => _move(queue, task, -1) + : null, + QueueTaskAction.moveDown: + enabled && + !queue.auto && + queueIndex >= 0 && + queueIndex < pending.length - 1 + ? () => _move(queue, task, 1) + : null, + QueueTaskAction.logs: () => selectTab(1, updateDetail), + QueueTaskAction.stop: confirm(QueueTaskAction.stop.label), + QueueTaskAction.close: confirm( + QueuePresentation.controlLabels['close']!, + ), + QueueTaskAction.latestReady: openSuccessor, + QueueTaskAction.latest: openSuccessor, + QueueTaskAction.copyError: () async { + final handoff = QueuePresentation.handoff(task); + final reason = card.reason; + await Clipboard.setData( + ClipboardData( + text: reason == null + ? handoff + : '$handoff\n\n报错:$reason', + ), + ); + _message('已复制报错与任务摘要'); + }, + QueueTaskAction.copySummary: () async { + await Clipboard.setData( + ClipboardData(text: QueuePresentation.taskSummary(task)), + ); + _message('已复制任务摘要'); + }, + QueueTaskAction.results: () => selectTab(2, updateDetail), + QueueTaskAction.directory: openDirectory, + QueueTaskAction.deleteRecord: + enabled && + !_deleting && + capabilities is Map && + capabilities['task_delete'] == true + ? () => _deleteRecord(queue, task) + : null, + }, + ), + const SizedBox(height: 16), SelectableText( - '${task['name']}\n任务 ID:${task['id']}\n授权:${task['approved_at'] ?? (retiredDraft ? '未授权' : '等待点击开始')}\n${task['description'] ?? ''}', + '任务 ID:${task['id']}\n授权:${task['approved_at'] ?? (state == 'ready' ? '等待点击开始' : '未记录授权')}\n${task['description'] ?? ''}', style: const TextStyle(fontSize: 12), ), - const SizedBox(height: 12), - Text(QueuePresentation.nextAction(task)), - if (latest != null) + if (previous != null || latest != null && latest != task['id'] && latest != card.versionId) Wrap( spacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [ if (previous != null) versionLink(task['version_relation'] == 'retry' ? '原失败任务' : '上一版本', previous), - versionLink(task['latest_ready_id'] != null ? '最新可启动版本' : '最新版本', latest), + if (latest != null && latest != task['id'] && latest != card.versionId) + versionLink('最新版本', latest), ], ), - TextButton.icon( - onPressed: () { Clipboard.setData(ClipboardData(text: QueuePresentation.handoff(task))); _message('已复制任务诊断摘要;不包含日志与文件路径'); }, - icon: const Icon(Icons.copy_outlined), label: const Text('复制给 Agent 排查'), - ), const SizedBox(height: 16), Text('申请资源需求', style: Theme.of(context).textTheme.titleMedium), SelectableText(QueuePresentation.requirements(task)), SelectableText('固定版本:${QueuePresentation.version(task)}'), - const SizedBox(height: 16), - Wrap( - spacing: 8, - runSpacing: 8, - children: [ - if (task['state'] == 'ready') - FilledButton( - onPressed: enabled && !queue.auto - ? () => _start(queue, task) - : null, - child: const Text('开始这一版任务'), - ), - if (control is Map && controlLabel != null) - OutlinedButton( - onPressed: enabled - ? () => _confirmControl(queue, task, control, controlLabel) - : null, - child: Text(controlLabel), - ), - if (_reorderable(task)) ...[ - IconButton( - tooltip: '队列向前移动', - onPressed: enabled && !queue.auto - ? () => _move(queue, task, -1) - : null, - icon: const Icon(Icons.arrow_upward), - ), - IconButton( - tooltip: '队列向后移动', - onPressed: enabled && !queue.auto - ? () => _move(queue, task, 1) - : null, - icon: const Icon(Icons.arrow_downward), - ), - ], - ], - ), - if (task['failureReason'] != null) - SelectableText( - '${task['failureReason']}', - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - if (task['phase'] != null && !_ended.contains(task['state'])) - Text('${task['phase']}'), - if (queue.snapshot['capabilities']?['task_control_receipts'] != true && - !_ended.contains(task['state']) && !retiredDraft) + if ((capabilities is! Map || capabilities['task_control_receipts'] != true) && + !_ended.contains(state) && !retiredDraft) const Text('撤单与停止确认需要更新个人任务服务。'), const Divider(height: 32), SelectableText( @@ -1188,21 +1220,11 @@ class _GpuQueuePageState extends ConsumerState ), child: const Text('SSH 终端'), ), - OutlinedButton( - onPressed: target == null || directory == null - ? null - : () => Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => SftpPage( - args: SftpPageArgs( - spi: target, - initPath: directory, - ), - ), - ), - ), - child: const Text('工作目录 / SFTP'), - ), + if (state != 'completed') + OutlinedButton( + onPressed: openDirectory, + child: const Text('工作目录 / SFTP'), + ), ], ), if (resource != null) diff --git a/serverbox/lib/view/page/gpu_queue/workspace.dart b/serverbox/lib/view/page/gpu_queue/workspace.dart index feb3b26..cff8b9a 100644 --- a/serverbox/lib/view/page/gpu_queue/workspace.dart +++ b/serverbox/lib/view/page/gpu_queue/workspace.dart @@ -74,11 +74,28 @@ class QueuePanel extends StatelessWidget { class QueueStatusBadge extends StatelessWidget { const QueueStatusBadge({super.key, required this.task}); final Map task; + + static IconData iconFor(Object? state) => switch (state) { + 'ready' => Icons.play_circle_outline, + 'queued' || 'waiting_gpu' => Icons.schedule, + 'checking_resources' => Icons.manage_search, + 'dispatching' => Icons.outbox_outlined, + 'starting' || 'running' => Icons.bolt, + 'stopping' || 'stopped' => Icons.stop_circle_outlined, + 'failed' || 'interrupted' => Icons.error_outline, + 'blocked' || 'execution_unknown' => Icons.warning_amber_rounded, + 'withdrawn' || 'cancelled' => Icons.cancel_outlined, + 'superseded' => Icons.history, + 'completed' => Icons.check_circle_outline, + _ => Icons.help_outline, + }; + @override Widget build(BuildContext context) { final colors = Theme.of(context).colorScheme; final failed = QueuePresentation.needsAttention(task); - final done = task['state'] == 'completed' || QueuePresentation.reviewClosed(task); + final closed = QueuePresentation.reviewClosed(task); + final done = task['state'] == 'completed' || closed; final color = failed ? colors.error : done @@ -88,13 +105,7 @@ class QueueStatusBadge extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Icon( - failed - ? Icons.error_outline - : done - ? Icons.check - : task['state'] == 'running' - ? Icons.play_circle_outline - : Icons.schedule, + closed ? Icons.check : iconFor(task['state']), size: 14, color: color, ), @@ -325,6 +336,97 @@ class QueueDetailPane extends StatelessWidget { ); } +class QueueTaskActionCard extends StatelessWidget { + const QueueTaskActionCard({ + super.key, + required this.data, + required this.actions, + }); + + final QueueTaskActionCardData data; + final Map actions; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final primary = data.primary; + return Material( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(data.conclusion, style: theme.textTheme.titleMedium), + if (data.reason case final reason?) ...[ + const SizedBox(height: 6), + Text( + reason, + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: theme.colorScheme.error), + ), + ], + for (final counter in data.progress) ...[ + const SizedBox(height: 8), + Text(counter.label, style: theme.textTheme.bodySmall), + if (counter.fraction case final fraction?) + LinearProgressIndicator( + value: fraction, + semanticsLabel: counter.label, + ), + ], + if (data.detail case final detail? when detail.isNotEmpty) ...[ + const SizedBox(height: 6), + Text(detail, style: theme.textTheme.bodySmall), + ], + if (primary != null || data.secondary.isNotEmpty) ...[ + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + if (primary != null) + FilledButton( + onPressed: actions[primary], + child: Text(primary.label), + ), + for (final action in data.secondary) + switch (action) { + QueueTaskAction.moveUp || + QueueTaskAction.moveDown => IconButton( + tooltip: action.label, + onPressed: actions[action], + icon: Icon( + action == QueueTaskAction.moveUp + ? Icons.arrow_upward + : Icons.arrow_downward, + ), + ), + _ => TextButton( + onPressed: actions[action], + style: + action == QueueTaskAction.stop || + action == QueueTaskAction.deleteRecord + ? TextButton.styleFrom( + foregroundColor: theme.colorScheme.error, + ) + : null, + child: Text(action.label), + ), + }, + ], + ), + ], + ], + ), + ), + ); + } +} + class QueueLogView extends StatelessWidget { const QueueLogView({super.key, required this.label, required this.text}); final String label, text; diff --git a/serverbox/test/unit/app/queue_presentation_test.dart b/serverbox/test/unit/app/queue_presentation_test.dart index 4dddec8..5993e2f 100644 --- a/serverbox/test/unit/app/queue_presentation_test.dart +++ b/serverbox/test/unit/app/queue_presentation_test.dart @@ -207,4 +207,174 @@ void main() { expect(QueuePresentation.stepStatus(null), '等待执行'); expect(QueuePresentation.stepStatus('new_internal_state'), '状态待核查'); }); + + test('the action card uses only the control offered by the server', () { + const id = 'GQ-0123456789abcdef'; + const nextId = 'GQ-fedcba9876543210'; + QueueTaskActionCardData card( + String state, { + String? control, + String? latest, + String? ready, + bool auto = false, + }) => QueuePresentation.taskActionCard( + { + 'id': id, + 'state': state, + if (control != null) 'control_action': {'action': control}, + 'latest_task_id': latest, + 'latest_ready_id': ready, + }, + auto: auto, + queueRank: state == 'queued' ? 2 : null, + ); + + expect(card('ready').primary, QueueTaskAction.start); + expect(card('ready').secondary, isEmpty); + final manual = card('ready', control: 'withdraw', auto: true); + expect(manual.primary, isNull); + expect(manual.secondary, [ + QueueTaskAction.editMode, + QueueTaskAction.withdrawDraft, + ]); + final queued = card('queued', control: 'withdraw'); + expect(queued.conclusion, contains('第 2 位')); + expect(queued.primary, isNull); + expect(queued.secondary, [ + QueueTaskAction.removeFromQueue, + QueueTaskAction.moveUp, + QueueTaskAction.moveDown, + ]); + for (final state in ['waiting_gpu', 'checking_resources']) { + expect(card(state, control: 'withdraw').secondary, [ + QueueTaskAction.removeFromQueue, + ]); + } + expect(card('dispatching', control: 'stop').secondary, [ + QueueTaskAction.stop, + ]); + for (final state in ['starting', 'running', 'stopping']) { + expect(card(state).primary, QueueTaskAction.logs); + } + expect(card('running', control: 'stop').secondary, [QueueTaskAction.stop]); + expect(card('stopping', control: 'close').secondary, [ + QueueTaskAction.close, + ]); + for (final state in [ + 'failed', + 'interrupted', + 'execution_unknown', + 'blocked', + ]) { + expect(card(state).primary, isNull); + expect(card(state).secondary, [QueueTaskAction.copyError]); + final close = card(state, control: 'close'); + expect(close.primary, QueueTaskAction.close); + expect(close.secondary, [QueueTaskAction.copyError]); + final retry = card(state, control: 'close', ready: nextId, latest: id); + expect(retry.primary, QueueTaskAction.latestReady); + expect(retry.versionId, nextId); + expect(retry.secondary, [ + QueueTaskAction.copyError, + QueueTaskAction.close, + ]); + } + expect( + card('execution_unknown', control: 'stop').detail, + contains('可能仍占用 GPU'), + ); + expect( + card('failed', control: 'close', ready: id).primary, + QueueTaskAction.close, + ); + for (final state in ['withdrawn', 'superseded']) { + expect(card(state, latest: id).primary, isNull); + expect(card(state).secondary, [QueueTaskAction.copySummary]); + final successor = card(state, latest: nextId); + expect(successor.primary, QueueTaskAction.latest); + expect(successor.versionId, nextId); + expect(successor.secondary, [QueueTaskAction.copySummary]); + } + expect(card('completed').primary, QueueTaskAction.results); + expect(card('completed').secondary, [ + QueueTaskAction.directory, + QueueTaskAction.deleteRecord, + ]); + }); + + test('closed exceptions keep their archive status and recorded actions', () { + const nextId = 'GQ-fedcba9876543210'; + for (final task in [ + {'state': 'interrupted', 'review_closed': true}, + { + 'state': 'stopped', + 'control_receipts': [{'outcome': 'review_closed'}], + }, + ]) { + expect(QueuePresentation.taskLabel(task), '已异常结案'); + expect(QueuePresentation.canCleanup(task), isTrue); + expect(QueuePresentation.needsAttention(task), isFalse); + expect(QueuePresentation.taskSummary(task), contains('已异常结案')); + final card = QueuePresentation.taskActionCard({ + ...task, + 'latest_ready_id': nextId, + }); + expect(card.conclusion, contains('异常已结案')); + expect(card.primary, QueueTaskAction.latestReady); + expect(card.versionId, nextId); + expect(card.secondary, [QueueTaskAction.logs, QueueTaskAction.copySummary]); + } + }); + + test( + 'the action card uses queue phases, matching live counters and reported elapsed time', + () { + final waiting = QueuePresentation.taskActionCard({ + 'state': 'waiting_gpu', + 'phase': '等待前序任务释放资源。', + }); + expect(waiting.conclusion, '等待前序任务释放资源。'); + final running = { + 'state': 'running', + 'stage': 0, + 'steps': ['模型训练', '整理结果'], + 'phase_updated_at': '2026-10-24T12:01:00Z', + 'progress': { + 'source': 'training_log', + 'step_index': 0, + 'epoch': 2.5, + 'step': 25, + 'total_steps': 100, + 'updated_at': '2026-10-24T12:02:00Z', + }, + }; + final live = QueuePresentation.taskActionCard(running); + expect(live.conclusion, '正在执行:模型训练'); + expect(live.detail, contains('12:02:00 UTC')); + expect(live.progress, [ + (label: 'Epoch 2.5', fraction: null), + (label: 'Step 25 / 100', fraction: 0.25), + ]); + final later = QueuePresentation.taskActionCard({...running, 'stage': 1}); + expect(later.conclusion, '正在执行:整理结果'); + expect(later.progress, isEmpty); + final cached = QueuePresentation.taskActionCard( + running, + connected: false, + ); + expect(cached.detail, contains('上次快照')); + final archived = QueuePresentation.taskActionCard({ + ...running, + 'progress': {...running['progress'], 'source': 'archived_training_log'}, + }); + expect(archived.progress, isEmpty); + expect( + QueuePresentation.taskActionCard({ + 'state': 'completed', + 'elapsed': '18 分钟', + }).detail, + '总耗时 18 分钟', + ); + }, + ); } diff --git a/serverbox/test/unit/app/queue_workspace_widget_test.dart b/serverbox/test/unit/app/queue_workspace_widget_test.dart index 3dbf6f8..60b746f 100644 --- a/serverbox/test/unit/app/queue_workspace_widget_test.dart +++ b/serverbox/test/unit/app/queue_workspace_widget_test.dart @@ -2,6 +2,7 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:material_ui/material_ui.dart'; +import 'package:server_box/core/gpu_queue/presentation.dart'; import 'package:server_box/core/utils/gpu_queue_theme.dart'; import 'package:server_box/view/page/gpu_queue/swipe_delete.dart'; import 'package:server_box/view/page/gpu_queue/workspace.dart'; @@ -326,6 +327,220 @@ void main() { }, ); + testWidgets( + 'detail switches states with one filled action and distinct icons', + (tester) async { + const id = 'GQ-0123456789abcdef'; + const nextId = 'GQ-fedcba9876543210'; + final cases = + < + ({ + String state, + String? control, + String? next, + String? primary, + String secondary, + IconData icon, + }) + >[ + ( + state: 'ready', + control: 'withdraw', + next: null, + primary: '开始运行', + secondary: '撤回草稿', + icon: Icons.play_circle_outline, + ), + ( + state: 'queued', + control: 'withdraw', + next: null, + primary: null, + secondary: '移出队列', + icon: Icons.schedule, + ), + ( + state: 'running', + control: 'stop', + next: null, + primary: '查看实时日志', + secondary: '停止任务', + icon: Icons.bolt, + ), + ( + state: 'failed', + control: 'close', + next: nextId, + primary: '前往最新待启动版本', + secondary: '复制报错给 Agent 排查', + icon: Icons.error_outline, + ), + ( + state: 'execution_unknown', + control: 'close', + next: null, + primary: '确认异常结案', + secondary: '复制报错给 Agent 排查', + icon: Icons.warning_amber_rounded, + ), + ( + state: 'withdrawn', + control: null, + next: null, + primary: null, + secondary: '复制任务摘要', + icon: Icons.cancel_outlined, + ), + ( + state: 'withdrawn', + control: null, + next: nextId, + primary: '查看最新版本', + secondary: '复制任务摘要', + icon: Icons.cancel_outlined, + ), + ( + state: 'superseded', + control: null, + next: nextId, + primary: '查看最新版本', + secondary: '复制任务摘要', + icon: Icons.history, + ), + ( + state: 'completed', + control: null, + next: null, + primary: '查看结果文件', + secondary: '打开工作目录', + icon: Icons.check_circle_outline, + ), + ]; + var current = cases.first; + QueueTaskAction? tapped; + late StateSetter change; + await show( + tester, + StatefulBuilder( + builder: (context, update) { + change = update; + final record = { + 'id': id, + 'state': current.state, + 'name': '示例任务', + if (current.control != null) + 'control_action': {'action': current.control}, + if (current.next != null) 'latest_task_id': current.next, + if (current.state == 'failed') 'latest_ready_id': current.next, + if (current.state == 'failed') 'failureReason': '示例报错内容' * 160, + if (current.state == 'running') + 'progress': { + 'source': 'training_log', + 'step_index': 0, + 'step': 25, + 'total_steps': 100, + }, + }; + return QueueDetailPane( + task: record, + tab: 0, + onTab: (_) {}, + onClose: () {}, + child: ListView( + children: [ + QueueTaskActionCard( + data: QueuePresentation.taskActionCard(record), + actions: { + for (final action in QueueTaskAction.values) + action: () => tapped = action, + }, + ), + ], + ), + ); + }, + ), + size: const Size(416, 640), + scale: 1.5, + ); + + for (final entry in cases) { + change(() => current = entry); + await tester.pumpAndSettle(); + expect(find.byIcon(entry.icon), findsOneWidget, reason: entry.state); + expect( + find.byType(FilledButton), + entry.primary == null ? findsNothing : findsOneWidget, + ); + if (entry.primary case final label?) { + final button = find.widgetWithText(FilledButton, label); + if (entry.state == 'failed') { + expect(button.hitTestable(), findsOneWidget); + } + await tester.ensureVisible(button); + await tester.tap(button); + expect(tapped?.label, label); + } + expect( + find.widgetWithText(TextButton, entry.secondary), + findsOneWidget, + ); + if (entry.state == 'running') { + expect( + tester + .widget( + find.byType(LinearProgressIndicator), + ) + .value, + 0.25, + ); + final stop = tester.widget( + find.widgetWithText(TextButton, '停止任务'), + ); + expect( + stop.style?.foregroundColor?.resolve({}), + Theme.of( + tester.element(find.byType(QueueTaskActionCard)), + ).colorScheme.error, + ); + } + if (entry.state == 'withdrawn' || entry.state == 'superseded') { + expect(find.textContaining('Agent'), findsNothing); + } + expect(tester.takeException(), isNull); + } + }, + ); + + testWidgets('auto monitoring switches to edit without activating start', ( + tester, + ) async { + final draft = { + 'state': 'ready', + 'control_action': {'action': 'withdraw'}, + }; + var auto = true, starts = 0; + await show( + tester, + StatefulBuilder( + builder: (context, update) => QueueTaskActionCard( + data: QueuePresentation.taskActionCard(draft, auto: auto), + actions: { + QueueTaskAction.editMode: () => update(() => auto = false), + QueueTaskAction.start: () => starts++, + }, + ), + ), + ); + expect(find.textContaining('当前正在自动监看'), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + await tester.tap(find.text('切回编辑模式')); + await tester.pumpAndSettle(); + expect(starts, 0); + await tester.tap(find.widgetWithText(FilledButton, '开始运行')); + expect(starts, 1); + }); + testWidgets( 'poll rebuild preserves focus, selection and scroll and scales task rows', (tester) async {