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

+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 {
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
/// 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<String, dynamic> 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<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 {
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) {
+30 -9
View File
@@ -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<NewSessionScreen> {
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<NewSessionScreen> {
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<NewSessionScreen> {
Future<void> _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<NewSessionScreen> {
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<NewSessionScreen> {
final byPath = <String, ProjectInfo>{};
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)) {
+22 -13
View File
@@ -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<SessionListPane> {
// --------------------------------------------------------------- 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) {
final map = <String, List<Session>>{};
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<SessionListPane> {
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<SessionListPane> {
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<SessionListPane> {
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(() {
+137 -3
View File
@@ -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<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.
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 = <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();
} 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.
Future<void> 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<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) {
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,
);
+1 -1
View File
@@ -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';
+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,
);
},
);
}
}