diff --git a/PLAN.md b/PLAN.md index 2f009fc..4365e20 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,18 @@ --- +## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream>`,SSE 与文件下载仍可流式读)、`abstract Transport`;`DirectTransport` 就是原来的直连实现(HTTP CONNECT、SOCKS5/socks5h、自签与指纹固定、SHA-256 内置实现),`Client` 只保留业务方法,构造时可注入别的 Transport。行为与之前逐字节一致,后续 Private Relay 只需再加一个 `RelayTransport` | +| 历史图片 | 用户消息里的 `files` 现在从服务端读 `data`(base64)并缓存解码结果;气泡内显示缩略图,点按打开图片预览(与工具行读图共用同一个对话框)。无内联图片时仍回退到刚发送时的本地路径 | +| 原生表单 | `FormInfo`/`AgentFormField`/`FormOption`/`FormWhen` 按 `@opencode/client` 2.2.7 的 schema 建模;`GET /api/session/:id/form` 拉取待答问题,`POST …/form/:fid/reply` 提交、`DELETE …/form/:fid` 取消;订阅 `form.created/replied/cancelled`。输入框上方是表单卡片:string(带 options 时用 chip + 「其他…」)、multiselect、boolean(开关)、number/integer、external(链接确认);`when` 控制字段显隐,必填项(含「必须打开」的开关)不满足时提示并阻止发送,最多 360 px 内部滚动 | +| 左右分栏 | 新增 `lib/screens/home_screen.dart`:手机(< 840 px)把会话列表放进左侧 Drawer、聊天占满屏幕、顶栏是菜单键;宽屏(平板/桌面)左侧常驻 320 px 会话列 + 聊天。两者共用同一个 `SessionListPane`(会话选中高亮、搜索、新建、服务器、重命名/归档/删除)。启动时若还没有打开的会话,自动打开最新一条(与官方手机端一致) | +| 版本 | **0.3.10(code 310)** | + +--- + ## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0) **背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo; diff --git a/README.md b/README.md index 0e88b2c..748c9eb 100644 --- a/README.md +++ b/README.md @@ -5,23 +5,25 @@ 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.3.9 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.3.10 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning), 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, -current one checked), copy / fork / revert, attachments (photos/files), -permissions. Android 7.0 (API 24)+, plus a Linux desktop target used for local -testing. +current one checked), copy / fork / revert, attachments (photos/files, kept +after a reload), the agent's native forms, permissions. A phone opens the +session list as the left drawer and a wide window (tablet, desktop) shows it +beside the chat. Android 7.0 (API 24)+, plus a Linux desktop target used for +local testing. ## What is here | Path | What | | --- | --- | -| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback` | +| `lib/api/` | Dart OpenChamber client: auth, sessions, messages, SSE, models/agents, forms, permissions, prompt/interrupt/fork/revert, `/api/fs/raw`; every request goes through `Transport` (today `DirectTransport`: HTTP/HTTPS proxies via `HttpClient.findProxy`, SOCKS5/socks5h via `socks5_proxy`, pinning/self-signed via `badCertificateCallback`), so a relay tunnel only adds an implementation | | `lib/storage.dart` | Saved servers in `shared_preferences`, tokens in `flutter_secure_storage` (Android Keystore) | | `lib/state.dart` | The app state: connections, live sessions, the open chat, and SSE event folding | -| `lib/screens/` | Servers, sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets); the message list is reversed so older pages grow above without moving the viewport | +| `lib/screens/` | Servers, the connected shell (`home_screen.dart`: drawer on a phone, two columns from 840 px), sessions, chat (streaming Markdown via `gpt_markdown`, composer, sheets, the native form dock, the files sidebar); the message list is reversed so older pages grow above without moving the viewport | | `lib/widgets/` | The context usage ring | Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer diff --git a/lib/api/client.dart b/lib/api/client.dart index d403421..7427dea 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -4,11 +4,8 @@ library; import 'dart:async'; import 'dart:convert'; -import 'dart:io'; - -import 'package:socks5_proxy/socks_client.dart'; - import 'models.dart'; +import 'transport.dart'; class ApiError implements Exception { final int status; @@ -18,111 +15,23 @@ class ApiError implements Exception { String toString() => message.isEmpty ? 'HTTP $status' : message; } -/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one. -class _ProxyConfig { - final String scheme; // http | https | socks5 | socks5h - final String host; - final int port; - final String? username; - final String? password; - _ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]); - - bool get socks => scheme.startsWith('socks'); -} - -_ProxyConfig? _parseProxy(String? raw) { - final s = raw?.trim() ?? ''; - if (s.isEmpty) return null; - var normalized = s; - if (!normalized.contains('://')) normalized = 'http://$normalized'; - final uri = Uri.tryParse(normalized); - if (uri == null || uri.host.isEmpty) { - throw ArgumentError('代理地址无效:$raw'); - } - final scheme = uri.scheme.toLowerCase(); - final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h'; - final http = scheme == 'http' || scheme == 'https'; - if (!socks && !http) { - throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)'); - } - String? user; - String? pass; - if (uri.userInfo.isNotEmpty) { - final i = uri.userInfo.indexOf(':'); - if (i >= 0) { - user = Uri.decodeComponent(uri.userInfo.substring(0, i)); - pass = Uri.decodeComponent(uri.userInfo.substring(i + 1)); - } else { - user = Uri.decodeComponent(uri.userInfo); - } - } - final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080); - return _ProxyConfig(scheme, uri.host, port, user, pass); -} - class Client { final Uri base; - final String? proxy; // http://host:port or socks5://host:port - final bool insecure; - final String? fingerprint; + + /// Every request and the event stream go through here; today a direct + /// connection, later one that can also be a relay tunnel. + final Transport transport; String? token; - late HttpClient _http; - _ProxyConfig? _proxyConfig; - InternetAddress? _proxyAddress; Client( this.base, { - this.proxy, - this.insecure = false, - this.fingerprint, - }) { - _http = HttpClient(); - _http.connectionTimeout = const Duration(seconds: 20); - _proxyConfig = _parseProxy(proxy); - if (_proxyConfig != null && _proxyConfig!.socks) { - // Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy - // package tunnels the socket and hands a Socket back to the client. - _http.connectionFactory = (uri, _, __) async { - final address = await _resolveProxyAddress(); - final settings = ProxySettings(address, _proxyConfig!.port, - username: _proxyConfig!.username, password: _proxyConfig!.password); - final tunnel = SocksTCPClient.connect( - [settings], - // A unix-type address carries the host name, so the proxy resolves - // it (socks5h semantics) instead of resolving it here. - InternetAddress(uri.host, type: InternetAddressType.unix), - uri.port, - ); - if (uri.scheme == 'https') { - final secure = tunnel.then( - (s) => s.secure(uri.host, onBadCertificate: _badCertificate)); - return ConnectionTask.fromSocket(secure, () {}); - } - return ConnectionTask.fromSocket(tunnel, () {}); - }; - } else if (_proxyConfig != null) { - _http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}'; - } - _http.badCertificateCallback = (cert, host, port) => _badCertificate(cert); - } - - Future _resolveProxyAddress() async { - if (_proxyAddress != null) return _proxyAddress!; - final addresses = await InternetAddress.lookup(_proxyConfig!.host); - if (addresses.isEmpty) { - throw const SocketException('无法解析代理主机'); - } - return _proxyAddress = addresses.first; - } - - /// True for a certificate the app was told to accept: the user trusts any - /// (insecure), or its SHA-256 matches the pinned fingerprint. - bool _badCertificate(X509Certificate cert) { - if (insecure) return true; - final pinned = fingerprint?.replaceAll(':', '').toLowerCase(); - if (pinned == null || pinned.isEmpty) return false; - return _sha256(cert.der) == pinned; - } + String? proxy, + bool insecure = false, + String? fingerprint, + Transport? transport, + }) : transport = transport ?? + DirectTransport(base, + proxy: proxy, insecure: insecure, fingerprint: fingerprint); String get baseUrl => base.toString(); @@ -290,6 +199,39 @@ class Client { return data is Map ? data['id'] as String? : null; } + // -------------------------------------------------------------- forms + + /// The agent's pending questions in this session. + Future> forms(String sessionId, {String? directory}) async { + final r = await _json( + 'GET', '/api/session/${Uri.encodeComponent(sessionId)}/form', + directory: directory); + return [ + for (final f in (r['data'] as List? ?? [])) + if (f is Map) FormInfo.fromJson(f), + ]; + } + + Future replyForm(String sessionId, String formId, + Map answer, {String? directory}) async { + await _json( + 'POST', + '/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}/reply', + body: {'answer': answer}, + directory: directory); + } + + Future cancelForm(String sessionId, String formId, + {String? message, String? directory}) async { + await _json( + 'DELETE', + '/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}', + query: { + if (message != null && message.isNotEmpty) 'message': message, + }, + directory: directory); + } + /// The commands this directory registers (`/api/command`). Future>> commands({String? directory}) async { final r = await _json('GET', '/api/command', directory: directory); @@ -357,10 +299,11 @@ class Client { }, directory: directory, rawDirectory: true); + final bytes = await res.collect(); if (res.statusCode < 200 || res.statusCode >= 300) { - throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true)); + throw ApiError(res.statusCode, utf8.decode(bytes, allowMalformed: true)); } - return res.body; + return bytes; } // ------------------------------------------------------------ files @@ -383,7 +326,7 @@ class Client { Future fsRead(String path, {String? directory}) async { final res = await _request('GET', '/api/fs/read', query: {'path': path}, directory: directory, rawDirectory: true); - final text = utf8.decode(res.body, allowMalformed: true); + final text = utf8.decode(await res.collect(), allowMalformed: true); if (res.statusCode < 200 || res.statusCode >= 300) { throw ApiError(res.statusCode, text.trim()); } @@ -419,27 +362,29 @@ class Client { /// when the connection drops; the caller restarts it with backoff. Stream> streamEvents({List? types}) async* { // `types` repeats: a Map would keep only the last one. - var uri = base.resolve('/api/event'); - if (types != null && types.isNotEmpty) { - final q = types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&'); - uri = Uri.parse('$uri?$q'); - } - final req = await _http.openUrl('GET', uri); - req.headers.set('Accept', 'text/event-stream'); - req.headers.set('Cache-Control', 'no-cache'); - if (token != null && token!.isNotEmpty) { - req.headers.set('Authorization', 'Bearer $token'); - } - final res = await req.close(); - if (res.statusCode != 200) { - throw ApiError(res.statusCode, 'event stream failed'); + final query = types == null || types.isEmpty + ? null + : types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&'); + final res = await transport.send(TransportRequest( + method: 'GET', + path: '/api/event', + rawQuery: query, + headers: { + 'accept': 'text/event-stream', + 'cache-control': 'no-cache', + 'user-agent': 'openchamber-native/0.3', + if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token', + }, + )); + if (res.status != 200) { + throw ApiError(res.status, 'event stream failed'); } String data = ''; // The server sends a `: heartbeat` comment every few seconds; if nothing // at all arrives for a while the connection is dead and the caller should // reconnect rather than wait on a half-open socket. final lines = utf8.decoder - .bind(res) + .bind(res.body) .transform(const LineSplitter()) .timeout(const Duration(seconds: 30)); await for (final line in lines) { @@ -471,7 +416,7 @@ class Client { directory: directory, partShells: partShells, rawDirectory: rawDirectory); - final text = utf8.decode(res.body, allowMalformed: true); + final text = utf8.decode(await res.collect(), allowMalformed: true); if (res.statusCode < 200 || res.statusCode >= 300) { String msg = text; try { @@ -494,127 +439,40 @@ class Client { String? directory, bool partShells = false, bool rawDirectory = false}) async { - final q = Uri(queryParameters: query ?? {}); - final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters); - final req = await _http.openUrl(method, uri); - // Every header must be set before the body, which finalizes them. - req.headers.set('Accept', path == '/api/event' ? 'text/event-stream' : 'application/json'); - req.headers.set('User-Agent', 'openchamber-native/0.3'); - if (token != null && token!.isNotEmpty) { - req.headers.set('Authorization', 'Bearer $token'); - } + final headers = { + 'accept': path == '/api/event' ? 'text/event-stream' : 'application/json', + 'user-agent': 'openchamber-native/0.3', + if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token', + }; if (directory != null && directory.isNotEmpty) { // The file routes compare this header with the workspace path, so they // need it as written; the rest of the API wants it URI-encoded. - req.headers.set('x-opencode-directory', - rawDirectory ? directory : Uri.encodeComponent(directory)); - if (!rawDirectory) { - req.headers.set('x-opencode-directory-encoding', 'uri'); - } + headers['x-opencode-directory'] = + rawDirectory ? directory : Uri.encodeComponent(directory); + if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri'; } - if (partShells) { - req.headers.set('x-openchamber-part-shells', 'v1'); - } - if (path == '/api/event') { - req.headers.set('Cache-Control', 'no-cache'); - } - if (body != null) { - req.headers.contentType = ContentType.json; - req.write(jsonEncode(body)); - } - final res = await req.close(); - final bodyBytes = await res.fold>([], (a, b) => a..addAll(b)); - return _Response(res.statusCode, bodyBytes); + if (partShells) headers['x-openchamber-part-shells'] = 'v1'; + if (path == '/api/event') headers['cache-control'] = 'no-cache'; + final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body)); + if (bodyBytes != null) headers['content-type'] = 'application/json'; + final res = await transport.send(TransportRequest( + method: method, + path: path, + query: query ?? const {}, + headers: headers, + body: bodyBytes, + )); + return _Response(res.status, res.body); } - void close() => _http.close(); + void close() => transport.close(); } class _Response { final int statusCode; - final List body; + final Stream> body; _Response(this.statusCode, this.body); -} -String _sha256(List bytes) { - return _Digest.sha256Hex(bytes); -} - -// Minimal SHA-256, so the client has no native dependencies for pinning. -class _Digest { - static String sha256Hex(List bytes) { - final h = List.from(const [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, - ]); - final k = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, - ]; - final m = List.from(bytes); - final bitLen = m.length * 8; - m.add(0x80); - while (m.length % 64 != 56) { - m.add(0); - } - for (var i = 7; i >= 0; i--) { - m.add((bitLen >> (8 * i)) & 0xff); - } - final words = List.generate(m.length ~/ 4, (i) => - (m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]); - var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; - for (var i = 0; i < words.length; i += 16) { - final w = List.filled(64, 0); - for (var j = 0; j < 16; j++) { - w[j] = words[i + j]; - } - for (var j = 16; j < 64; j++) { - final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3); - final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10); - w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff; - } - var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh; - for (var j = 0; j < 64; j++) { - final S1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25); - final ch = (te & tf) ^ ((~te) & tg); - final t1 = (th + S1 + ch + k[j] + w[j]) & 0xffffffff; - final S0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22); - final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc); - final t2 = (S0 + maj) & 0xffffffff; - th = tg; - tg = tf; - tf = te; - te = (td + t1) & 0xffffffff; - td = tc; - tc = tb; - tb = ta; - ta = (t1 + t2) & 0xffffffff; - } - a = (a + ta) & 0xffffffff; - b = (b + tb) & 0xffffffff; - c = (c + tc) & 0xffffffff; - d = (d + td) & 0xffffffff; - e = (e + te) & 0xffffffff; - f = (f + tf) & 0xffffffff; - g = (g + tg) & 0xffffffff; - hh = (hh + th) & 0xffffffff; - } - final out = List.filled(32, 0); - final vals = [a, b, c, d, e, f, g, hh]; - for (var i = 0; i < 8; i++) { - out[i * 4] = (vals[i] >> 24) & 0xff; - out[i * 4 + 1] = (vals[i] >> 16) & 0xff; - out[i * 4 + 2] = (vals[i] >> 8) & 0xff; - out[i * 4 + 3] = vals[i] & 0xff; - } - return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); - } - - static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff); + Future> collect() => + body.fold>([], (a, b) => a..addAll(b)); } diff --git a/lib/api/models.dart b/lib/api/models.dart index 5f6777a..9066cba 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -291,9 +291,153 @@ class Message { class FileAttachment { final String name; final String mime; - FileAttachment(this.name, this.mime); - factory FileAttachment.fromJson(Map j) => - FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? ''); + + /// Base64 of the file the user attached, as the server stores it. + final String data; + + /// 'inline' | 'path' — where the bytes came from, when the server says. + final String source; + + FileAttachment(this.name, this.mime, {this.data = '', this.source = ''}); + + bool get isImage => mime.startsWith('image/') && data.isNotEmpty; + + factory FileAttachment.fromJson(Map j) => FileAttachment( + j['name'] as String? ?? '', + j['mime'] as String? ?? '', + data: j['data'] as String? ?? '', + // Stored messages carry `{type: 'inline'}` here; keep only text. + source: j['source'] is String ? j['source'] as String : '', + ); +} + +/// One row of a native form's choice control. +class FormOption { + final String value; + final String label; + final String? description; + const FormOption(this.value, this.label, [this.description]); + factory FormOption.fromJson(Map j) => FormOption( + j['value'] as String? ?? '', + j['label'] as String? ?? j['value'] as String? ?? '', + j['description'] as String?, + ); +} + +/// `when` makes a field visible only while another field holds a value. +class FormWhen { + final String key; + final String op; // eq | neq + final Object? value; + const FormWhen(this.key, this.op, this.value); + factory FormWhen.fromJson(Map j) => FormWhen( + j['key'] as String? ?? '', + j['op'] as String? ?? 'eq', + j['value'], + ); +} + +/// A field of a form request: string, number, integer, boolean, multiselect +/// or external (a link the user acknowledges). +class AgentFormField { + final String key; + final String type; + final String? title; + final String? description; + final String? placeholder; + final String? format; + final String? url; + final bool required; + final bool hidden; + final bool custom; + final Object? defaultValue; + final num? minimum; + final num? maximum; + final int? minLength; + final int? maxLength; + final int? minItems; + final int? maxItems; + final List options; + final List when; + + const AgentFormField({ + required this.key, + required this.type, + this.title, + this.description, + this.placeholder, + this.format, + this.url, + this.required = false, + this.hidden = false, + this.custom = false, + this.defaultValue, + this.minimum, + this.maximum, + this.minLength, + this.maxLength, + this.minItems, + this.maxItems, + this.options = const [], + this.when = const [], + }); + + factory AgentFormField.fromJson(Map j) { + num? numOf(Object? v) => v is num ? v : null; + return AgentFormField( + key: j['key'] as String? ?? '', + type: j['type'] as String? ?? 'string', + title: j['title'] as String?, + description: j['description'] as String?, + placeholder: j['placeholder'] as String?, + format: j['format'] as String?, + url: j['url'] as String?, + required: j['required'] as bool? ?? false, + hidden: j['hidden'] as bool? ?? false, + custom: j['custom'] as bool? ?? false, + defaultValue: j['default'], + minimum: numOf(j['minimum']), + maximum: numOf(j['maximum']), + minLength: (j['minLength'] as num?)?.toInt(), + maxLength: (j['maxLength'] as num?)?.toInt(), + minItems: (j['minItems'] as num?)?.toInt(), + maxItems: (j['maxItems'] as num?)?.toInt(), + options: [ + for (final o in (j['options'] as List? ?? [])) + if (o is Map) FormOption.fromJson(o), + ], + when: [ + for (final w in (j['when'] as List? ?? [])) + if (w is Map) FormWhen.fromJson(w), + ], + ); + } + + String get label => (title == null || title!.isEmpty) ? key : title!; +} + +/// A blocking question from the agent. The client answers every visible field +/// at once; the answer map is keyed by field key. +class FormInfo { + final String id; + final String sessionID; + final String title; + final List fields; + const FormInfo({ + required this.id, + required this.sessionID, + required this.title, + required this.fields, + }); + factory FormInfo.fromJson(Map j) => FormInfo( + id: j['id'] as String? ?? '', + sessionID: j['sessionID'] as String? ?? '', + title: j['title'] as String? ?? '', + fields: [ + for (final f in (j['fields'] as List? ?? [])) + if (f is Map) AgentFormField.fromJson(f), + ], + ); } class Page { diff --git a/lib/api/transport.dart b/lib/api/transport.dart new file mode 100644 index 0000000..003002a --- /dev/null +++ b/lib/api/transport.dart @@ -0,0 +1,255 @@ +// How the client reaches the server. Today that is a direct HttpClient with +// the configured proxy and certificate rules; a relay transport can implement +// the same interface over its encrypted tunnel without any caller changing. +import 'dart:async'; +import 'dart:io'; + +import 'package:socks5_proxy/socks_client.dart'; + +/// One request: a method, a path relative to the server root, its query, the +/// headers already decided by [Client] (auth, directory, accept, …) and an +/// optional complete body. +class TransportRequest { + final String method; + final String path; + final Map query; + final Map headers; + final List? body; + + /// When set, used verbatim as the query string (the event stream repeats + /// `types`, which a Map cannot express). + final String? rawQuery; + const TransportRequest({ + required this.method, + required this.path, + this.query = const {}, + this.headers = const {}, + this.body, + this.rawQuery, + }); +} + +/// A reply whose head is in hand and whose body still streams (SSE and file +/// downloads rely on that). +class TransportResponse { + final int status; + final Map headers; + final Stream> body; + const TransportResponse(this.status, this.headers, this.body); +} + +/// The one seam every request goes through. +abstract class Transport { + /// Sends [request], completing when the reply head arrives. + Future send(TransportRequest request); + + /// Releases whatever sockets the transport holds. + void close(); +} + +/// A proxy as configured: an HTTP CONNECT proxy, or a SOCKS5 one. +class ProxyConfig { + final String scheme; // http | https | socks5 | socks5h + final String host; + final int port; + final String? username; + final String? password; + ProxyConfig(this.scheme, this.host, this.port, [this.username, this.password]); + + bool get socks => scheme.startsWith('socks'); +} + +ProxyConfig? parseProxy(String? raw) { + final s = raw?.trim() ?? ''; + if (s.isEmpty) return null; + var normalized = s; + if (!normalized.contains('://')) normalized = 'http://$normalized'; + final uri = Uri.tryParse(normalized); + if (uri == null || uri.host.isEmpty) { + throw ArgumentError('代理地址无效:$raw'); + } + final scheme = uri.scheme.toLowerCase(); + final socks = scheme == 'socks' || scheme == 'socks5' || scheme == 'socks5h'; + final http = scheme == 'http' || scheme == 'https'; + if (!socks && !http) { + throw ArgumentError('不支持的代理协议:$scheme(支持 http、https、socks5、socks5h)'); + } + String? user; + String? pass; + if (uri.userInfo.isNotEmpty) { + final i = uri.userInfo.indexOf(':'); + if (i >= 0) { + user = Uri.decodeComponent(uri.userInfo.substring(0, i)); + pass = Uri.decodeComponent(uri.userInfo.substring(i + 1)); + } else { + user = Uri.decodeComponent(uri.userInfo); + } + } + final port = uri.hasPort ? uri.port : (socks ? 1080 : 8080); + return ProxyConfig(scheme, uri.host, port, user, pass); +} + +/// Direct HTTP: the server's own URL, optionally through an HTTP or SOCKS5 +/// proxy, with the self-signed certificate rules. +class DirectTransport implements Transport { + final Uri base; + final bool insecure; + final String? fingerprint; + late final HttpClient _http; + ProxyConfig? _proxyConfig; + InternetAddress? _proxyAddress; + + DirectTransport( + this.base, { + String? proxy, + this.insecure = false, + this.fingerprint, + }) { + _http = HttpClient()..connectionTimeout = const Duration(seconds: 20); + _proxyConfig = parseProxy(proxy); + if (_proxyConfig != null && _proxyConfig!.socks) { + // Dart's HttpClient has no SOCKS support in findProxy; the socks5_proxy + // package tunnels the socket and hands a Socket back to the client. + _http.connectionFactory = (uri, _, __) async { + final address = await _resolveProxyAddress(); + final settings = ProxySettings(address, _proxyConfig!.port, + username: _proxyConfig!.username, password: _proxyConfig!.password); + final tunnel = SocksTCPClient.connect( + [settings], + // A unix-type address carries the host name, so the proxy resolves + // it (socks5h semantics) instead of resolving it here. + InternetAddress(uri.host, type: InternetAddressType.unix), + uri.port, + ); + if (uri.scheme == 'https') { + final secure = tunnel.then( + (s) => s.secure(uri.host, onBadCertificate: _badCertificate)); + return ConnectionTask.fromSocket(secure, () {}); + } + return ConnectionTask.fromSocket(tunnel, () {}); + }; + } else if (_proxyConfig != null) { + _http.findProxy = (_) => 'PROXY ${_proxyConfig!.host}:${_proxyConfig!.port}'; + } + _http.badCertificateCallback = (cert, host, port) => _badCertificate(cert); + } + + Future _resolveProxyAddress() async { + if (_proxyAddress != null) return _proxyAddress!; + final addresses = await InternetAddress.lookup(_proxyConfig!.host); + if (addresses.isEmpty) { + throw const SocketException('无法解析代理主机'); + } + return _proxyAddress = addresses.first; + } + + /// True for a certificate the app was told to accept: the user trusts any + /// (insecure), or its SHA-256 matches the pinned fingerprint. + bool _badCertificate(X509Certificate cert) { + if (insecure) return true; + final pinned = fingerprint?.replaceAll(':', '').toLowerCase(); + if (pinned == null || pinned.isEmpty) return false; + return sha256Hex(cert.der) == pinned; + } + + @override + Future send(TransportRequest r) async { + final query = r.rawQuery ?? + Uri(queryParameters: r.query.isEmpty ? null : r.query).query; + final uri = base.resolve(r.path).replace(query: query.isEmpty ? null : query); + final req = await _http.openUrl(r.method, uri); + // Every header must be set before the body, which finalizes them. + r.headers.forEach(req.headers.set); + if (r.body != null) req.add(r.body!); + final res = await req.close(); + final headers = {}; + res.headers.forEach((name, values) { + headers[name.toLowerCase()] = values.join(', '); + }); + return TransportResponse(res.statusCode, headers, res); + } + + @override + void close() => _http.close(); +} + +String sha256Hex(List bytes) => _Digest.sha256Hex(bytes); + +// Minimal SHA-256, so the client has no native dependencies for pinning. +class _Digest { + static String sha256Hex(List bytes) { + final h = List.from(const [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]); + const k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ]; + final m = List.from(bytes); + final bitLen = m.length * 8; + m.add(0x80); + while (m.length % 64 != 56) { + m.add(0); + } + for (var i = 7; i >= 0; i--) { + m.add((bitLen >> (8 * i)) & 0xff); + } + final words = List.generate(m.length ~/ 4, (i) => + (m[i * 4] << 24) | (m[i * 4 + 1] << 16) | (m[i * 4 + 2] << 8) | m[i * 4 + 3]); + var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (var i = 0; i < words.length; i += 16) { + final w = List.filled(64, 0); + for (var j = 0; j < 16; j++) { + w[j] = words[i + j]; + } + for (var j = 16; j < 64; j++) { + final s0 = _rotr(w[j - 15], 7) ^ _rotr(w[j - 15], 18) ^ (w[j - 15] >> 3); + final s1 = _rotr(w[j - 2], 17) ^ _rotr(w[j - 2], 19) ^ (w[j - 2] >> 10); + w[j] = (w[j - 16] + s0 + w[j - 7] + s1) & 0xffffffff; + } + var ta = a, tb = b, tc = c, td = d, te = e, tf = f, tg = g, th = hh; + for (var j = 0; j < 64; j++) { + final s1 = _rotr(te, 6) ^ _rotr(te, 11) ^ _rotr(te, 25); + final ch = (te & tf) ^ ((~te) & tg); + final t1 = (th + s1 + ch + k[j] + w[j]) & 0xffffffff; + final s0 = _rotr(ta, 2) ^ _rotr(ta, 13) ^ _rotr(ta, 22); + final maj = (ta & tb) ^ (ta & tc) ^ (tb & tc); + final t2 = (s0 + maj) & 0xffffffff; + th = tg; + tg = tf; + tf = te; + te = (td + t1) & 0xffffffff; + td = tc; + tc = tb; + tb = ta; + ta = (t1 + t2) & 0xffffffff; + } + a = (a + ta) & 0xffffffff; + b = (b + tb) & 0xffffffff; + c = (c + tc) & 0xffffffff; + d = (d + td) & 0xffffffff; + e = (e + te) & 0xffffffff; + f = (f + tf) & 0xffffffff; + g = (g + tg) & 0xffffffff; + hh = (hh + th) & 0xffffffff; + } + final out = List.filled(32, 0); + final vals = [a, b, c, d, e, f, g, hh]; + for (var i = 0; i < 8; i++) { + out[i * 4] = (vals[i] >> 24) & 0xff; + out[i * 4 + 1] = (vals[i] >> 16) & 0xff; + out[i * 4 + 2] = (vals[i] >> 8) & 0xff; + out[i * 4 + 3] = vals[i] & 0xff; + } + return out.map((e) => e.toRadixString(16).padLeft(2, '0')).join(); + } + + static int _rotr(int x, int n) => (x >> n) | ((x << (32 - n)) & 0xffffffff); +} diff --git a/lib/main.dart b/lib/main.dart index 7720d61..253b75d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; +import 'screens/home_screen.dart'; import 'screens/servers_screen.dart'; -import 'screens/sessions_screen.dart'; import 'state.dart'; void main() { @@ -45,7 +45,7 @@ class _OpenChamberAppState extends State builder: (context, _) { final home = app.client == null ? ServersScreen(app: app) - : SessionsScreen(app: app); + : HomeScreen(app: app); return MaterialApp( title: 'OpenChamber', theme: ThemeData( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e72220c..9aff5fd 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -18,7 +18,16 @@ import 'files_panel.dart'; class ChatScreen extends StatefulWidget { final AppState app; final Session session; - const ChatScreen({super.key, required this.app, required this.session}); + + /// Opens the session drawer. Null where the list is always on screen (a + /// wide layout), so no menu button is shown there. + final VoidCallback? onOpenSessions; + const ChatScreen({ + super.key, + required this.app, + required this.session, + this.onOpenSessions, + }); @override State createState() => _ChatScreenState(); @@ -36,6 +45,9 @@ class _ChatScreenState extends State { List<_Attach> _attachments = []; bool _attaching = false; + /// Decoded user attachments, so a rebuild does not base64-decode again. + final Map _userImages = {}; + /// `/` palette: the highlighted row, and the draft Esc closed it at. int _slashIndex = 0; String? _slashDismissed; @@ -90,6 +102,13 @@ class _ChatScreenState extends State { final theme = Theme.of(context); return Scaffold( appBar: AppBar( + leading: widget.onOpenSessions == null + ? null + : IconButton( + icon: const Icon(Icons.menu), + tooltip: '会话', + onPressed: widget.onOpenSessions, + ), title: Text(widget.session.title.isEmpty ? '会话' : widget.session.title, maxLines: 1, overflow: TextOverflow.ellipsis), actions: [ @@ -131,6 +150,7 @@ class _ChatScreenState extends State { ), Expanded(child: _messageList()), _permissions(), + _forms(), _composer(), ], ), @@ -376,8 +396,15 @@ class _ChatScreenState extends State { Widget _userRow(String id) { final m = chat.byId[id]!; - final images = chat.imagePaths[id] ?? []; final theme = Theme.of(context); + // The server keeps attached images in the message; the paths only cover + // the moment between sending and the next refresh. + final attachedImages = [ + for (var i = 0; i < m.files.length; i++) + if (m.files[i].isImage) i, + ]; + final localImages = attachedImages.isEmpty ? chat.imagePaths[id] ?? [] : const []; + final otherFiles = m.files.where((f) => !f.isImage).toList(); return Align( alignment: Alignment.centerRight, child: Container( @@ -393,20 +420,43 @@ class _ChatScreenState extends State { children: [ if (m.text.isNotEmpty) Text(m.text, style: TextStyle(color: theme.colorScheme.onPrimary)), - for (final p in images) + for (final i in attachedImages) Padding( - padding: const EdgeInsets.only(top: 4), - child: ClipRRect( - borderRadius: BorderRadius.circular(10), - child: Image.file(File(p), width: 200, height: 150, fit: BoxFit.cover), + padding: const EdgeInsets.only(top: 6), + child: GestureDetector( + onTap: () => _previewAttachment(m.files[i]), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: _attachmentImage(id, i, m.files[i]), + ), ), ), - if (m.files.isNotEmpty) + for (final p in localImages) Padding( padding: const EdgeInsets.only(top: 4), - child: Text( - m.files.map((f) => '📎 ${f.name}').join('\n'), - style: TextStyle(color: theme.colorScheme.onPrimary, fontSize: 13), + child: GestureDetector( + onTap: () => _openPreview(_ImageRef(p, p.split('/').last)), + child: ClipRRect( + borderRadius: BorderRadius.circular(10), + child: Image.file(File(p), + width: 200, height: 150, fit: BoxFit.cover), + ), + ), + ), + for (final f in otherFiles) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: theme.colorScheme.onPrimary.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(8), + ), + child: Text('📎 ${f.name.isEmpty ? '附件' : f.name}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + color: theme.colorScheme.onPrimary, fontSize: 12.5)), ), ), ], @@ -415,6 +465,28 @@ class _ChatScreenState extends State { ); } + Widget _attachmentImage(String messageId, int index, FileAttachment f) { + final key = '$messageId/$index'; + Uint8List? bytes = _userImages[key]; + if (bytes == null) { + try { + bytes = base64Decode(f.data); + _userImages[key] = bytes; + } catch (_) { + return const SizedBox( + width: 200, height: 60, child: Center(child: Text('图片无法显示'))); + } + } + return Image.memory(bytes, width: 200, height: 150, fit: BoxFit.cover); + } + + void _previewAttachment(FileAttachment f) { + _showImageDialog( + f.name.isEmpty ? '图片' : f.name, + source: 'data:${f.mime};base64,${f.data}', + ); + } + Widget _userActions(String id) { final m = chat.byId[id]!; final stamp = m.created > 0 @@ -1747,6 +1819,14 @@ class _ChatScreenState extends State { // ---------------------------------------------------------- permissions + /// The agent's blocking questions sit just above the composer, like the + /// permissions dock: answering one lets the turn continue. + Widget _forms() { + if (chat.forms.isEmpty) return const SizedBox.shrink(); + final form = chat.forms.first; + return _FormDock(key: ValueKey(form.id), chat: chat, form: form); + } + Widget _permissions() { final perms = widget.app.perms .where((p) => p.sessionId.isEmpty || p.sessionId == chat.id) @@ -1922,12 +2002,15 @@ class _ChatScreenState extends State { // ------------------------------------------------------------ previews - Future _openPreview(_ImageRef ref) async { + Future _openPreview(_ImageRef ref) => + _showImageDialog(ref.label, source: ref.source); + + Future _showImageDialog(String title, {required String source}) async { await showDialog( context: context, builder: (_) => _ImagePreviewDialog( - title: ref.label, - source: ref.source, + title: title, + source: source, directory: chat.dir, client: widget.app.client!, ), @@ -2300,3 +2383,385 @@ class _ImagePreviewDialogState extends State<_ImagePreviewDialog> { ); } } + +/// The native form/question card: every visible field at once, one answer. +/// Field visibility follows the form's `when` clauses, and required fields +/// must be filled before it can be sent. +class _FormDock extends StatefulWidget { + final ChatState chat; + final FormInfo form; + const _FormDock({super.key, required this.chat, required this.form}); + + @override + State<_FormDock> createState() => _FormDockState(); +} + +class _FormDockState extends State<_FormDock> { + final Map _values = {}; + final Map _controllers = {}; + String? _error; + bool _sending = false; + + @override + void initState() { + super.initState(); + for (final f in widget.form.fields) { + switch (f.type) { + case 'boolean': + _values[f.key] = f.defaultValue is bool ? f.defaultValue : false; + break; + case 'multiselect': + _values[f.key] = f.defaultValue is List + ? List.from((f.defaultValue as List).whereType()) + : []; + break; + case 'external': + _values[f.key] = true; + break; + default: + if (f.defaultValue != null) { + _values[f.key] = f.defaultValue; + _controllers[f.key] = + TextEditingController(text: '${f.defaultValue}'); + } + } + } + } + + @override + void dispose() { + for (final c in _controllers.values) { + c.dispose(); + } + super.dispose(); + } + + bool _visible(AgentFormField f) { + if (f.hidden) return false; + for (final w in f.when) { + final v = _values[w.key]; + final eq = v == w.value || + (v is num && w.value is num && v == w.value) || + (v is bool && w.value is bool && v == w.value); + if (w.op == 'neq' ? eq : !eq) return false; + } + return true; + } + + TextEditingController _controller(AgentFormField f) => + _controllers.putIfAbsent(f.key, () => TextEditingController()); + + void _set(AgentFormField f, Object? value) { + setState(() { + _values[f.key] = value; + _error = null; + }); + } + + Future _submit() async { + final visible = widget.form.fields.where(_visible).toList(); + final missing = []; + for (final f in visible) { + if (!f.required || f.type == 'external') continue; + final v = _values[f.key]; + // A required switch or acknowledgement has to be on, not merely set. + final empty = v == null || + v == false || + (v is String && v.trim().isEmpty) || + (v is List && v.isEmpty); + if (empty) missing.add(f.label); + } + if (missing.isNotEmpty) { + setState(() => _error = '请填写:${missing.join('、')}'); + return; + } + final answer = {}; + for (final f in visible) { + if (f.type == 'external') { + answer[f.key] = true; + continue; + } + final v = _values[f.key]; + if (v == null) continue; + if (v is String && v.trim().isEmpty) continue; + if (v is List && v.isEmpty) continue; + answer[f.key] = v; + } + setState(() { + _sending = true; + _error = null; + }); + await widget.chat.replyForm(widget.form, answer); + if (mounted) setState(() => _sending = false); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final fields = widget.form.fields.where(_visible).toList(); + return Card( + margin: const EdgeInsets.fromLTRB(12, 4, 12, 4), + color: scheme.surfaceContainerHigh, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Icon(Icons.help_outline, size: 18, color: scheme.primary), + const SizedBox(width: 8), + Expanded( + child: Text( + widget.form.title.isEmpty ? '请选择' : widget.form.title, + style: const TextStyle( + fontSize: 14, fontWeight: FontWeight.w600), + ), + ), + TextButton( + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, 32), + ), + onPressed: _sending + ? null + : () => widget.chat.cancelForm(widget.form), + child: const Text('取消', style: TextStyle(fontSize: 12.5)), + ), + ], + ), + if (fields.isNotEmpty) + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 360), + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final f in fields) _field(f, theme), + ], + ), + ), + ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(_error!, + style: TextStyle(fontSize: 12, color: scheme.error)), + ), + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + FilledButton( + onPressed: _sending ? null : _submit, + child: _sending + ? const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('发送'), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _field(AgentFormField f, ThemeData theme) { + final scheme = theme.colorScheme; + final title = Row( + children: [ + Flexible( + child: Text(f.label, + style: + const TextStyle(fontSize: 13, fontWeight: FontWeight.w600)), + ), + if (f.required) + Text(' *', style: TextStyle(color: scheme.error, fontSize: 13)), + ], + ); + Widget hint() => f.description == null || f.description!.isEmpty + ? const SizedBox.shrink() + : Padding( + padding: const EdgeInsets.only(top: 2, bottom: 2), + child: Text(f.description!, + style: TextStyle(fontSize: 12, color: theme.hintColor)), + ); + switch (f.type) { + case 'external': + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + hint(), + if (f.url != null && f.url!.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Text(f.url!, + style: TextStyle( + fontSize: 12, color: scheme.primary), + maxLines: 2, + overflow: TextOverflow.ellipsis), + ), + ], + ), + ); + case 'boolean': + return SwitchListTile( + contentPadding: EdgeInsets.zero, + dense: true, + title: title, + subtitle: hint(), + value: _values[f.key] == true, + onChanged: (v) => _set(f, v), + ); + case 'multiselect': + final selected = List.from( + (_values[f.key] as List?)?.whereType() ?? const []); + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + hint(), + Wrap( + spacing: 6, + runSpacing: -6, + children: [ + for (final o in f.options) + FilterChip( + label: Text(o.label, style: const TextStyle(fontSize: 12.5)), + selected: selected.contains(o.value), + onSelected: (on) { + final next = [...selected]; + if (on) { + next.add(o.value); + } else { + next.remove(o.value); + } + _set(f, next); + }, + ), + ], + ), + ], + ), + ); + case 'string': + if (f.options.isNotEmpty) { + final current = _values[f.key]?.toString(); + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + hint(), + Wrap( + spacing: 6, + runSpacing: -6, + children: [ + for (final o in f.options) + ChoiceChip( + label: Text(o.label, + style: const TextStyle(fontSize: 12.5)), + selected: current == o.value, + onSelected: (_) => _set(f, o.value), + ), + ], + ), + if (f.custom) + Padding( + padding: const EdgeInsets.only(top: 6), + child: TextField( + controller: _controller(f), + onChanged: (v) => _set(f, v), + style: const TextStyle(fontSize: 13), + decoration: InputDecoration( + isDense: true, + hintText: '其他…', + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8)), + ), + ), + ), + ], + ), + ); + } + final numeric = f.format == 'number'; + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + hint(), + const SizedBox(height: 4), + TextField( + controller: _controller(f), + onChanged: (v) => _set(f, v), + keyboardType: f.format == 'email' + ? TextInputType.emailAddress + : f.format == 'uri' + ? TextInputType.url + : numeric + ? TextInputType.number + : TextInputType.text, + style: const TextStyle(fontSize: 13), + decoration: InputDecoration( + isDense: true, + hintText: f.placeholder ?? + (f.format == 'date' ? 'YYYY-MM-DD' : null), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + case 'number': + case 'integer': + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + title, + hint(), + const SizedBox(height: 4), + TextField( + controller: _controller(f), + keyboardType: + TextInputType.numberWithOptions(decimal: f.type == 'number'), + onChanged: (v) { + final n = f.type == 'integer' + ? int.tryParse(v) + : num.tryParse(v); + _set(f, n ?? (v.isEmpty ? null : v)); + }, + style: const TextStyle(fontSize: 13), + decoration: InputDecoration( + isDense: true, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8)), + ), + ), + ], + ), + ); + default: + return Padding( + padding: const EdgeInsets.only(top: 8), + child: Text('${f.label}(${f.type})', + style: const TextStyle(fontSize: 13)), + ); + } + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart new file mode 100644 index 0000000..98a5766 --- /dev/null +++ b/lib/screens/home_screen.dart @@ -0,0 +1,126 @@ +// The connected shell. A phone treats the session list as the left drawer and +// the chat as the screen; a wide layout shows both side by side, which is +// where a tablet or a desktop window lands. +import 'package:flutter/material.dart'; + +import '../state.dart'; +import 'chat_screen.dart'; +import 'sessions_screen.dart'; + +class HomeScreen extends StatefulWidget { + final AppState app; + const HomeScreen({super.key, required this.app}); + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + final GlobalKey _scaffold = GlobalKey(); + bool _opening = false; + + static const _wideBreakpoint = 840.0; + + @override + void initState() { + super.initState(); + widget.app.addListener(_maybeOpenFirst); + WidgetsBinding.instance.addPostFrameCallback((_) => _maybeOpenFirst()); + } + + @override + void dispose() { + widget.app.removeListener(_maybeOpenFirst); + super.dispose(); + } + + /// Like the first-party client, a phone lands in a conversation rather than + /// on an empty pane: open the newest one when nothing is open yet. + void _maybeOpenFirst() { + final app = widget.app; + if (!mounted || _opening) return; + if (app.chat != null || app.sessions.isEmpty) return; + _opening = true; + app.openChat(app.sessions.first).whenComplete(() => _opening = false); + } + + void _closeDrawer() { + _scaffold.currentState?.closeDrawer(); + } + + @override + Widget build(BuildContext context) { + return ListenableBuilder( + listenable: widget.app, + builder: (context, _) { + return LayoutBuilder( + builder: (context, constraints) { + final wide = constraints.maxWidth >= _wideBreakpoint; + final chat = widget.app.chat; + final chatView = chat == null + ? _empty(wide) + : ChatScreen( + key: ValueKey(chat.session.id), + app: widget.app, + session: chat.session, + onOpenSessions: wide ? null : () => + _scaffold.currentState?.openDrawer(), + ); + if (wide) { + return Scaffold( + body: Row( + children: [ + SizedBox( + width: 320, + child: SessionListPane(app: widget.app), + ), + const VerticalDivider(width: 1), + Expanded(child: chatView), + ], + ), + ); + } + return Scaffold( + key: _scaffold, + drawer: Drawer( + width: constraints.maxWidth * 0.86 > 380 + ? 380 + : constraints.maxWidth * 0.86, + child: SessionListPane( + app: widget.app, + onOpened: _closeDrawer, + ), + ), + body: chatView, + ); + }, + ); + }, + ); + } + + Widget _empty(bool wide) { + final scheme = Theme.of(context).colorScheme; + return Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.forum_outlined, size: 40, color: scheme.onSurfaceVariant), + const SizedBox(height: 12), + Text('选择一个会话', + style: TextStyle(fontSize: 16, color: scheme.onSurfaceVariant)), + if (!wide) ...[ + const SizedBox(height: 12), + FilledButton( + onPressed: () => _scaffold.currentState?.openDrawer(), + child: const Text('打开会话列表'), + ), + ], + ], + ), + ), + ); + } +} diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index 94bf037..f3a3583 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -5,18 +5,23 @@ import 'package:flutter/material.dart'; import '../api/models.dart'; import '../state.dart'; import 'servers_screen.dart'; -import 'chat_screen.dart'; -/// The connected screen: the live session list. -class SessionsScreen extends StatefulWidget { +/// The session list: a drawer on a phone, a persistent column on a wide +/// layout. Selecting a session opens it in the chat beside it (the shell owns +/// that), so this only reports the choice through [onOpened]. +class SessionListPane extends StatefulWidget { final AppState app; - const SessionsScreen({super.key, required this.app}); + + /// Called after a session was opened, so the drawer can close itself. + final VoidCallback? onOpened; + + const SessionListPane({super.key, required this.app, this.onOpened}); @override - State createState() => _SessionsScreenState(); + State createState() => _SessionListPaneState(); } -class _SessionsScreenState extends State { +class _SessionListPaneState extends State { bool _searchOpen = false; Timer? _timer; late final TextEditingController _searchCtrl; @@ -51,40 +56,48 @@ class _SessionsScreenState extends State { return ListenableBuilder( listenable: app, builder: (context, _) { - return Scaffold( - appBar: AppBar( - title: const Text('会话'), - leading: IconButton( - icon: const Icon(Icons.dns_outlined), - tooltip: '服务器', - onPressed: _instancesSheet, - ), - actions: [ - IconButton( - icon: Icon(_searchOpen ? Icons.close : Icons.search), - tooltip: '搜索', - onPressed: () { - setState(() { - _searchOpen = !_searchOpen; - if (!_searchOpen) { - _searchCtrl.clear(); - app.refreshSessions(); - } - }); - }, - ), - IconButton( - icon: const Icon(Icons.add), - tooltip: '新建会话', - onPressed: _newSessionSheet, - ), - ], - ), - body: Column( + final scheme = Theme.of(context).colorScheme; + return SafeArea( + child: Column( children: [ + Padding( + padding: const EdgeInsets.fromLTRB(4, 6, 4, 0), + child: Row( + children: [ + IconButton( + icon: const Icon(Icons.dns_outlined), + tooltip: '服务器', + onPressed: _instancesSheet, + ), + const Expanded( + child: Text('会话', + style: TextStyle( + fontSize: 20, fontWeight: FontWeight.w600)), + ), + IconButton( + icon: Icon(_searchOpen ? Icons.close : Icons.search), + tooltip: '搜索', + onPressed: () { + setState(() { + _searchOpen = !_searchOpen; + if (!_searchOpen) { + _searchCtrl.clear(); + app.refreshSessions(); + } + }); + }, + ), + IconButton( + icon: const Icon(Icons.add), + tooltip: '新建会话', + onPressed: _newSessionSheet, + ), + ], + ), + ), if (_searchOpen) Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 4), + padding: const EdgeInsets.fromLTRB(12, 2, 12, 4), child: TextField( controller: _searchCtrl, autofocus: true, @@ -99,14 +112,17 @@ class _SessionsScreenState extends State { ), if (app.error != null) Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), + padding: const EdgeInsets.symmetric(horizontal: 12), child: Row( children: [ Expanded( child: Text(app.error!, - style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 13)), + style: TextStyle( + color: scheme.error, fontSize: 13)), ), - TextButton(onPressed: app.refreshSessions, child: const Text('重试')), + TextButton( + onPressed: app.refreshSessions, + child: const Text('重试')), ], ), ), @@ -130,7 +146,8 @@ class _SessionsScreenState extends State { children: [ const Text('暂无会话'), const SizedBox(height: 8), - FilledButton(onPressed: _newSessionSheet, child: const Text('新建会话')), + FilledButton( + onPressed: _newSessionSheet, child: const Text('新建会话')), ], ), ); @@ -142,7 +159,9 @@ class _SessionsScreenState extends State { itemBuilder: (context, i) { final s = app.sessions[i]; final running = app.active.contains(s.id); + final selected = widget.app.chat?.session.id == s.id; return ListTile( + selected: selected, title: Text(s.title.isEmpty ? '(无标题会话)' : s.title, maxLines: 1, overflow: TextOverflow.ellipsis), subtitle: Text(_subtitle(s), @@ -153,7 +172,9 @@ class _SessionsScreenState extends State { if (running) Padding( padding: const EdgeInsets.only(right: 8), - child: Icon(Icons.circle, size: 10, color: Theme.of(context).colorScheme.primary), + child: Icon(Icons.circle, + size: 10, + color: Theme.of(context).colorScheme.primary), ), PopupMenuButton( onSelected: (v) => _sessionAction(s, v), @@ -167,10 +188,7 @@ class _SessionsScreenState extends State { ), onTap: () { app.openChat(s); - Navigator.push( - context, - MaterialPageRoute(builder: (_) => ChatScreen(app: app, session: s)), - ); + widget.onOpened?.call(); }, ); }, @@ -212,7 +230,9 @@ class _SessionsScreenState extends State { title: const Text('重命名'), content: TextField(controller: ctrl, autofocus: true), actions: [ - TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消')), FilledButton( onPressed: () { Navigator.pop(context); @@ -232,7 +252,9 @@ class _SessionsScreenState extends State { title: const Text('删除会话?'), content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'), actions: [ - TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('取消')), FilledButton( onPressed: () { Navigator.pop(context); @@ -257,12 +279,14 @@ class _SessionsScreenState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - const Text('新建会话', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + const Text('新建会话', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const SizedBox(height: 12), TextField( controller: ctrl, autofocus: true, - decoration: const InputDecoration(hintText: '标题(可选)', border: OutlineInputBorder()), + decoration: const InputDecoration( + hintText: '标题(可选)', border: OutlineInputBorder()), ), const SizedBox(height: 12), FilledButton( @@ -274,12 +298,7 @@ class _SessionsScreenState extends State { widget.app.sessions.insert(0, s); widget.app.touch(); widget.app.openChat(s); - if (mounted) { - Navigator.push( - context, - MaterialPageRoute(builder: (_) => ChatScreen(app: widget.app, session: s)), - ); - } + widget.onOpened?.call(); } }, child: const Text('创建'), @@ -300,14 +319,18 @@ class _SessionsScreenState extends State { children: [ const Padding( padding: EdgeInsets.all(12), - child: Text('服务器', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + child: Text('服务器', + style: + TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), ), for (final c in app.connections) ...[ ListTile( title: Text(c.label), subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), trailing: app.conn?.id == c.id - ? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary)) + ? Text('已连接', + style: TextStyle( + color: Theme.of(context).colorScheme.primary)) : null, onTap: () { Navigator.pop(context); @@ -321,8 +344,7 @@ class _SessionsScreenState extends State { onTap: () { Navigator.pop(context); Navigator.of(context).push(MaterialPageRoute( - builder: (_) => - ServersScreen(app: app, startEditing: true), + builder: (_) => ServersScreen(app: app, startEditing: true), )); }, ), diff --git a/lib/state.dart b/lib/state.dart index 22f67c4..739ac94 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -41,6 +41,9 @@ const _eventTypes = [ 'session.compaction.delta', 'session.compaction.ended', 'session.compaction.failed', + 'form.created', + 'form.replied', + 'form.cancelled', 'permission.asked', 'permission.replied', ]; @@ -328,7 +331,11 @@ class AppState extends ChangeNotifier { final type = ev['type'] as String? ?? ''; final data = ev['data'] as Map? ?? {}; if (chat != null) { - final sid = data['sessionID'] as String?; + final form = data['form']; + final sid = data['sessionID'] as String? ?? + (form is Map + ? form['sessionID'] as String? + : null); if (sid != null && sid == chat!.session.id) { chat!.handleEvent(type, data, ev['created'] as int? ?? 0); } @@ -468,6 +475,8 @@ class AppState extends ChangeNotifier { Future openChat(Session s) async { chat = ChatState(this, s); + // The shell shows the new session at once; its messages follow. + notifyListeners(); await chat!.load(); notifyListeners(); } @@ -529,6 +538,9 @@ class ChatState extends ChangeNotifier { ModelRef? selectedModel; String selectedAgent; + /// The agent's pending questions (native forms), oldest first. + List forms = []; + /// `/` palette contents, loaded once per open chat. List slashItems = []; bool slashLoading = false; @@ -559,6 +571,7 @@ class ChatState extends ChangeNotifier { error = null; notifyListeners(); await reloadTail(); + await reloadForms(); } catch (e) { loading = false; error = e.toString(); @@ -664,6 +677,44 @@ class ChatState extends ChangeNotifier { ); } + /// Fetches the pending forms, which may have been asked while the stream + /// was down (the events alone would miss them). + Future reloadForms() async { + final cl = app.client; + if (cl == null) return; + try { + forms = await cl.forms(id, directory: dir); + notifyListeners(); + } catch (_) {} + } + + Future replyForm(FormInfo form, Map answer) async { + final cl = app.client; + if (cl == null) return; + try { + await cl.replyForm(id, form.id, answer, directory: dir); + forms.removeWhere((f) => f.id == form.id); + error = null; + notifyListeners(); + } catch (e) { + error = e.toString(); + notifyListeners(); + } + } + + Future cancelForm(FormInfo form) async { + final cl = app.client; + if (cl == null) return; + try { + await cl.cancelForm(id, form.id, directory: dir); + forms.removeWhere((f) => f.id == form.id); + notifyListeners(); + } catch (e) { + error = e.toString(); + notifyListeners(); + } + } + /// Refreshes the newest page without dropping the older pages that were /// already loaded; the server's copy wins for messages it returns. Future reloadTail() async { @@ -1003,6 +1054,23 @@ class ChatState extends ChangeNotifier { case 'session.tool.progress': if (mid != null) _applyTool(mid, type, data); break; + case 'form.created': + final raw = data['form']; + if (raw is Map) { + final form = FormInfo.fromJson(raw); + forms.removeWhere((f) => f.id == form.id); + forms.add(form); + notifyListeners(); + } + break; + case 'form.replied': + case 'form.cancelled': + final id = data['id'] as String?; + if (id != null) { + forms.removeWhere((f) => f.id == id); + notifyListeners(); + } + break; case 'session.compaction.started': final cid = data['inputID'] as String?; if (cid != null && byId[cid] == null) { diff --git a/pubspec.yaml b/pubspec.yaml index 4c27901..4f26486 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.3.9+309 +version: 0.3.10+310 environment: sdk: ^3.14.0