feat: group the server's chats and use OpenChamber's project icons

Sessions under the server's managed chats root (chats/<date>/session-…) were
grouped per directory, so each one appeared as its own session-xxxxx band.
GET /api/fs/home now supplies the chats root plus its canonical and legacy
aliases; every chat folder becomes the single 聊天 group. The new-session
picker can target 聊天 too: the first send creates a fresh chat directory
before creating the session, and a new session started from an existing chat
gets a new one instead of sharing its folder.

Projects merge their OpenChamber settings row (label, icon key, colour,
iconBackground and uploaded/auto icon image) with /api/project. Group
headers, the picker and the draft chip draw the chosen icon in its colour,
and custom images are fetched through the client transport (SVG included)
with a themed fallback to the glyph. The chat group uses a chat bubble rather
than a folder.

0.4.8 (408).
This commit is contained in:
blumia committed 2026-11-23 17:42:49 +08:00
1 parent 91bf5e5b81
commit 79221e57d7
14 files changed
+599 -32

No files matched your search

+24
View File
@@ -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/<settingsId>/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-<id>` 建目录(`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`) ## 0.4.6 扫码无反应的修复与诊断(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+6 -2
View File
@@ -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 feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. 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 SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing 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 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 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 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 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) 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 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 form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
+29
View File
@@ -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<FsHomeInfo> 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<Uint8List?> 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<void> deleteSession(String id) async { Future<void> deleteSession(String id) async {
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}'); await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
} }
+84
View File
@@ -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<String, dynamic> 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 /// A project the server knows: a checkout (or chat folder) an agent can work
/// in. [canonical] is the directory a session there carries. /// in. [canonical] is the directory a session there carries.
class ProjectInfo { class ProjectInfo {
@@ -151,11 +177,26 @@ class ProjectInfo {
final String name; final String name;
final String vcs; 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({ const ProjectInfo({
required this.id, required this.id,
required this.canonical, required this.canonical,
this.name = '', this.name = '',
this.vcs = '', this.vcs = '',
this.metaId = '',
this.icon = '',
this.color = '',
this.iconBackground = '',
this.iconImageMime = '',
this.iconImageUpdatedAt = 0,
}); });
factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo( factory ProjectInfo.fromJson(Map<String, dynamic> j) => ProjectInfo(
@@ -165,6 +206,36 @@ class ProjectInfo {
vcs: j['vcs'] as String? ?? '', 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<String, dynamic>? 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 { String get label {
if (name.trim().isNotEmpty) return name.trim(); if (name.trim().isNotEmpty) return name.trim();
return pathLeaf(canonical); return pathLeaf(canonical);
@@ -184,6 +255,19 @@ String pathLeaf(String path) {
String slashPath(String path) => String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), ''); 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; /// Whether two directory paths name the same place. Separators are unified;
/// a drive-letter path compares case-insensitively, as Windows does. /// a drive-letter path compares case-insensitively, as Windows does.
bool samePath(String a, String b) { bool samePath(String a, String b) {
+30 -9
View File
@@ -10,6 +10,7 @@ import '../widgets/composer_attachment.dart';
import '../widgets/composer_box.dart'; import '../widgets/composer_box.dart';
import '../widgets/model_controls.dart'; import '../widgets/model_controls.dart';
import '../widgets/pet_sprite.dart'; import '../widgets/pet_sprite.dart';
import '../widgets/project_icon.dart';
import '../widgets/slash_palette.dart'; import '../widgets/slash_palette.dart';
import 'files_panel.dart'; import 'files_panel.dart';
@@ -280,6 +281,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
Widget _projectChip(SessionDraft draft) { Widget _projectChip(SessionDraft draft) {
final theme = Theme.of(context); final theme = Theme.of(context);
final isChat = draft.directory == AppState.chatTarget;
final label = widget.app.projectLabelFor(draft.directory); final label = widget.app.projectLabelFor(draft.directory);
return InkWell( return InkWell(
borderRadius: BorderRadius.circular(18), borderRadius: BorderRadius.circular(18),
@@ -289,8 +291,12 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(Icons.folder_outlined, ProjectIcon(
size: 15, color: theme.hintColor), app: widget.app,
project: isChat ? null : widget.app.projectFor(draft.directory),
chat: isChat,
size: 15,
),
const SizedBox(width: 5), const SizedBox(width: 5),
ConstrainedBox( ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170), constraints: const BoxConstraints(maxWidth: 170),
@@ -455,7 +461,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
Future<void> _pickProject() async { Future<void> _pickProject() async {
final app = widget.app; final app = widget.app;
await app.refreshProjects(); await Future.wait([app.refreshProjects(), app.refreshFsHome()]);
if (!mounted) return; if (!mounted) return;
final draft = app.draft; final draft = app.draft;
if (draft == null) return; if (draft == null) return;
@@ -479,14 +485,29 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
child: ListView( child: ListView(
controller: controller, controller: controller,
children: [ 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) for (final project in projects)
ListTile( ListTile(
dense: true, dense: true,
leading: Icon( leading:
project.vcs.isNotEmpty ProjectIcon(app: widget.app, project: project, size: 20),
? Icons.account_tree_outlined
: Icons.folder_outlined,
size: 20),
title: Text(project.label, title: Text(project.label,
maxLines: 1, overflow: TextOverflow.ellipsis), maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(project.canonical, subtitle: Text(project.canonical,
@@ -525,7 +546,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
final byPath = <String, ProjectInfo>{}; final byPath = <String, ProjectInfo>{};
for (final project in projects) { for (final project in projects) {
if (project.canonical.isEmpty) continue; if (project.canonical.isEmpty) continue;
if (project.canonical.contains('/.config/openchamber/')) continue; if (widget.app.isChatDirectory(project.canonical)) continue;
final existing = byPath[project.canonical]; final existing = byPath[project.canonical];
if (existing == null || if (existing == null ||
(existing.vcs.isEmpty && project.vcs.isNotEmpty)) { (existing.vcs.isEmpty && project.vcs.isNotEmpty)) {
+22 -13
View File
@@ -6,6 +6,7 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import '../api/models.dart'; import '../api/models.dart';
import '../state.dart'; import '../state.dart';
import '../widgets/project_icon.dart';
import 'servers_screen.dart'; import 'servers_screen.dart';
import 'settings_screen.dart'; import 'settings_screen.dart';
@@ -248,19 +249,13 @@ class _SessionListPaneState extends State<SessionListPane> {
// --------------------------------------------------------------- groups // --------------------------------------------------------------- groups
bool _isChatDirectory(String directory) =>
directory.contains('/.config/openchamber/chats');
String _groupLabel(String key) =>
key == '\u0000chats' ? '聊天' : _app.projectLabelFor(key);
List<_SessionGroup> _groups(List<Session> sessions) { List<_SessionGroup> _groups(List<Session> sessions) {
final map = <String, List<Session>>{}; final map = <String, List<Session>>{};
for (final session in sessions) { for (final session in sessions) {
// Group on a separator-normalised key so a Windows server's mix of // Group on a separator-normalised key so a Windows server's mix of
// `\` and `/` does not split one project into two. // `\` and `/` does not split one project into two.
final key = _isChatDirectory(session.directory) final key = _app.isChatDirectory(session.directory)
? '\u0000chats' ? AppState.chatTarget
: slashPath(session.directory); : slashPath(session.directory);
map.putIfAbsent(key, () => []).add(session); map.putIfAbsent(key, () => []).add(session);
} }
@@ -268,9 +263,13 @@ class _SessionListPaneState extends State<SessionListPane> {
for (final entry in map.entries) for (final entry in map.entries)
_SessionGroup( _SessionGroup(
key: entry.key, 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. // 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 sessions: entry.value
..sort((a, b) => b.updated.compareTo(a.updated)), ..sort((a, b) => b.updated.compareTo(a.updated)),
), ),
@@ -320,7 +319,14 @@ class _SessionListPaneState extends State<SessionListPane> {
Icon(collapsed ? Icons.chevron_right : Icons.expand_more, Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
size: 18, color: scheme.onSurfaceVariant), size: 18, color: scheme.onSurfaceVariant),
const SizedBox(width: 2), 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( title: Text(
@@ -349,8 +355,11 @@ class _SessionListPaneState extends State<SessionListPane> {
child: IconButton( child: IconButton(
icon: const Icon(Icons.add, size: 20), icon: const Icon(Icons.add, size: 20),
padding: EdgeInsets.zero, padding: EdgeInsets.zero,
tooltip: '在此项目新会话', tooltip: group.key == AppState.chatTarget ? '新建聊天' : '在此项目新会话',
onPressed: () => _newSession(directory: group.path), onPressed: () => _newSession(
directory: group.key == AppState.chatTarget
? AppState.chatTarget
: group.path),
), ),
), ),
onTap: () => setState(() { onTap: () => setState(() {
+137 -3
View File
@@ -5,6 +5,7 @@ library;
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@@ -106,6 +107,15 @@ class AppState extends ChangeNotifier {
/// group headers. /// group headers.
List<ProjectInfo> projects = []; List<ProjectInfo> 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<String> chatRoots = [];
/// The unsent new-session draft, kept in memory. Null when there is none. /// The unsent new-session draft, kept in memory. Null when there is none.
SessionDraft? draft; SessionDraft? draft;
bool sendingDraft = false; bool sendingDraft = false;
@@ -428,6 +438,7 @@ class AppState extends ChangeNotifier {
_startStream(); _startStream();
refreshSessions(); refreshSessions();
refreshProjects(); refreshProjects();
refreshFsHome();
refreshActive(); refreshActive();
refreshPerms(); refreshPerms();
refreshModels(); refreshModels();
@@ -452,6 +463,9 @@ class AppState extends ChangeNotifier {
sendingDraft = false; sendingDraft = false;
sessions = []; sessions = [];
projects = []; projects = [];
chatsRoot = null;
chatRoots = [];
_projectIcons.clear();
archivedSessions = []; archivedSessions = [];
archivedLoaded = false; archivedLoaded = false;
_sessionsNext = null; _sessionsNext = null;
@@ -510,11 +524,57 @@ class AppState extends ChangeNotifier {
final cl = client; final cl = client;
if (cl == null) return; if (cl == null) return;
try { 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 = <String, Map<String, dynamic>>{};
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<String, dynamic>.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(); notifyListeners();
} catch (_) {} } catch (_) {}
} }
final Map<String, Future<Uint8List?>> _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<Uint8List?> 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<Uint8List?>.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. /// Loads the next (older) page of the session list.
Future<void> loadMoreSessions() async { Future<void> loadMoreSessions() async {
final cl = client; final cl = client;
@@ -611,6 +671,7 @@ class AppState extends ChangeNotifier {
} }
String projectLabelFor(String directory) { String projectLabelFor(String directory) {
if (directory == chatTarget || isChatDirectory(directory)) return '聊天';
if (directory.isEmpty) return ''; if (directory.isEmpty) return '';
for (final project in projects) { for (final project in projects) {
if (samePath(project.canonical, directory)) return project.label; if (samePath(project.canonical, directory)) return project.label;
@@ -618,6 +679,63 @@ class AppState extends ChangeNotifier {
return pathLeaf(directory); 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<void> refreshFsHome() async {
final cl = client;
if (cl == null) return;
try {
final info = await cl.fsHome();
if (client != cl) return;
final roots = <String>{};
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<String> 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) { ProjectInfo? projectFor(String directory) {
for (final project in projects) { for (final project in projects) {
if (samePath(project.canonical, directory)) return project; if (samePath(project.canonical, directory)) return project;
@@ -705,9 +823,12 @@ class AppState extends ChangeNotifier {
chat?.session.directory ?? chat?.session.directory ??
(sessions.isNotEmpty ? sessions.first.directory : ''); (sessions.isNotEmpty ? sessions.first.directory : '');
final latest = sessions.isNotEmpty ? sessions.first : null; final latest = sessions.isNotEmpty ? sessions.first : null;
final dir = fallback.isNotEmpty var dir = fallback.isNotEmpty
? fallback ? fallback
: (projects.isNotEmpty ? projects.first.canonical : ''); : (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( final created = SessionDraft(
directory: dir, directory: dir,
model: chat?.selectedModel ?? latest?.model, model: chat?.selectedModel ?? latest?.model,
@@ -773,10 +894,23 @@ class AppState extends ChangeNotifier {
current.error = null; current.error = null;
sendingDraft = true; sendingDraft = true;
notifyListeners(); 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; final Session created;
try { try {
created = await cl.createSession( created = await cl.createSession(
directory: current.directory, directory: target,
model: current.model, model: current.model,
agent: current.agent, agent: current.agent,
); );
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes. /// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.6'; const appVersion = '0.4.8';
+165
View File
@@ -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<Uint8List?>(
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,
);
},
);
}
}
+3 -3
View File
@@ -348,13 +348,13 @@ packages:
source: hosted source: hosted
version: "5.2.0" version: "5.2.0"
flutter_svg: flutter_svg:
dependency: transitive dependency: "direct main"
description: description:
name: flutter_svg name: flutter_svg
sha256: "455a22036f8d1b7c74f53283c8644d6af2f6f7c9ec72c7b06a2ff70fb3954a54" sha256: "4565a66f0a968f2e1ab4197854686990258aadab9572eb80a7655053a01dc302"
url: "https://pub.flutter-io.cn" url: "https://pub.flutter-io.cn"
source: hosted source: hosted
version: "2.4.0" version: "2.5.0"
flutter_test: flutter_test:
dependency: "direct dev" dependency: "direct dev"
description: flutter description: flutter
+2 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.4.6+406 version: 0.4.8+408
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
@@ -22,6 +22,7 @@ dependencies:
pointycastle: ^4.0.0 pointycastle: ^4.0.0
camera: ^0.12.2 camera: ^0.12.2
zxing2: ^0.2.4 zxing2: ^0.2.4
flutter_svg: ^2.5.0
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
+12
View File
@@ -30,4 +30,16 @@ void main() {
test('slashPath only unifies separators', () { test('slashPath only unifies separators', () {
expect(slashPath(r'C:\a\b\'), 'C:/a/b'); 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);
});
} }
+46
View File
@@ -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);
});
}
+38
View File
@@ -5,6 +5,44 @@ import 'package:openchamber/screens/sessions_screen.dart';
import 'package:openchamber/state.dart'; import 'package:openchamber/state.dart';
void main() { 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', testWidgets('the project band matches a session row and keeps the keys in line',
(tester) async { (tester) async {
final app = AppState(); final app = AppState();