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
This commit is contained in:
blumia committed 2026-11-27 09:26:14 +08:00
1 parent bd8afeb686
commit c6b5a870c6
11 files changed
+708 -22

No files matched your search

+16
View File
@@ -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<String> 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.
+12
View File
@@ -11,7 +11,9 @@ const Map<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> chineseStrings = {
'Generating summary…': '正在生成摘要…',
'Generating; you can still type…': '生成中,仍可输入…',
'Global memory': '全局记忆',
'Go': '前往',
'Goal': '目标',
'Got it': '知道了',
'Help & about': '帮助与关于',
@@ -261,6 +270,7 @@ const Map<String, String> 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<String, String> 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<String, String> chineseStrings = {
'Success rate': '成功率',
'Failed': '失败',
'Unfinished': '未完成',
'Up': '上一级',
'Updated {0}': '更新于 {0}',
'Subagents: {0}': '子代理:{0}',
'In {0} · Out {1} · Cache {2}': '输入 {0} · 输出 {1} · 缓存 {2}',
+12 -3
View File
@@ -2078,7 +2078,10 @@ class _ChatScreenState extends State<ChatScreen> {
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<ChatScreen> {
],
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)),
],
),
),
+72 -11
View File
@@ -141,6 +141,9 @@ class AppState extends ChangeNotifier {
String? chatsRoot;
List<String> 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 = <String, Map<String, dynamic>>{};
final settingsRows = <Map<String, dynamic>>[];
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 = <String>{};
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<ProjectInfo?> 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<String, Future<Uint8List?>> _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 {
+322
View File
@@ -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<String?> showDirectoryPicker(BuildContext context,
{required AppState app}) {
return showModalBottomSheet<String>(
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<FsEntry> _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<void> _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<void> _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<void> _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<String?> _askFolderName() async {
final controller = TextEditingController();
final name = await showDialog<String>(
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<void> _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'),
),
),
),
),
],
);
}
}
+29 -4
View File
@@ -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<void> _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