From c6b5a870c6c20db6bfdfa824b39cd15a76444391 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Fri, 27 Nov 2026 09:26:14 +0800 Subject: [PATCH] feat: add a project from the picker, and keep the context ring - the project picker has an "Add project" action: a folder browser starts at the server user's home, navigates (typed path, up, new folder) and adds the chosen folder through POST /api/openchamber/directory; the new project becomes the draft's target at once - refreshProjects merges settings-only projects (newest added first), so a project added before its first session still appears in the picker; the first session moves it into /api/project as usual - usageReading no longer hides the composer's context ring when the session's model has left the server catalog: a 200K window is assumed, the percentage is prefixed with "~", and the usage sheet says the window is estimated. A failed model fetch at connect is retried when a chat opens, so a normal session shows the real percentage - tests: the add-project browser flow, settings-only projects, and the estimated/known context readings --- PLAN.md | 11 + README.md | 10 +- lib/api/client.dart | 16 ++ lib/l10n/zh.dart | 12 ++ lib/screens/chat_screen.dart | 15 +- lib/state.dart | 83 +++++++- lib/widgets/directory_picker.dart | 322 ++++++++++++++++++++++++++++++ lib/widgets/project_picker.dart | 33 ++- pubspec.yaml | 2 +- test/directory_picker_test.dart | 175 ++++++++++++++++ test/running_state_test.dart | 51 +++++ 11 files changed, 708 insertions(+), 22 deletions(-) create mode 100644 lib/widgets/directory_picker.dart create mode 100644 test/directory_picker_test.dart diff --git a/PLAN.md b/PLAN.md index 2e97d41..3483d96 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,17 @@ --- +## 0.5.7 添加项目与上下文环回退(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 添加项目 | 项目选择器右上角新增【添加项目】:从服务器用户主目录开始浏览文件夹(可输入路径、上一级、新建文件夹),选中后写入 OpenChamber 项目列表并立即作为当前目标;新建会话、计划任务、统计的项目列表共享同一入口 | +| 项目列表 | `/api/project` 只在项目里有会话后才返回该项;`refreshProjects` 现在合并设置文档里的项目(按 `addedAt` 新的在前),所以刚添加、还没有会话的项目也能在选择器里出现 | +| 上下文环 | 旧会话的模型可能已从服务器模型目录移除,`usageReading` 找不到上下文窗口时不再隐藏输入框底部的环:按 200K 窗口估算并显示 `~百分比`;用量弹层注明「该模型不在模型目录中,上下文窗口为估算值」 | +| 版本 | **0.5.7(code 507)** | + +--- + ## 0.5.6 统计页面与 Chamber Go(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 34aad49..1368e7c 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,19 @@ 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.5.6 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.5.7 — 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 events, chat with streaming Markdown and full history paging, tool steps grouped per turn (icon, one-line summary, foldable run) with image previews, a -context usage ring with a detail sheet, model/agent switching (Build/Plan only, +context usage ring with a detail sheet (an estimated window when the session's +model has left the server catalog), model/agent switching (Build/Plan only, current one checked), copy / fork / revert, attachments (photos/files, kept -after a reload), the agent's native forms, permissions. The files sidebar also +after a reload), the agent's native forms, permissions. The project picker can +add a folder from the server: it browses from the server user's home, renames +paths and creates folders, and keeps a project that exists only in OpenChamber's +settings (no session yet) in the list. The files sidebar also carries the project knowledge (notes, todos, plans, and agent memory when the server enables it) and a full terminal with a Termux-style key bar; downloads show their progress and can be cancelled. The terminal holds several tabs per diff --git a/lib/api/client.dart b/lib/api/client.dart index e716335..45d5eae 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -187,6 +187,22 @@ class Client { ]; } + /// Adds [path] to OpenChamber's project list (its settings document). A + /// project can be added before any session exists in it, so this is the + /// way a new checkout appears in the project picker; [create] also makes + /// the folder. Returns the server's canonical path, which may resolve a + /// symlink or a trailing slash. + Future addProjectDirectory(String path, {bool create = false}) async { + final r = await _json('POST', '/api/openchamber/directory', body: { + 'path': path, + 'create': create, + }); + final resolved = r['path']; + return resolved is String && resolved.trim().isNotEmpty + ? resolved.trim() + : path; + } + /// 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. diff --git a/lib/l10n/zh.dart b/lib/l10n/zh.dart index a43ef1a..462c37c 100644 --- a/lib/l10n/zh.dart +++ b/lib/l10n/zh.dart @@ -11,7 +11,9 @@ const Map chineseStrings = { 'Accent color': '主题色', 'Accent color {0}': '主题色 {0}', 'Add attachment': '添加附件', + 'Add project': '添加项目', 'Add server': '添加服务器', + 'Add this folder': '添加此文件夹', 'Add time': '添加时间', 'Agent': '智能体', 'Agent tools': '通用', @@ -75,12 +77,15 @@ const Map chineseStrings = { 'Copy answer': '复制回答', 'Copy message': '复制消息', 'Copy session ID': '复制会话 ID', + 'Could not add the project: {0}': '无法添加项目:{0}', 'Could not attach: {0}': '选择失败:{0}', 'Could not connect to the relay: {0}': '无法连接 Relay:{0}', 'Could not create the chat directory: {0}': '无法创建聊天目录:{0}', + 'Could not create the folder: {0}': '无法创建文件夹:{0}', 'Could not decode the QR code; try again': '二维码解码出错,请重试', 'Could not get a WebSocket token ({0})': '无法获取 WebSocket 令牌({0})', 'Could not load image: {0}': '图片加载失败:{0}', + 'Could not load this folder: {0}': '无法加载此文件夹:{0}', 'Could not load, refresh to retry': '读取失败,请刷新', 'Could not open the camera: {0}': '无法打开相机:{0}', 'Could not open the subagent session: {0}': '无法打开子代理会话:{0}', @@ -142,6 +147,7 @@ const Map chineseStrings = { 'Edit scheduled task': '编辑计划任务', 'Enable pet': '启用宠物', 'Enabled': '已启用', + 'Enter a valid folder name': '请输入有效的文件夹名称', 'End-to-end encrypted; the server and device token stay the same': '端到端加密;服务器与设备令牌保持不变', 'Ended': '已结束', 'Error': '错误', @@ -162,6 +168,8 @@ const Map chineseStrings = { 'File {0}': '文件 {0}', 'Files': '文件', 'Flashlight': '手电筒', + 'Folder name': '文件夹名称', + 'Folder path': '文件夹路径', 'Follow system': '跟随系统', 'Follow the system, Chinese or English': '跟随系统、中文或 English', 'Follow-up behavior': '追问处理行为', @@ -172,6 +180,7 @@ const Map chineseStrings = { 'Generating summary…': '正在生成摘要…', 'Generating; you can still type…': '生成中,仍可输入…', 'Global memory': '全局记忆', + 'Go': '前往', 'Goal': '目标', 'Got it': '知道了', 'Help & about': '帮助与关于', @@ -261,6 +270,7 @@ const Map chineseStrings = { 'No content': '无内容', 'no date': '未选日期', 'no days': '未选', + 'No folders here': '此目录没有子文件夹', 'No matching files': '没有匹配的文件', 'No matching files in subdirectories': '子目录里没有匹配的文件', 'No matching memories': '没有匹配的记忆', @@ -450,6 +460,7 @@ const Map chineseStrings = { 'The agent notifies you when work finishes or gets stuck.': '工作完成或卡住时,智能体会通知你。', 'The archive has no pack.json': '压缩包里没有 pack.json', 'The model failed to authenticate. Sign in again on the server or check the API key.': '模型的认证失败,请在服务端重新登录或检查 API Key。', + 'The model is not in the catalog; the context window is estimated.': '该模型不在模型目录中,上下文窗口为估算值。', 'The pet pack stored on this device will be deleted.': '本机保存的宠物包会被删除。', 'The server doesn\'t support scheduled tasks': '服务器不支持计划任务', 'The theme is stored on this device only and does not sync with the server.': '主题只保存在本机,不随服务器同步。', @@ -591,6 +602,7 @@ const Map chineseStrings = { 'Success rate': '成功率', 'Failed': '失败', 'Unfinished': '未完成', + 'Up': '上一级', 'Updated {0}': '更新于 {0}', 'Subagents: {0}': '子代理:{0}', 'In {0} · Out {1} · Cache {2}': '输入 {0} · 输出 {1} · 缓存 {2}', diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 398d5e9..fcc7342 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -2078,7 +2078,10 @@ class _ChatScreenState extends State { size: 16, accent: scheme.primary), const SizedBox(width: 3), - AppText('${usage.$4.round()}%', + AppText( + usage.$6 + ? '~${usage.$4.round()}%' + : '${usage.$4.round()}%', style: TextStyle( fontSize: 12, color: scheme.onSurfaceVariant)), @@ -2395,8 +2398,14 @@ class _ChatScreenState extends State { ], if (chat.turnCost > 0) _usageRow('Turn cost', '\$${chat.turnCost.toStringAsFixed(4)}'), const SizedBox(height: 8), - const AppText('Reserved output assumes at most 32K tokens, matching the official client.', - style: TextStyle(color: Colors.grey, fontSize: 12)), + if (r.$6) + const AppText( + 'The model is not in the catalog; the context window is estimated.', + style: TextStyle(color: Colors.grey, fontSize: 12)) + else + const AppText( + 'Reserved output assumes at most 32K tokens, matching the official client.', + style: TextStyle(color: Colors.grey, fontSize: 12)), ], ), ), diff --git a/lib/state.dart b/lib/state.dart index 7b2d0ad..879ca64 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -141,6 +141,9 @@ class AppState extends ChangeNotifier { String? chatsRoot; List chatRoots = []; + /// The server user's home directory, where the add-project browser starts. + String homeDirectory = ''; + /// The unsent new-session draft, kept in memory. Null when there is none. SessionDraft? draft; bool sendingDraft = false; @@ -532,6 +535,7 @@ class AppState extends ChangeNotifier { projects = []; chatsRoot = null; chatRoots = []; + homeDirectory = ''; allowPromptingSubagentSessions = false; _childrenLoaded.clear(); _childrenLoading.clear(); @@ -598,6 +602,7 @@ class AppState extends ChangeNotifier { // The settings document carries the operator's label, icon key, colour // and icon image; /api/project only knows the checkout itself. final byPath = >{}; + final settingsRows = >[]; try { final settings = await cl.settings(); final rows = settings['projects']; @@ -610,10 +615,36 @@ class AppState extends ChangeNotifier { final key = slashPath(path); byPath[key] = meta; byPath[key.toLowerCase()] = meta; + settingsRows.add(meta); } } } catch (_) {} + + // OpenCode only lists a checkout once it has a session. A project the + // user added in the client has no session yet, so its settings row is + // the only record; keep those rows in the picker (newest first) until + // the first session moves them into /api/project. + final known = {}; + for (final project in list) { + known.add(slashPath(project.canonical)); + known.add(slashPath(project.canonical).toLowerCase()); + } + final extras = <({int added, ProjectInfo project})>[]; + for (final meta in settingsRows) { + final path = meta['path']; + if (path is! String || path.trim().isEmpty) continue; + final key = slashPath(path); + if (known.contains(key) || known.contains(key.toLowerCase())) continue; + final added = meta['addedAt']; + extras.add(( + added: added is num ? added.toInt() : 0, + project: ProjectInfo(id: '', canonical: path).withMeta(meta), + )); + } + extras.sort((a, b) => b.added.compareTo(a.added)); + projects = [ + for (final extra in extras) extra.project, for (final project in list) project.withMeta(byPath[slashPath(project.canonical)] ?? byPath[slashPath(project.canonical).toLowerCase()]), @@ -622,6 +653,18 @@ class AppState extends ChangeNotifier { } catch (_) {} } + /// Adds a folder to the server's project list, then refreshes the list so + /// its settings row decorates it. Returns the resolved project; the caller + /// may select it for a new session. Throws when the server refuses the path. + Future addProjectDirectory(String path) async { + final cl = client; + if (cl == null) return null; + final resolved = await cl.addProjectDirectory(path); + await refreshProjects(); + return projectFor(resolved) ?? + ProjectInfo(id: '', canonical: resolved, name: pathLeaf(resolved)); + } + final Map> _projectIcons = {}; /// A project's icon image, fetched once per theme/colour/version. Null when @@ -818,6 +861,7 @@ class AppState extends ChangeNotifier { add(info.canonicalLegacyChatsRoot); chatsRoot = info.chatsRoot.isNotEmpty ? info.chatsRoot : null; chatRoots = roots.toList(); + if (info.home.isNotEmpty) homeDirectory = info.home; notifyListeners(); } catch (_) {} } @@ -1343,6 +1387,10 @@ class AppState extends ChangeNotifier { // Opening a chat whose turn is already under way: the events that started // it came while the chat was closed, so ask the server once. final actives = refreshActive(); + // The catalog is read once per connection; a request that raced the + // server's startup leaves it empty and the context ring without the + // model's window. Opening a chat is where that window is first needed. + if (modelList.isEmpty) unawaited(refreshModels()); await chat!.load(); final known = await actives; if (chat != null && chat!.session.id == s.id) { @@ -2351,7 +2399,18 @@ class ChatState extends ChangeNotifier { // ------------------------------------------------------------ usage - (int, int, int, double, bool, double) usageReading() { + /// The context window assumed when the session's model is not in the + /// server's catalog: old sessions can name a model its provider has since + /// dropped, and hiding the ring then reads as a regression. The value is + /// the common 200K window; the usage sheet marks it as estimated. + static const estimatedContextWindow = 200000; + + /// The composer's context reading: used tokens, the model's context window, + /// its reserved output, the percentage of the usable window, whether there + /// is a reading at all, and whether the window was estimated because the + /// model is unknown. The last two are false before the first assistant + /// message with token usage. + (int, int, int, double, bool, bool) usageReading() { Message? last; for (var i = msgs.length - 1; i >= 0; i--) { if (msgs[i].type == 'assistant' && msgs[i].tokens != null) { @@ -2359,25 +2418,27 @@ class ChatState extends ChangeNotifier { break; } } - if (last == null) return (0, 0, 0, 0, false, 0); + if (last == null) return (0, 0, 0, 0, false, false); ModelRef? model = last.model; if (model == null) { for (var i = msgs.length - 1; i >= 0 && model == null; i--) { model = msgs[i].model; } } - if (model == null) return (0, 0, 0, 0, false, 0); final used = last.tokens!.used; - final lim = app.modelLimits['${model.providerId}/${model.id}'] ?? - app.modelLimits[model.id] ?? - (0, 0); - final context = lim.$1; - var output = lim.$2; - if (context <= 0 || used <= 0) return (used, context, output, 0, false, 0); - var reserve = output > 32000 ? 32000 : output; + if (used <= 0) return (used, 0, 0, 0, false, false); + final lim = model == null + ? (0, 0) + : (app.modelLimits['${model.providerId}/${model.id}'] ?? + app.modelLimits[model.id] ?? + (0, 0)); + final known = lim.$1 > 0; + final context = known ? lim.$1 : estimatedContextWindow; + final output = known ? lim.$2 : 0; + final reserve = output > 32000 ? 32000 : output; final threshold = (context - reserve) < 1 ? 1 : context - reserve; final pct = used / threshold * 100; - return (used, context, output, pct, true, 0); + return (used, context, output, pct, true, !known); } double get turnCost { diff --git a/lib/widgets/directory_picker.dart b/lib/widgets/directory_picker.dart new file mode 100644 index 0000000..76955f7 --- /dev/null +++ b/lib/widgets/directory_picker.dart @@ -0,0 +1,322 @@ +// The add-project browser: walks the server's directories from the user's +// home and adds the chosen folder to OpenChamber's project list. A project +// stored only in the settings document (no session yet) is still a valid +// target; the first session in it makes OpenCode list it too. +import 'package:flutter/material.dart'; + +import '../api/models.dart'; +import '../l10n.dart'; +import '../state.dart'; + +/// Opens the folder browser and returns the canonical path that was added, or +/// null when the sheet was dismissed. +Future showDirectoryPicker(BuildContext context, + {required AppState app}) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + useSafeArea: true, + builder: (context) => Padding( + // Keep the sheet above the keyboard; the folder list gets the rest. + padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom), + child: FractionallySizedBox( + heightFactor: 0.9, + child: _DirectoryPickerSheet(app: app), + ), + ), + ); +} + +class _DirectoryPickerSheet extends StatefulWidget { + final AppState app; + + const _DirectoryPickerSheet({required this.app}); + + @override + State<_DirectoryPickerSheet> createState() => _DirectoryPickerSheetState(); +} + +class _DirectoryPickerSheetState extends State<_DirectoryPickerSheet> { + final TextEditingController _pathCtrl = TextEditingController(); + String _path = ''; + List _dirs = const []; + bool _loading = true; + bool _adding = false; + String? _error; + + AppState get _app => widget.app; + + @override + void initState() { + super.initState(); + _start(); + } + + @override + void dispose() { + _pathCtrl.dispose(); + super.dispose(); + } + + Future _start() async { + var home = _app.homeDirectory.trim(); + if (home.isEmpty) { + try { + home = (await _app.client?.fsHome())?.home.trim() ?? ''; + } catch (_) { + // Fall back to the filesystem root; the path field still works. + } + } + await _open(home.isEmpty ? '/' : home); + } + + /// trims a typed path, keeps the root and drops trailing separators. + String _normalize(String path) { + var p = path.trim(); + if (p.isEmpty) return '/'; + while (p.length > 1 && (p.endsWith('/') || p.endsWith('\\'))) { + p = p.substring(0, p.length - 1); + } + return p.isEmpty ? '/' : p; + } + + String _parent(String path) { + final p = _normalize(path); + if (p == '/') return '/'; + final index = p.lastIndexOf(RegExp(r'[/\\]')); + if (index <= 0) return '/'; + return p.substring(0, index); + } + + String _join(String folder) => _path == '/' ? '/$folder' : '$_path/$folder'; + + Future _open(String path) async { + final target = _normalize(path); + setState(() { + _path = target; + _pathCtrl.text = target; + _loading = true; + _error = null; + }); + final client = _app.client; + if (client == null) { + setState(() { + _loading = false; + _error = tr('Not connected to a server'); + }); + return; + } + try { + final entries = + await client.fsList(target, respectGitignore: false); + final dirs = [ + for (final entry in entries) + if (entry.isDirectory) entry, + ]..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + if (!mounted) return; + setState(() { + _dirs = dirs; + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _dirs = const []; + _loading = false; + _error = trArgs('Could not load this folder: {0}', [e]); + }); + } + } + + Future _createFolder() async { + final name = await _askFolderName(); + if (name == null || !mounted) return; + final client = _app.client; + if (client == null) return; + final target = _join(name); + try { + await client.fsMkdir(target); + if (!mounted) return; + await _open(target); + } catch (e) { + if (!mounted) return; + setState(() => _error = trArgs('Could not create the folder: {0}', [e])); + } + } + + Future _askFolderName() async { + final controller = TextEditingController(); + final name = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const AppText('New folder'), + content: TextField( + controller: controller, + autofocus: true, + decoration: InputDecoration(hintText: tr('Folder name')), + onSubmitted: (value) => Navigator.pop(context, value.trim()), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const AppText('Cancel')), + FilledButton( + onPressed: () => Navigator.pop(context, controller.text.trim()), + child: const AppText('Create')), + ], + ), + ); + controller.dispose(); + if (name == null || name.isEmpty) return null; + if (name == '.' || name == '..' || name.contains('/') || name.contains('\\')) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: AppText(tr('Enter a valid folder name')))); + } + return null; + } + return name; + } + + Future _add() async { + if (_adding || _loading) return; + setState(() { + _adding = true; + _error = null; + }); + try { + final project = await _app.addProjectDirectory(_path); + if (!mounted) return; + Navigator.pop(context, project?.canonical ?? _path); + } catch (e) { + if (!mounted) return; + setState(() { + _adding = false; + _error = trArgs('Could not add the project: {0}', [e]); + }); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(4, 6, 12, 0), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.close), + tooltip: tr('Close'), + onPressed: () => Navigator.pop(context)), + const Expanded( + child: AppText('Add project', + style: + TextStyle(fontSize: 18, fontWeight: FontWeight.w600)), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 12, 6), + child: TextField( + controller: _pathCtrl, + textInputAction: TextInputAction.go, + onSubmitted: _open, + style: const TextStyle(fontSize: 13, fontFamily: 'monospace'), + decoration: InputDecoration( + isDense: true, + prefixIcon: const Icon(Icons.folder_outlined, size: 18), + hintText: tr('Folder path'), + border: + OutlineInputBorder(borderRadius: BorderRadius.circular(10)), + suffixIcon: TextButton( + onPressed: () => _open(_pathCtrl.text), + child: const AppText('Go')), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.arrow_upward, size: 18), + tooltip: tr('Up'), + onPressed: _path == '/' ? null : () => _open(_parent(_path)), + ), + Expanded( + child: Text( + _path, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: theme.hintColor), + ), + ), + TextButton.icon( + onPressed: _createFolder, + icon: const Icon(Icons.create_new_folder_outlined, size: 18), + label: const AppText('New folder'), + ), + ], + ), + ), + if (_error != null) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 6), + child: Text(_error!, + style: TextStyle(fontSize: 12, color: theme.colorScheme.error)), + ), + Expanded( + child: _loading + ? const Center( + child: SizedBox( + width: 22, + height: 22, + child: CircularProgressIndicator(strokeWidth: 2))) + : ListView( + children: [ + for (final entry in _dirs) + ListTile( + dense: true, + leading: + const Icon(Icons.folder_outlined, size: 20), + title: Text(entry.name, + maxLines: 1, overflow: TextOverflow.ellipsis), + trailing: + const Icon(Icons.chevron_right, size: 18), + onTap: () => _open(entry.path), + ), + if (_dirs.isEmpty && _error == null) + const Padding( + padding: EdgeInsets.all(24), + child: AppText('No folders here', + textAlign: TextAlign.center), + ), + ], + ), + ), + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 12), + child: SizedBox( + width: double.infinity, + child: FilledButton.icon( + onPressed: _adding || _loading ? null : _add, + icon: _adding + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)) + : const Icon(Icons.add, size: 18), + label: const AppText('Add this folder'), + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/project_picker.dart b/lib/widgets/project_picker.dart index 59b9e07..4a287c1 100644 --- a/lib/widgets/project_picker.dart +++ b/lib/widgets/project_picker.dart @@ -6,6 +6,7 @@ import 'package:flutter/material.dart'; import '../api/models.dart'; import '../l10n.dart'; import '../state.dart'; +import 'directory_picker.dart'; import 'project_icon.dart'; /// The "All projects" row of the stats scope picker, where a report is not @@ -117,6 +118,15 @@ class _ProjectPickerSheetState extends State<_ProjectPickerSheet> { setState(() => _refreshing = false); } + /// Browses the server's folders and returns with the new project selected. + Future _addProject() async { + final path = await showDirectoryPicker(context, app: widget.app); + if (path == null || !mounted) return; + final project = widget.app.projectFor(path) ?? + ProjectInfo(id: '', canonical: path, name: pathLeaf(path)); + Navigator.pop(context, ProjectChoice.project(project)); + } + @override Widget build(BuildContext context) { final chat = widget.selected == AppState.chatTarget; @@ -125,10 +135,25 @@ class _ProjectPickerSheetState extends State<_ProjectPickerSheet> { final loading = _refreshing && projects.isEmpty; return Column( children: [ - const Padding( - padding: EdgeInsets.fromLTRB(16, 14, 16, 6), - child: AppText('Choose project', - style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600)), + Padding( + padding: const EdgeInsets.fromLTRB(16, 6, 8, 0), + child: Row( + children: [ + const Expanded( + child: AppText('Choose project', + style: + TextStyle(fontSize: 17, fontWeight: FontWeight.w600)), + ), + TextButton.icon( + onPressed: _addProject, + style: TextButton.styleFrom( + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric(horizontal: 8)), + icon: const Icon(Icons.create_new_folder_outlined, size: 18), + label: const AppText('Add project'), + ), + ], + ), ), Expanded( child: loading diff --git a/pubspec.yaml b/pubspec.yaml index 4c24c8d..07cf1b1 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.5.6+506 +version: 0.5.7+507 environment: sdk: ^3.14.0 diff --git a/test/directory_picker_test.dart b/test/directory_picker_test.dart new file mode 100644 index 0000000..4031001 --- /dev/null +++ b/test/directory_picker_test.dart @@ -0,0 +1,175 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/client.dart'; +import 'package:openchamber/api/transport.dart'; +import 'package:openchamber/l10n.dart'; +import 'package:openchamber/state.dart'; +import 'package:openchamber/widgets/project_picker.dart'; + +/// A server with one project folder, and an add-project endpoint that records +/// the folder in both its project list and its settings document. +class _FakeTransport implements Transport { + final List> projects = []; + Map settings = {'projects': []}; + + @override + Future send(TransportRequest r) async { + Object? body; + switch (r.path) { + case '/api/fs/home': + body = {'home': '/home/me'}; + break; + case '/api/fs/list': + final path = r.query['path'] ?? '/'; + body = { + 'entries': [ + {'name': 'project', 'path': '$path/project', 'isDirectory': true}, + {'name': 'notes.txt', 'path': '$path/notes.txt', 'isDirectory': false}, + ], + }; + break; + case '/api/project': + body = projects; + break; + case '/api/config/settings': + body = settings; + break; + case '/api/openchamber/directory': + final payload = jsonDecode(utf8.decode(r.body!)) as Map; + final path = payload['path'] as String; + projects.add({'id': 'oc1', 'canonical': path, 'vcs': 'git'}); + settings = { + 'projects': [ + { + 'id': 'settings1', + 'path': path, + 'label': 'Project', + 'addedAt': 1, + } + ] + }; + body = {'success': true, 'path': path}; + break; + default: + body = {}; + } + return TransportResponse( + 200, + const {'content-type': 'application/json'}, + Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))), + ); + } + + @override + Future webSocket(String path, + {String? rawQuery, Map headers = const {}}) async => + throw UnimplementedError(); + + @override + void setBearerToken(String? token) {} + + @override + void close() {} +} + +void main() { + setUp(() => L10n.instance.apply(AppLanguage.en)); + tearDown(() => L10n.instance.apply(AppLanguage.zh)); + + testWidgets('a folder can be browsed and added as a project', + (tester) async { + final app = AppState(); + addTearDown(app.dispose); + final transport = _FakeTransport(); + app.client = Client(Uri.parse('http://test'), transport: transport); + + ProjectChoice? choice; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + choice = await showProjectPicker(context, + app: app, selected: AppState.chatTarget); + }, + child: const Text('open'), + ), + ), + ), + )); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); + + expect(find.text('Add project'), findsOneWidget); + await tester.tap(find.text('Add project')); + await tester.pumpAndSettle(); + + // The browser starts at home and lists folders, not files. + expect(find.text('project'), findsOneWidget); + expect(find.text('notes.txt'), findsNothing); + await tester.tap(find.text('project')); + await tester.pumpAndSettle(); + expect(find.text('/home/me/project'), findsWidgets); + + await tester.tap(find.text('Add this folder')); + await tester.pumpAndSettle(); + + expect(choice, isNotNull); + expect(choice!.canonical, '/home/me/project'); + expect(app.projects.any((p) => p.canonical == '/home/me/project'), isTrue); + }); + + testWidgets('a project added before it has a session is still listed', + (tester) async { + final app = AppState(); + addTearDown(app.dispose); + app.client = Client(Uri.parse('http://test'), transport: _SettingsOnly()); + + await app.refreshProjects(); + + expect(app.projects.map((p) => p.canonical), + contains('/home/me/fresh-project')); + expect(app.projectLabelFor('/home/me/fresh-project'), 'Fresh'); + }); +} + +/// `/api/project` is empty, but the settings document already has the folder: +/// the state must keep it so the picker can offer a first session there. +class _SettingsOnly implements Transport { + @override + Future send(TransportRequest r) async { + final body = switch (r.path) { + '/api/project' => [], + '/api/config/settings' => { + 'projects': [ + { + 'id': 'settings1', + 'path': '/home/me/fresh-project', + 'label': 'Fresh', + 'addedAt': 1, + } + ] + }, + _ => {}, + }; + return TransportResponse( + 200, + const {'content-type': 'application/json'}, + Stream.value(Uint8List.fromList(utf8.encode(jsonEncode(body)))), + ); + } + + @override + Future webSocket(String path, + {String? rawQuery, Map headers = const {}}) async => + throw UnimplementedError(); + + @override + void setBearerToken(String? token) {} + + @override + void close() {} +} diff --git a/test/running_state_test.dart b/test/running_state_test.dart index 96ccd35..2140ad3 100644 --- a/test/running_state_test.dart +++ b/test/running_state_test.dart @@ -3,6 +3,57 @@ import 'package:openchamber/api/models.dart'; import 'package:openchamber/state.dart'; void main() { + group('context reading', () { + late AppState app; + late ChatState chat; + + setUp(() { + app = AppState(); + chat = ChatState(app, Session(id: 'ses_a', title: '会话')); + }); + + tearDown(() { + chat.dispose(); + app.dispose(); + }); + + Message assistant() => Message( + id: 'a1', + type: 'assistant', + model: ModelRef('getdeepin/deepseek-flash', 'axonhub'), + tokens: TokenUsage(input: 33800, output: 810, cacheRead: 1792), + ); + + test('a known model reports its limit and no estimate', () { + app.modelLimits = { + 'axonhub/getdeepin/deepseek-flash': (1000000, 100000), + }; + chat.msgs = [assistant()]; + + final reading = chat.usageReading(); + expect(reading.$1, 36402); + expect(reading.$2, 1000000); + expect(reading.$5, isTrue); + expect(reading.$6, isFalse); + }); + + test('an unknown model keeps the ring and marks the window estimated', () { + app.modelLimits = {}; + chat.msgs = [assistant()]; + + final reading = chat.usageReading(); + expect(reading.$5, isTrue); + expect(reading.$6, isTrue); + expect(reading.$2, ChatState.estimatedContextWindow); + expect(reading.$4, greaterThan(0)); + }); + + test('no assistant tokens means no ring', () { + chat.msgs = [Message(id: 'u1', type: 'user')]; + expect(chat.usageReading().$5, isFalse); + }); + }); + // The app can be in the background while a turn starts or ends; the events // that said so never arrive, so the chat's running flag has to be taken // from the server again when the app comes back.