diff --git a/PLAN.md b/PLAN.md index 4d6201f..f11ca79 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,30 @@ --- +## 0.4.8 项目图标与聊天图标(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 元数据 | `refreshProjects` 同时读 `/api/config/settings?surface=mobile` 的 `projects`,把 label / icon / color / iconBackground / iconImage 按路径合并到 `/api/project` 的条目上(自定义 data dir、Windows 大小写/分隔符都按路径匹配) | +| 项目图标 | 聊天组改用聊天气泡图标;项目组、项目选择器、草稿的项目 chip 统一用 `ProjectIcon`:OpenChamber 的 46 个 icon key 映射到 Material 图标,`color` 支持 hex 与旧主题 key(primary/error/comment/keyword/string/…),无自定义图标时显示对应颜色的图标/文件夹 | +| 自定义图标 | `iconImage` 存在时经 `GET /api/projects//icon?theme=…&iconColor=…` 取图(带认证,走 Transport/Relay);SVG 用 `flutter_svg` 渲染,PNG/favicon 用 `Image.memory`;有 `iconBackground` 时加圆角底色;加载失败回退字形,按 theme+updatedAt 缓存 | +| 测试 | 现有 46 项全过;模拟器上确认聊天组是气泡、项目组带各自的颜色/图标、选择器与草稿 chip 一致 | +| 版本 | **0.4.8(code 408)** | + +--- + +## 0.4.7 聊天分组与「聊天」新建目标(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 聊天分组 | 连接后读 `GET /api/fs/home` 的 `chatsRoot` / `canonicalChatsRoot` / 旧版 `.config/openchamber/chats`,所有位于这些根下的会话(`chats/<日期>/session-…`)合并成一个「聊天」组;修复此前按目录 leaf 分组、每个聊天各显示成 `session-xxxxx` 的问题。自定义 data dir、Windows 分隔符/盘符大小写都按路径边界匹配 | +| 新建目标 | 新会话的项目选择器新增「聊天」:选择后草稿 chip 显示聊天图标和「聊天」;首次发送时先在 `chatsRoot/YYYY-MM-DD/session-` 建目录(`POST /api/fs/mkdir`),再在该目录创建会话。已有聊天里点新会话会得到一个新的聊天目录,不会复用旧的 | +| 侧栏 | 聊天组的「+」提示「新建聊天」,直接打开以聊天为目标的草稿;项目选择器不再把聊天目录当作项目列出 | +| 测试 | `test/paths_test.dart` 增加聊天根边界(POSIX/Windows、`chats-other` 不误判);`test/sidebar_rows_test.dart` 增加多个聊天目录合并为唯一「聊天」组、不出现 `session-xxxxx` 的断言;本地服务器上用 curl 验证了在 chatsRoot 下 mkdir + 建会话 + 删除 | +| 版本 | **0.4.7(code 407)** | + +--- + ## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index ba53689..8817a52 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.4.6 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.4.8 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link over the OpenChamber private relay with end-to-end encryption; the pairing link is pasted or scanned with the camera), session list with search and live @@ -22,7 +22,11 @@ remembers them per connection and directory: reopening after an app restart attaches to the shells the server still holds instead of starting new ones. The panel is a tab row with its own close button, and each tab has its own header row. Starting a session opens a draft that only creates the session on the first send; the session list is -grouped by project with date captions, pins, archive and swipe actions. The +grouped by project with date captions, pins, archive and swipe actions; the +server's managed chat folders are one 聊天 group, and a new session can target +聊天 instead of a project. Project rows use the icon and colour chosen in +OpenChamber (including an uploaded/auto icon image), and the chat group has a +chat icon. The composer folds to one line when unfocused (or when the keyboard is dismissed) and opens into two rows on focus, as in dsh-Go: the model and its thinking level form one pill, the Build/Plan mode a separate chip (picked from a sheet). A diff --git a/lib/api/client.dart b/lib/api/client.dart index 9b37849..1aa3792 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -153,6 +153,35 @@ class Client { ]; } + /// The server's home and chats root. Sessions filed under a chats root are + /// the "聊天" group, not a project; the root can be relocated away from the + /// home config directory, so it must come from the server. + Future fsHome() async { + final r = await _json('GET', '/api/fs/home'); + return FsHomeInfo.fromJson(r); + } + + /// The project's chosen/auto icon image. [projectId] is the OpenChamber + /// settings id; SVG icons are recoloured by the server for [theme] and + /// [iconColor]. + Future projectIconBytes(String projectId, + {String? theme, String? iconColor}) async { + try { + final res = await _request( + 'GET', '/api/projects/${Uri.encodeComponent(projectId)}/icon', + query: { + if (theme != null && theme.isNotEmpty) 'theme': theme, + if (iconColor != null && iconColor.isNotEmpty) + 'iconColor': iconColor, + }); + if (res.statusCode != 200) return null; + final bytes = await res.collect(); + return bytes.isEmpty ? null : Uint8List.fromList(bytes); + } catch (_) { + return null; + } + } + Future deleteSession(String id) async { await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}'); } diff --git a/lib/api/models.dart b/lib/api/models.dart index 39726e2..66bac40 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -143,6 +143,32 @@ class Session { ); } +/// The server's home and managed chats roots (`GET /api/fs/home`). +class FsHomeInfo { + final String home; + final String chatsRoot; + final String? canonicalChatsRoot; + final String? canonicalLegacyChatsRoot; + + const FsHomeInfo({ + required this.home, + required this.chatsRoot, + this.canonicalChatsRoot, + this.canonicalLegacyChatsRoot, + }); + + factory FsHomeInfo.fromJson(Map j) { + String? nonEmpty(Object? value) => + value is String && value.trim().isNotEmpty ? value.trim() : null; + return FsHomeInfo( + home: nonEmpty(j['home']) ?? '', + chatsRoot: nonEmpty(j['chatsRoot']) ?? '', + canonicalChatsRoot: nonEmpty(j['canonicalChatsRoot']), + canonicalLegacyChatsRoot: nonEmpty(j['canonicalLegacyChatsRoot']), + ); + } +} + /// A project the server knows: a checkout (or chat folder) an agent can work /// in. [canonical] is the directory a session there carries. class ProjectInfo { @@ -151,11 +177,26 @@ class ProjectInfo { final String name; final String vcs; + /// The OpenChamber settings row this project was decorated from. The icon + /// endpoint keys on this id, not the opencode project id. + final String metaId; + final String icon; + final String color; + final String iconBackground; + final String iconImageMime; + final int iconImageUpdatedAt; + const ProjectInfo({ required this.id, required this.canonical, this.name = '', this.vcs = '', + this.metaId = '', + this.icon = '', + this.color = '', + this.iconBackground = '', + this.iconImageMime = '', + this.iconImageUpdatedAt = 0, }); factory ProjectInfo.fromJson(Map j) => ProjectInfo( @@ -165,6 +206,36 @@ class ProjectInfo { vcs: j['vcs'] as String? ?? '', ); + bool get hasIconImage => metaId.isNotEmpty && iconImageUpdatedAt > 0; + + /// Decorates the opencode project with its OpenChamber settings row: the + /// operator's label, icon key, colour and uploaded/auto icon image. + ProjectInfo withMeta(Map? meta) { + if (meta == null) return this; + String text(Object? value) => value is String ? value.trim() : ''; + final label = text(meta['label']); + final image = meta['iconImage']; + var mime = ''; + var updatedAt = 0; + if (image is Map) { + mime = text(image['mime']); + final updated = image['updatedAt']; + if (updated is num) updatedAt = updated.toInt(); + } + return ProjectInfo( + id: id, + canonical: canonical, + name: label.isNotEmpty ? label : name, + vcs: vcs, + metaId: text(meta['id']), + icon: text(meta['icon']), + color: text(meta['color']), + iconBackground: text(meta['iconBackground']), + iconImageMime: mime, + iconImageUpdatedAt: updatedAt, + ); + } + String get label { if (name.trim().isNotEmpty) return name.trim(); return pathLeaf(canonical); @@ -184,6 +255,19 @@ String pathLeaf(String path) { String slashPath(String path) => path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), ''); +/// Whether [directory] is [root] or inside it. Separators are unified and a +/// Windows drive path compares case-insensitively, as [samePath] does. +bool isUnderDirectory(String directory, String root) { + final d = slashPath(directory); + final r = slashPath(root); + if (d.isEmpty || r.isEmpty) return false; + final windows = RegExp(r'^[A-Za-z]:').hasMatch(d) || + RegExp(r'^[A-Za-z]:').hasMatch(r); + final dd = windows ? d.toLowerCase() : d; + final rr = windows ? r.toLowerCase() : r; + return dd == rr || dd.startsWith('$rr/'); +} + /// Whether two directory paths name the same place. Separators are unified; /// a drive-letter path compares case-insensitively, as Windows does. bool samePath(String a, String b) { diff --git a/lib/screens/new_session_screen.dart b/lib/screens/new_session_screen.dart index 0e1c61e..58058f0 100644 --- a/lib/screens/new_session_screen.dart +++ b/lib/screens/new_session_screen.dart @@ -10,6 +10,7 @@ import '../widgets/composer_attachment.dart'; import '../widgets/composer_box.dart'; import '../widgets/model_controls.dart'; import '../widgets/pet_sprite.dart'; +import '../widgets/project_icon.dart'; import '../widgets/slash_palette.dart'; import 'files_panel.dart'; @@ -280,6 +281,7 @@ class _NewSessionScreenState extends State { Widget _projectChip(SessionDraft draft) { final theme = Theme.of(context); + final isChat = draft.directory == AppState.chatTarget; final label = widget.app.projectLabelFor(draft.directory); return InkWell( borderRadius: BorderRadius.circular(18), @@ -289,8 +291,12 @@ class _NewSessionScreenState extends State { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Icon(Icons.folder_outlined, - size: 15, color: theme.hintColor), + ProjectIcon( + app: widget.app, + project: isChat ? null : widget.app.projectFor(draft.directory), + chat: isChat, + size: 15, + ), const SizedBox(width: 5), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 170), @@ -455,7 +461,7 @@ class _NewSessionScreenState extends State { Future _pickProject() async { final app = widget.app; - await app.refreshProjects(); + await Future.wait([app.refreshProjects(), app.refreshFsHome()]); if (!mounted) return; final draft = app.draft; if (draft == null) return; @@ -479,14 +485,29 @@ class _NewSessionScreenState extends State { child: ListView( controller: controller, children: [ + ListTile( + dense: true, + leading: ProjectIcon( + app: widget.app, chat: true, size: 20), + title: const Text('聊天'), + subtitle: const Text('不关联项目,保存在 OpenChamber 的聊天目录'), + trailing: draft.directory == AppState.chatTarget + ? Icon(Icons.check, + size: 18, + color: Theme.of(context).colorScheme.primary) + : null, + onTap: () { + app.updateDraftTarget(AppState.chatTarget); + _slashLoaded = false; + _slashItems = []; + Navigator.pop(context); + }, + ), for (final project in projects) ListTile( dense: true, - leading: Icon( - project.vcs.isNotEmpty - ? Icons.account_tree_outlined - : Icons.folder_outlined, - size: 20), + leading: + ProjectIcon(app: widget.app, project: project, size: 20), title: Text(project.label, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text(project.canonical, @@ -525,7 +546,7 @@ class _NewSessionScreenState extends State { final byPath = {}; for (final project in projects) { if (project.canonical.isEmpty) continue; - if (project.canonical.contains('/.config/openchamber/')) continue; + if (widget.app.isChatDirectory(project.canonical)) continue; final existing = byPath[project.canonical]; if (existing == null || (existing.vcs.isEmpty && project.vcs.isNotEmpty)) { diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index 1d6d6ff..c1a5cde 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -6,6 +6,7 @@ import 'package:flutter_slidable/flutter_slidable.dart'; import '../api/models.dart'; import '../state.dart'; +import '../widgets/project_icon.dart'; import 'servers_screen.dart'; import 'settings_screen.dart'; @@ -248,19 +249,13 @@ class _SessionListPaneState extends State { // --------------------------------------------------------------- groups - bool _isChatDirectory(String directory) => - directory.contains('/.config/openchamber/chats'); - - String _groupLabel(String key) => - key == '\u0000chats' ? '聊天' : _app.projectLabelFor(key); - List<_SessionGroup> _groups(List sessions) { final map = >{}; for (final session in sessions) { // Group on a separator-normalised key so a Windows server's mix of // `\` and `/` does not split one project into two. - final key = _isChatDirectory(session.directory) - ? '\u0000chats' + final key = _app.isChatDirectory(session.directory) + ? AppState.chatTarget : slashPath(session.directory); map.putIfAbsent(key, () => []).add(session); } @@ -268,9 +263,13 @@ class _SessionListPaneState extends State { for (final entry in map.entries) _SessionGroup( key: entry.key, - label: _groupLabel(entry.value.first.directory), + label: entry.key == AppState.chatTarget + ? '聊天' + : _app.projectLabelFor(entry.value.first.directory), // The first session's own path: the server knows that spelling. - path: entry.key == '\u0000chats' ? '' : entry.value.first.directory, + path: entry.key == AppState.chatTarget + ? '' + : entry.value.first.directory, sessions: entry.value ..sort((a, b) => b.updated.compareTo(a.updated)), ), @@ -320,7 +319,14 @@ class _SessionListPaneState extends State { Icon(collapsed ? Icons.chevron_right : Icons.expand_more, size: 18, color: scheme.onSurfaceVariant), const SizedBox(width: 2), - Icon(Icons.folder_outlined, size: 16, color: scheme.primary), + ProjectIcon( + app: _app, + project: group.key == AppState.chatTarget + ? null + : _app.projectFor(group.path), + chat: group.key == AppState.chatTarget, + size: 16, + ), ], ), title: Text( @@ -349,8 +355,11 @@ class _SessionListPaneState extends State { child: IconButton( icon: const Icon(Icons.add, size: 20), padding: EdgeInsets.zero, - tooltip: '在此项目新会话', - onPressed: () => _newSession(directory: group.path), + tooltip: group.key == AppState.chatTarget ? '新建聊天' : '在此项目新会话', + onPressed: () => _newSession( + directory: group.key == AppState.chatTarget + ? AppState.chatTarget + : group.path), ), ), onTap: () => setState(() { diff --git a/lib/state.dart b/lib/state.dart index 2731726..ea2ad26 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -5,6 +5,7 @@ library; import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:flutter/foundation.dart'; @@ -106,6 +107,15 @@ class AppState extends ChangeNotifier { /// group headers. List projects = []; + /// The "聊天" target of a new-session draft. It is not a path: the first + /// send creates a fresh directory under the server's chats root. + static const chatTarget = '\u0000chats'; + + /// The server's chats root and the aliases it may appear under (canonical, + /// legacy `.config` path). Sessions below these are the sidebar's 聊天 group. + String? chatsRoot; + List chatRoots = []; + /// The unsent new-session draft, kept in memory. Null when there is none. SessionDraft? draft; bool sendingDraft = false; @@ -428,6 +438,7 @@ class AppState extends ChangeNotifier { _startStream(); refreshSessions(); refreshProjects(); + refreshFsHome(); refreshActive(); refreshPerms(); refreshModels(); @@ -452,6 +463,9 @@ class AppState extends ChangeNotifier { sendingDraft = false; sessions = []; projects = []; + chatsRoot = null; + chatRoots = []; + _projectIcons.clear(); archivedSessions = []; archivedLoaded = false; _sessionsNext = null; @@ -510,11 +524,57 @@ class AppState extends ChangeNotifier { final cl = client; if (cl == null) return; try { - projects = await cl.listProjects(); + final list = await cl.listProjects(); + // The settings document carries the operator's label, icon key, colour + // and icon image; /api/project only knows the checkout itself. + final byPath = >{}; + try { + final settings = await cl.settings(); + final rows = settings['projects']; + if (rows is List) { + for (final row in rows) { + if (row is! Map) continue; + final path = row['path']; + if (path is! String || path.trim().isEmpty) continue; + final meta = Map.from(row); + final key = slashPath(path); + byPath[key] = meta; + byPath[key.toLowerCase()] = meta; + } + } + } catch (_) {} + projects = [ + for (final project in list) + project.withMeta(byPath[slashPath(project.canonical)] ?? + byPath[slashPath(project.canonical).toLowerCase()]), + ]; notifyListeners(); } catch (_) {} } + final Map> _projectIcons = {}; + + /// A project's icon image, fetched once per theme/colour/version. Null when + /// the project has no image or the server does not serve one. + Future projectIcon(ProjectInfo project, + {required bool dark, required String iconColor}) { + if (!project.hasIconImage) return Future.value(null); + final key = '${project.metaId}|${project.iconImageUpdatedAt}|' + '${dark ? 'dark' : 'light'}|$iconColor'; + final cached = _projectIcons[key]; + if (cached != null) return cached; + final cl = client; + final future = cl == null + ? Future.value(null) + : cl.projectIconBytes(project.metaId, + theme: dark ? 'dark' : 'light', iconColor: iconColor); + _projectIcons[key] = future; + future.then((bytes) { + if (bytes == null) _projectIcons.remove(key); + }); + return future; + } + /// Loads the next (older) page of the session list. Future loadMoreSessions() async { final cl = client; @@ -611,6 +671,7 @@ class AppState extends ChangeNotifier { } String projectLabelFor(String directory) { + if (directory == chatTarget || isChatDirectory(directory)) return '聊天'; if (directory.isEmpty) return ''; for (final project in projects) { if (samePath(project.canonical, directory)) return project.label; @@ -618,6 +679,63 @@ class AppState extends ChangeNotifier { return pathLeaf(directory); } + /// Whether [directory] is one of the server's managed chat folders. The + /// chats root can be relocated away from the home config directory, so it + /// comes from `/api/fs/home`; before that answer the default layout is still + /// recognised. + bool isChatDirectory(String directory) { + if (directory.isEmpty) return false; + if (directory == chatTarget) return true; + for (final root in chatRoots) { + if (isUnderDirectory(directory, root)) return true; + } + return slashPath(directory).contains('/.config/openchamber/chats/'); + } + + Future refreshFsHome() async { + final cl = client; + if (cl == null) return; + try { + final info = await cl.fsHome(); + if (client != cl) return; + final roots = {}; + void add(String? value) { + if (value != null && value.trim().isNotEmpty) roots.add(value.trim()); + } + add(info.chatsRoot); + add(info.canonicalChatsRoot); + if (info.home.isNotEmpty) { + final home = info.home.replaceAll(RegExp(r'[/\\]+$'), ''); + add('$home/.config/openchamber/chats'); + } + add(info.canonicalLegacyChatsRoot); + chatsRoot = info.chatsRoot.isNotEmpty ? info.chatsRoot : null; + chatRoots = roots.toList(); + notifyListeners(); + } catch (_) {} + } + + /// A new directory for a chat session, in the server's chats root. The + /// server allows creating folders under that managed root without a + /// project scope. + Future createChatDirectory() async { + final cl = client; + if (cl == null) throw StateError('未连接服务器'); + if (chatsRoot == null || chatsRoot!.isEmpty) await refreshFsHome(); + final root = chatsRoot; + if (root == null || root.isEmpty) { + throw StateError('服务器没有提供聊天目录'); + } + final now = DateTime.now(); + final date = '${now.year.toString().padLeft(4, '0')}-' + '${now.month.toString().padLeft(2, '0')}-' + '${now.day.toString().padLeft(2, '0')}'; + final id = now.microsecondsSinceEpoch.toRadixString(36); + final dir = '${root.replaceAll(RegExp(r'[/\\]+$'), '')}/$date/session-$id'; + await cl.fsMkdir(dir); + return dir; + } + ProjectInfo? projectFor(String directory) { for (final project in projects) { if (samePath(project.canonical, directory)) return project; @@ -705,9 +823,12 @@ class AppState extends ChangeNotifier { chat?.session.directory ?? (sessions.isNotEmpty ? sessions.first.directory : ''); final latest = sessions.isNotEmpty ? sessions.first : null; - final dir = fallback.isNotEmpty + var dir = fallback.isNotEmpty ? fallback : (projects.isNotEmpty ? projects.first.canonical : ''); + // A new session started from an existing chat gets a chat of its own, not + // a second session in the same folder. + if (dir.isNotEmpty && isChatDirectory(dir)) dir = chatTarget; final created = SessionDraft( directory: dir, model: chat?.selectedModel ?? latest?.model, @@ -773,10 +894,23 @@ class AppState extends ChangeNotifier { current.error = null; sendingDraft = true; notifyListeners(); + var target = current.directory; + if (target == chatTarget) { + try { + target = await createChatDirectory(); + current.directory = target; + } catch (e) { + sendingDraft = false; + current.error = + '无法创建聊天目录:${e is ApiError ? e.message : e}'; + notifyListeners(); + return; + } + } final Session created; try { created = await cl.createSession( - directory: current.directory, + directory: target, model: current.model, agent: current.agent, ); diff --git a/lib/version.dart b/lib/version.dart index b536995..9abcc05 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -1,2 +1,2 @@ /// The app version sent to the server in pairing and relay handshakes. -const appVersion = '0.4.6'; +const appVersion = '0.4.8'; diff --git a/lib/widgets/project_icon.dart b/lib/widgets/project_icon.dart new file mode 100644 index 0000000..7ba11bd --- /dev/null +++ b/lib/widgets/project_icon.dart @@ -0,0 +1,165 @@ +// A project's sidebar icon: the operator's chosen icon in its colour, a custom +// icon image from the project, or a folder. OpenChamber's managed chats have +// no project and get a chat bubble instead. +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_svg/flutter_svg.dart'; + +import '../api/models.dart'; +import '../state.dart'; + +/// The Flutter equivalent of OpenChamber's `PROJECT_ICON_MAP` keys. +IconData? projectIconData(String key) => switch (key) { + 'code' => Icons.code, + 'terminal' => Icons.terminal, + 'rocket' => Icons.rocket_launch_outlined, + 'flask' => Icons.science_outlined, + 'gamepad' => Icons.sports_esports_outlined, + 'briefcase' => Icons.work_outline, + 'home' => Icons.home_outlined, + 'globe' => Icons.public, + 'leaf' => Icons.eco_outlined, + 'shield' => Icons.shield_outlined, + 'palette' => Icons.palette_outlined, + 'server' => Icons.dns_outlined, + 'phone' => Icons.smartphone, + 'database' => Icons.storage, + 'lightbulb' => Icons.lightbulb_outline, + 'music' => Icons.music_note_outlined, + 'camera' => Icons.photo_camera_outlined, + 'book' => Icons.menu_book_outlined, + 'heart' => Icons.favorite_outline, + 'cpu' => Icons.memory, + 'cloud' => Icons.cloud_outlined, + 'store' => Icons.storefront_outlined, + 'school' => Icons.school_outlined, + 'chat' => Icons.chat_bubble_outline, + 'mail' => Icons.mail_outline, + 'map' => Icons.place_outlined, + 'robot' => Icons.smart_toy_outlined, + 'ai' => Icons.psychology_outlined, + 'plugin' => Icons.extension_outlined, + 'tools' => Icons.build_outlined, + 'chart' => Icons.bar_chart, + 'writing' => Icons.edit_outlined, + 'image' => Icons.image_outlined, + 'film' => Icons.movie_outlined, + 'trophy' => Icons.emoji_events_outlined, + 'travel' => Icons.flight, + 'coffee' => Icons.coffee_outlined, + 'bug' => Icons.bug_report_outlined, + 'apple' => Icons.apple, + 'android' => Icons.android, + 'windows' => Icons.window, + 'github' => Icons.code, + 'stack' => Icons.layers_outlined, + 'finance' => Icons.account_balance_outlined, + 'team' => Icons.groups_outlined, + 'fire' => Icons.local_fire_department_outlined, + 'planet' => Icons.public, + _ => null, + }; + +/// A stored project colour as a Flutter colour. Newer projects store hex; +/// older ones a theme/syntax key, resolved against the app's scheme. +Color? projectColor(String value, ColorScheme scheme) { + final hex = projectHexColor(value); + if (hex != null) return hex; + return switch (value.trim()) { + 'primary' => scheme.primary, + 'error' => scheme.error, + 'success' => Colors.green, + 'keyword' => scheme.primary, + 'string' => Colors.green, + 'number' => Colors.orange, + 'type' => Colors.teal, + 'constant' => Colors.blue, + 'comment' => scheme.onSurfaceVariant, + _ => null, + }; +} + +Color? projectHexColor(String value) { + final text = value.trim(); + if (!text.startsWith('#')) return null; + var hex = text.substring(1); + if (hex.length == 3) { + hex = hex.split('').map((c) => '$c$c').join(); + } + if (hex.length != 6 && hex.length != 8) return null; + final parsed = int.tryParse(hex, radix: 16); + if (parsed == null) return null; + return Color(hex.length == 6 ? 0xff000000 | parsed : parsed); +} + +String _hexOf(Color color) => + '#${(color.toARGB32() & 0xffffff).toRadixString(16).padLeft(6, '0')}'; + +class ProjectIcon extends StatelessWidget { + final AppState app; + final ProjectInfo? project; + final bool chat; + final double size; + + const ProjectIcon({ + super.key, + required this.app, + this.project, + this.chat = false, + this.size = 16, + }); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + if (chat) { + return Icon(Icons.chat_bubble_outline, size: size, color: scheme.primary); + } + final project = this.project; + if (project == null) { + return Icon(Icons.folder_outlined, size: size, color: theme.hintColor); + } + final color = projectColor(project.color, scheme) ?? theme.hintColor; + final glyph = Icon(projectIconData(project.icon) ?? Icons.folder_outlined, + size: size, color: color); + if (!project.hasIconImage) return glyph; + + final future = app.projectIcon( + project, + dark: theme.brightness == Brightness.dark, + iconColor: _hexOf(scheme.onSurface), + ); + return FutureBuilder( + future: future, + builder: (context, snapshot) { + final bytes = snapshot.data; + if (bytes == null || bytes.isEmpty) { + // Loading or unavailable: keep the glyph so the row does not jump. + return glyph; + } + final Widget image = project.iconImageMime.contains('svg') + ? SvgPicture.memory(bytes, + width: size, height: size, fit: BoxFit.contain) + : Image.memory(bytes, + width: size, + height: size, + fit: BoxFit.contain, + gaplessPlayback: true); + final background = projectHexColor(project.iconBackground); + if (background == null) return image; + return Container( + width: size, + height: size, + decoration: BoxDecoration( + color: background, + borderRadius: BorderRadius.circular(3), + ), + clipBehavior: Clip.antiAlias, + child: image, + ); + }, + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index 3d3bd72..90de211 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -348,13 +348,13 @@ packages: source: hosted version: "5.2.0" flutter_svg: - dependency: transitive + dependency: "direct main" description: name: flutter_svg - sha256: "455a22036f8d1b7c74f53283c8644d6af2f6f7c9ec72c7b06a2ff70fb3954a54" + sha256: "4565a66f0a968f2e1ab4197854686990258aadab9572eb80a7655053a01dc302" url: "https://pub.flutter-io.cn" source: hosted - version: "2.4.0" + version: "2.5.0" flutter_test: dependency: "direct dev" description: flutter diff --git a/pubspec.yaml b/pubspec.yaml index 1a85a31..7aa57e8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.4.6+406 +version: 0.4.8+408 environment: sdk: ^3.14.0 @@ -22,6 +22,7 @@ dependencies: pointycastle: ^4.0.0 camera: ^0.12.2 zxing2: ^0.2.4 + flutter_svg: ^2.5.0 dev_dependencies: flutter_test: sdk: flutter diff --git a/test/paths_test.dart b/test/paths_test.dart index e838881..7915725 100644 --- a/test/paths_test.dart +++ b/test/paths_test.dart @@ -30,4 +30,16 @@ void main() { test('slashPath only unifies separators', () { expect(slashPath(r'C:\a\b\'), 'C:/a/b'); }); + + test('a directory is recognised under a chats root', () { + expect(isUnderDirectory('/home/me/.config/openchamber/chats/2026-11-23/x', + '/home/me/.config/openchamber/chats'), isTrue); + expect(isUnderDirectory(r'C:\Users\me\.config\openchamber\chats\a\b', + r'c:\users\me\.config\openchamber\chats'), isTrue); + expect(isUnderDirectory('/home/me/.config/openchamber/chats-other/x', + '/home/me/.config/openchamber/chats'), isFalse); + expect(isUnderDirectory('/home/me/project', '/home/me/.config/openchamber/chats'), + isFalse); + expect(isUnderDirectory('', '/x'), isFalse); + }); } diff --git a/test/project_icon_test.dart b/test/project_icon_test.dart new file mode 100644 index 0000000..efe6792 --- /dev/null +++ b/test/project_icon_test.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/models.dart'; +import 'package:openchamber/widgets/project_icon.dart'; + +void main() { + test('OpenChamber icon keys map to Flutter icons', () { + expect(projectIconData('code'), Icons.code); + expect(projectIconData('terminal'), Icons.terminal); + expect(projectIconData('ai'), Icons.psychology_outlined); + expect(projectIconData('unknown'), isNull); + expect(projectIconData(''), isNull); + }); + + test('hex and legacy project colours resolve', () { + final scheme = ColorScheme.fromSeed(seedColor: Colors.indigo); + expect(projectHexColor('#30a46c'), const Color(0xff30a46c)); + expect(projectHexColor('#abc'), const Color(0xffaabbcc)); + expect(projectHexColor('30a46c'), isNull); + expect(projectColor('error', scheme), scheme.error); + expect(projectColor('primary', scheme), scheme.primary); + expect(projectColor('comment', scheme), scheme.onSurfaceVariant); + expect(projectColor('#30a46c', scheme), const Color(0xff30a46c)); + expect(projectColor('', scheme), isNull); + }); + + test('a settings row decorates the project with label and icon metadata', () { + const project = ProjectInfo(id: 'p1', canonical: '/w/app'); + final merged = project.withMeta({ + 'id': 'path_L3cL2FwcA', + 'path': '/w/app', + 'label': 'My App', + 'icon': 'rocket', + 'color': '#30a46c', + 'iconBackground': '#101010', + 'iconImage': {'mime': 'image/svg+xml', 'updatedAt': 42}, + }); + expect(merged.label, 'My App'); + expect(merged.icon, 'rocket'); + expect(merged.color, '#30a46c'); + expect(merged.metaId, 'path_L3cL2FwcA'); + expect(merged.hasIconImage, isTrue); + expect(merged.iconImageMime, 'image/svg+xml'); + expect(merged.iconImageUpdatedAt, 42); + }); +} diff --git a/test/sidebar_rows_test.dart b/test/sidebar_rows_test.dart index 7beb6ca..e2a8a7b 100644 --- a/test/sidebar_rows_test.dart +++ b/test/sidebar_rows_test.dart @@ -5,6 +5,44 @@ import 'package:openchamber/screens/sessions_screen.dart'; import 'package:openchamber/state.dart'; void main() { + testWidgets('chat folders group under 聊天, not under session-xxxxx', + (tester) async { + final app = AppState(); + app.chatRoots = const [r'C:\Users\me\.config\openchamber\chats']; + final now = DateTime.now().millisecondsSinceEpoch; + app.sessions = [ + Session( + id: 'c1', + title: 'OpenCode 图像模型配置', + location: Location( + r'C:\Users\me\.config\openchamber\chats\2026-11-23\session-a'), + created: now, + updated: now, + ), + Session( + id: 'c2', + title: 'LC_ALL 环境变量的设置来源', + location: Location( + r'C:\Users\me\.config\openchamber\chats\2026-11-22\session-b'), + created: now - 1000, + updated: now - 1000, + ), + ]; + addTearDown(app.dispose); + + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: SessionListPane(app: app)), + )); + await tester.pumpAndSettle(); + + // One chats group, labelled the same as the first-party sidebar. + expect(find.text('聊天'), findsOneWidget); + expect(find.byTooltip('新建聊天'), findsOneWidget); + expect(find.textContaining('session-'), findsNothing); + expect(find.text('OpenCode 图像模型配置'), findsOneWidget); + expect(find.text('LC_ALL 环境变量的设置来源'), findsOneWidget); + }); + testWidgets('the project band matches a session row and keeps the keys in line', (tester) async { final app = AppState();