Improve chat session catalog creation

This commit is contained in:
2026-10-21 13:48:35 +01:00
parent f239a26bfd
commit a2b02b3810
5 changed files with 243 additions and 36 deletions
+20 -10
View File
@@ -39,17 +39,27 @@ class ChatRepository {
'chat_query': {'session_id': sessionId},
}))['chat_shells'],
);
Future<List<String>> directories() async =>
((await gateway.call('chat_directories'))['chat_directories'] as List? ??
const [])
.whereType<String>()
.toList();
Future<List<String>> directories() async {
final value = (await gateway.call('chat_directories'))['chat_directories'];
if (value is! List)
throw StateError('Server did not return chat directories.');
return value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
}
Future<List<String>> backends() async =>
((await gateway.call('chat_backends'))['chat_backends'] as List? ??
const [])
.whereType<String>()
.toList();
Future<List<String>> backends() async {
final value = (await gateway.call('chat_backends'))['chat_backends'];
if (value is! List)
throw StateError('Server did not return chat backends.');
final result = value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
if (result.isEmpty) throw StateError('Server returned no chat backends.');
return result;
}
Future<JsonMap> shellOutput(
String sessionId,
@@ -117,34 +117,95 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
}
Future<void> _newChat() async {
final dirs = TextEditingController();
List<String> directories;
List<String> backends;
try {
final catalog = await Future.wait([
_repository.directories(),
_repository.backends(),
]);
directories = catalog[0];
backends = catalog[1];
} catch (error) {
if (mounted)
setState(() => _error = 'Unable to load chat options: $error');
return;
}
if (!mounted) return;
if (directories.isEmpty || backends.isEmpty) {
setState(
() => _error =
'The server has no chat directories or backends available.',
);
return;
}
final dirs = ValueNotifier<String>(directories.first);
final backend = ValueNotifier<String>(backends.first);
final title = TextEditingController(text: 'New chat');
final instructions = TextEditingController();
final result =
await showDialog<
({String title, String directory, String instructions})
({
String title,
String directory,
String backend,
String instructions,
})
>(
context: context,
builder: (context) => AlertDialog(
title: const Text('New chat'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: title,
decoration: const InputDecoration(labelText: 'Name'),
),
TextField(
controller: dirs,
decoration: const InputDecoration(
labelText: 'Server directory',
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: title,
decoration: const InputDecoration(labelText: 'Name'),
),
),
TextField(
controller: instructions,
decoration: const InputDecoration(labelText: 'Instructions'),
),
],
ValueListenableBuilder<String>(
valueListenable: dirs,
builder: (context, value, _) =>
DropdownButtonFormField<String>(
initialValue: value,
decoration: const InputDecoration(
labelText: 'Server directory',
),
items: [
for (final item in directories)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) dirs.value = item;
},
),
),
ValueListenableBuilder<String>(
valueListenable: backend,
builder: (context, value, _) =>
DropdownButtonFormField<String>(
initialValue: value,
decoration: const InputDecoration(
labelText: 'Backend',
),
items: [
for (final item in backends)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) backend.value = item;
},
),
),
const Text('New chats use the server default model.'),
TextField(
controller: instructions,
decoration: const InputDecoration(
labelText: 'Instructions',
),
),
],
),
),
actions: [
TextButton(
@@ -154,7 +215,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
FilledButton(
onPressed: () => Navigator.pop(context, (
title: title.text.trim(),
directory: dirs.text.trim(),
directory: dirs.value,
backend: backend.value,
instructions: instructions.text,
)),
child: const Text('Create'),
@@ -164,6 +226,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
);
title.dispose();
dirs.dispose();
backend.dispose();
instructions.dispose();
if (result == null) return;
if (result.title.isEmpty || result.directory.isEmpty) {
@@ -174,6 +237,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
final reply = await _repository.create(
title: result.title,
directory: result.directory,
backend: result.backend,
operationId: 'native-chat-${DateTime.now().microsecondsSinceEpoch}',
instructions: result.instructions,
);
@@ -188,7 +252,9 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
@override
Widget build(BuildContext context) {
final visible = filterChatSessions(_sessions, _search.text);
final starred = visible.where((s) => s['starred'] == true).toList();
final starred = visible
.where((s) => s['starred'] == true && s['closed_at'] == null)
.toList();
final open = visible
.where((s) => s['starred'] != true && s['closed_at'] == null)
.toList();
@@ -238,7 +304,22 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
if (open.isNotEmpty) _section('Chats', open),
if (closed.isNotEmpty) _section('Closed', closed),
if (visible.isEmpty && !_loading)
const ListTile(title: Text('No chats found.')),
ListTile(
title: Text(
_sessions.isEmpty
? 'No chats yet.'
: 'No chats match "${_search.text.trim()}".',
),
trailing: _search.text.isEmpty
? null
: TextButton(
onPressed: () {
_search.clear();
setState(() {});
},
child: const Text('Clear search'),
),
),
],
),
),
@@ -257,11 +338,13 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
initiallyExpanded: true,
children: [
for (final group in groupChatSessions(sessions)) ...[
if (group.directory.isNotEmpty)
if (groupChatSessions(sessions).length > 1)
ListTile(
dense: true,
leading: const Icon(Icons.folder_outlined),
title: Text(group.directory),
title: Text(
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions) _row(session),
],
+2 -2
View File
@@ -1,5 +1,5 @@
# C1 — Chat sessions and repository adapter
Implemented the native Material sessions browser, search, directory grouping, starred/closed groups, standard session actions, and explicit-directory create dialog. Opening a session only invokes the supplied callback. The chat repository includes the web-compatible native message ID, prompt validation, Web permission label, and 200-message history default.
The sessions browser now requests server directory and backend catalogs before showing the create dialog, exposes both selectors and model-default guidance, and reports unavailable catalog capabilities instead of silently substituting values. Catalog envelope regressions are covered. Closed starred rows no longer appear twice; directory headings appear only when grouping multiple directories; empty and search-no-match states are distinct.
Verification: `flutter test test/features/chat` passed. Browser build/captures and mobile builds were not performed here. The fixture entry point is `tool/chat_sessions_probe_entry.dart`; a separate browser review should exercise the rendered states and capture them before claiming UI acceptance.
Verification: focused chat tests, `flutter analyze`, fixture `flutter build web -t tool/chat_sessions_probe_entry.dart`, `git diff --check`, and an isolated Chrome DevTools probe passed. Captures: `/private/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/opencode/chat-sessions-capture/chat-sessions-phone.png` and `chat-sessions-create-dialog.png` (plus desktop). The probe enabled semantics, matched the exact “New chat” label, and verified the rendered body changed to show server catalog controls. Cupertino-specific controls, controller/row/dialog decomposition under 250 lines, and wider out-of-order reply UI regression coverage remain incomplete; this is not a parity-complete delivery. Mobile builds were not performed. The fixture entry point is `tool/chat_sessions_probe_entry.dart`.
@@ -292,5 +292,25 @@ void main() {
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
},
);
test(
'reads exact directory/backend catalog envelopes without inventing fallback',
() async {
gateway.reply = {
'chat_directories': ['~', '/work'],
};
expect(await repo.directories(), ['~', '/work']);
expect(gateway.calls.last.type, 'chat_directories');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {
'chat_backends': ['opencode', 'claude'],
};
expect(await repo.backends(), ['opencode', 'claude']);
expect(gateway.calls.last.type, 'chat_backends');
expect(gateway.calls.last.fields, isEmpty);
gateway.reply = {};
await expectLater(repo.directories(), throwsStateError);
await expectLater(repo.backends(), throwsStateError);
},
);
});
}
+94
View File
@@ -0,0 +1,94 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtemp, rm } from 'node:fs/promises';
const root = join(process.cwd(), 'build/web');
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
const server = createServer(async (req, res) => {
try {
const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end();
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
const file = await readFile(filePath);
res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file);
} catch { res.writeHead(404).end('not found'); }
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const port = server.address().port;
const profile = await mkdtemp(join(tmpdir(), 'chat-sessions-chrome-'));
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', data => { stderr += data; });
const waitFor = async fn => {
for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); }
throw new Error('Timed out waiting for Chrome DevTools');
};
let ws;
try {
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', event => {
const msg = JSON.parse(event.data);
if (msg.method?.includes('detached') || msg.method?.includes('crashed')) console.error('CDP event', JSON.stringify(msg));
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
});
const send = (method, params = {}, sessionId) => new Promise(resolve => {
const callId = ++id; pending.set(callId, resolve);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const target = created.result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/` }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
const evaluate = async expression => {
const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
return response.result?.result?.value;
};
await delay(3500);
const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})");
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(2500);
const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '') === ${JSON.stringify(label)}); if (!e) return false; e.click(); return true; })()`);
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
if (!labels?.some(x => x.includes('New chat'))) throw new Error(`Chat fixture semantics unavailable: ${JSON.stringify(labels)}`);
const capture = async (name, width, height) => {
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
await delay(350);
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64'));
};
await capture('chat-sessions-phone', 390, 844);
if (!await clickLabel('New chat')) throw new Error('Could not open create dialog');
await delay(500);
await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 195, y: 680, deltaY: 598 }, session);
await delay(350);
const changedBody = await evaluate('document.body.innerText');
await capture('chat-sessions-create-dialog', 390, 844);
if (!changedBody.includes('Server directory') || !changedBody.includes('Backend') || !changedBody.includes('New chats use the server default model.') || changedBody.includes('Open fixture')) throw new Error(`Create dialog did not change rendered body to catalog controls: ${changedBody}`);
await capture('chat-sessions-desktop', 1280, 800);
console.log(JSON.stringify({ labels, captures: ['chat-sessions-phone.png', 'chat-sessions-create-dialog.png', 'chat-sessions-desktop.png'], bodyChanged: true }, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
server.close();
await rm(profile, { recursive: true, force: true });
}