feat: a transport seam, image previews, native forms, a phone drawer

- lib/api/transport.dart: TransportRequest/TransportResponse/Transport, with
  DirectTransport holding the old behaviour (HTTP CONNECT, SOCKS5/socks5h,
  self-signed and pinned certificates). Client goes through it, so a relay
  tunnel only adds an implementation.
- User rows decode the server's inline attachment data and open the shared
  image preview on tap; the local path stays the fallback.
- The agent's native forms: models from @opencode/client, the form list,
  replies and cancels, form.* events, and a dock above the composer with
  when-rules and required-field validation (a switch must be on).
- HomeScreen: the session list is the phone's left drawer and a persistent
  column from 840 px, the chat beside it; the newest session opens on start.
- 0.3.10 (310).
This commit is contained in:
blumia committed 2026-11-21 01:16:10 +08:00
1 parent 9b53338908
commit 60d02083d3
11 files changed
+1247 -295

No files matched your search

+12
View File
@@ -5,6 +5,18 @@
--- ---
## 0.3.10 Transport 层、历史图片、原生表单与左右分栏(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| Transport | 新增 `lib/api/transport.dart`:`TransportRequest`(method/path/query/rawQuery/headers/body)、`TransportResponse`(状态码/头/`Stream<List<int>>`,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) ## 0.3 Flutter 尝试(2026-11-18,分支 `flutter`,0.3.0)
**背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo; **背景**:MyGo 手机端首个版本(0.10.0)在实机上 UI 可用性不如 Asuka 0.1,决定观察、暂停 MyGo;
+8 -6
View File
@@ -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 feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. 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 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 events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
context usage ring with a detail sheet, model/agent switching (Build/Plan only, context usage ring with a detail sheet, model/agent switching (Build/Plan only,
current one checked), copy / fork / revert, attachments (photos/files), current one checked), copy / fork / revert, attachments (photos/files, kept
permissions. Android 7.0 (API 24)+, plus a Linux desktop target used for local after a reload), the agent's native forms, permissions. A phone opens the
testing. 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 ## What is here
| Path | What | | 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/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/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 | | `lib/widgets/` | The context usage ring |
Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer Markdown rendering reuses **`gpt_markdown`** (BSD-3), the Flutter AI-output renderer
+91 -233
View File
@@ -4,11 +4,8 @@ library;
import 'dart:async'; import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:io';
import 'package:socks5_proxy/socks_client.dart';
import 'models.dart'; import 'models.dart';
import 'transport.dart';
class ApiError implements Exception { class ApiError implements Exception {
final int status; final int status;
@@ -18,111 +15,23 @@ class ApiError implements Exception {
String toString() => message.isEmpty ? 'HTTP $status' : message; 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 { class Client {
final Uri base; final Uri base;
final String? proxy; // http://host:port or socks5://host:port
final bool insecure; /// Every request and the event stream go through here; today a direct
final String? fingerprint; /// connection, later one that can also be a relay tunnel.
final Transport transport;
String? token; String? token;
late HttpClient _http;
_ProxyConfig? _proxyConfig;
InternetAddress? _proxyAddress;
Client( Client(
this.base, { this.base, {
this.proxy, String? proxy,
this.insecure = false, bool insecure = false,
this.fingerprint, String? fingerprint,
}) { Transport? transport,
_http = HttpClient(); }) : transport = transport ??
_http.connectionTimeout = const Duration(seconds: 20); DirectTransport(base,
_proxyConfig = _parseProxy(proxy); proxy: proxy, insecure: insecure, fingerprint: fingerprint);
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<InternetAddress> _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 get baseUrl => base.toString(); String get baseUrl => base.toString();
@@ -290,6 +199,39 @@ class Client {
return data is Map ? data['id'] as String? : null; return data is Map ? data['id'] as String? : null;
} }
// -------------------------------------------------------------- forms
/// The agent's pending questions in this session.
Future<List<FormInfo>> 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<String, dynamic>) FormInfo.fromJson(f),
];
}
Future<void> replyForm(String sessionId, String formId,
Map<String, Object?> answer, {String? directory}) async {
await _json(
'POST',
'/api/session/${Uri.encodeComponent(sessionId)}/form/${Uri.encodeComponent(formId)}/reply',
body: {'answer': answer},
directory: directory);
}
Future<void> 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`). /// The commands this directory registers (`/api/command`).
Future<List<Map<String, String>>> commands({String? directory}) async { Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory); final r = await _json('GET', '/api/command', directory: directory);
@@ -357,10 +299,11 @@ class Client {
}, },
directory: directory, directory: directory,
rawDirectory: true); rawDirectory: true);
final bytes = await res.collect();
if (res.statusCode < 200 || res.statusCode >= 300) { 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 // ------------------------------------------------------------ files
@@ -383,7 +326,7 @@ class Client {
Future<String> fsRead(String path, {String? directory}) async { Future<String> fsRead(String path, {String? directory}) async {
final res = await _request('GET', '/api/fs/read', final res = await _request('GET', '/api/fs/read',
query: {'path': path}, directory: directory, rawDirectory: true); 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) { if (res.statusCode < 200 || res.statusCode >= 300) {
throw ApiError(res.statusCode, text.trim()); throw ApiError(res.statusCode, text.trim());
} }
@@ -419,27 +362,29 @@ class Client {
/// when the connection drops; the caller restarts it with backoff. /// when the connection drops; the caller restarts it with backoff.
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* { Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
// `types` repeats: a Map would keep only the last one. // `types` repeats: a Map would keep only the last one.
var uri = base.resolve('/api/event'); final query = types == null || types.isEmpty
if (types != null && types.isNotEmpty) { ? null
final q = types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&'); : types.map((t) => 'types=${Uri.encodeQueryComponent(t)}').join('&');
uri = Uri.parse('$uri?$q'); final res = await transport.send(TransportRequest(
} method: 'GET',
final req = await _http.openUrl('GET', uri); path: '/api/event',
req.headers.set('Accept', 'text/event-stream'); rawQuery: query,
req.headers.set('Cache-Control', 'no-cache'); headers: {
if (token != null && token!.isNotEmpty) { 'accept': 'text/event-stream',
req.headers.set('Authorization', 'Bearer $token'); 'cache-control': 'no-cache',
} 'user-agent': 'openchamber-native/0.3',
final res = await req.close(); if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
if (res.statusCode != 200) { },
throw ApiError(res.statusCode, 'event stream failed'); ));
if (res.status != 200) {
throw ApiError(res.status, 'event stream failed');
} }
String data = ''; String data = '';
// The server sends a `: heartbeat` comment every few seconds; if nothing // 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 // at all arrives for a while the connection is dead and the caller should
// reconnect rather than wait on a half-open socket. // reconnect rather than wait on a half-open socket.
final lines = utf8.decoder final lines = utf8.decoder
.bind(res) .bind(res.body)
.transform(const LineSplitter()) .transform(const LineSplitter())
.timeout(const Duration(seconds: 30)); .timeout(const Duration(seconds: 30));
await for (final line in lines) { await for (final line in lines) {
@@ -471,7 +416,7 @@ class Client {
directory: directory, directory: directory,
partShells: partShells, partShells: partShells,
rawDirectory: rawDirectory); 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) { if (res.statusCode < 200 || res.statusCode >= 300) {
String msg = text; String msg = text;
try { try {
@@ -494,127 +439,40 @@ class Client {
String? directory, String? directory,
bool partShells = false, bool partShells = false,
bool rawDirectory = false}) async { bool rawDirectory = false}) async {
final q = Uri(queryParameters: query ?? {}); final headers = <String, String>{
final uri = base.resolve(path).replace(queryParameters: q.queryParameters.isEmpty ? null : q.queryParameters); 'accept': path == '/api/event' ? 'text/event-stream' : 'application/json',
final req = await _http.openUrl(method, uri); 'user-agent': 'openchamber-native/0.3',
// Every header must be set before the body, which finalizes them. if (token != null && token!.isNotEmpty) 'authorization': 'Bearer $token',
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');
}
if (directory != null && directory.isNotEmpty) { if (directory != null && directory.isNotEmpty) {
// The file routes compare this header with the workspace path, so they // 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. // need it as written; the rest of the API wants it URI-encoded.
req.headers.set('x-opencode-directory', headers['x-opencode-directory'] =
rawDirectory ? directory : Uri.encodeComponent(directory)); rawDirectory ? directory : Uri.encodeComponent(directory);
if (!rawDirectory) { if (!rawDirectory) headers['x-opencode-directory-encoding'] = 'uri';
req.headers.set('x-opencode-directory-encoding', 'uri');
} }
} if (partShells) headers['x-openchamber-part-shells'] = 'v1';
if (partShells) { if (path == '/api/event') headers['cache-control'] = 'no-cache';
req.headers.set('x-openchamber-part-shells', 'v1'); final bodyBytes = body == null ? null : utf8.encode(jsonEncode(body));
} if (bodyBytes != null) headers['content-type'] = 'application/json';
if (path == '/api/event') { final res = await transport.send(TransportRequest(
req.headers.set('Cache-Control', 'no-cache'); method: method,
} path: path,
if (body != null) { query: query ?? const {},
req.headers.contentType = ContentType.json; headers: headers,
req.write(jsonEncode(body)); body: bodyBytes,
} ));
final res = await req.close(); return _Response(res.status, res.body);
final bodyBytes = await res.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
return _Response(res.statusCode, bodyBytes);
} }
void close() => _http.close(); void close() => transport.close();
} }
class _Response { class _Response {
final int statusCode; final int statusCode;
final List<int> body; final Stream<List<int>> body;
_Response(this.statusCode, this.body); _Response(this.statusCode, this.body);
}
String _sha256(List<int> bytes) { Future<List<int>> collect() =>
return _Digest.sha256Hex(bytes); body.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
}
// Minimal SHA-256, so the client has no native dependencies for pinning.
class _Digest {
static String sha256Hex(List<int> bytes) {
final h = List<int>.from(const [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
final k = <int>[
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<int>.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<int>.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<int>.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<int>.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);
} }
+147 -3
View File
@@ -291,9 +291,153 @@ class Message {
class FileAttachment { class FileAttachment {
final String name; final String name;
final String mime; final String mime;
FileAttachment(this.name, this.mime);
factory FileAttachment.fromJson(Map<String, dynamic> j) => /// Base64 of the file the user attached, as the server stores it.
FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? ''); 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<FormOption> options;
final List<FormWhen> 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<String, dynamic> 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<String, dynamic>) FormOption.fromJson(o),
],
when: [
for (final w in (j['when'] as List? ?? []))
if (w is Map<String, dynamic>) 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<AgentFormField> fields;
const FormInfo({
required this.id,
required this.sessionID,
required this.title,
required this.fields,
});
factory FormInfo.fromJson(Map<String, dynamic> 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<String, dynamic>) AgentFormField.fromJson(f),
],
);
} }
class Page<T> { class Page<T> {
+255
View File
@@ -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<String, String> query;
final Map<String, String> headers;
final List<int>? 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<String, String> headers;
final Stream<List<int>> 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<TransportResponse> 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<InternetAddress> _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<TransportResponse> 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 = <String, String>{};
res.headers.forEach((name, values) {
headers[name.toLowerCase()] = values.join(', ');
});
return TransportResponse(res.statusCode, headers, res);
}
@override
void close() => _http.close();
}
String sha256Hex(List<int> bytes) => _Digest.sha256Hex(bytes);
// Minimal SHA-256, so the client has no native dependencies for pinning.
class _Digest {
static String sha256Hex(List<int> bytes) {
final h = List<int>.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<int>.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<int>.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<int>.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<int>.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);
}
+2 -2
View File
@@ -1,7 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'screens/home_screen.dart';
import 'screens/servers_screen.dart'; import 'screens/servers_screen.dart';
import 'screens/sessions_screen.dart';
import 'state.dart'; import 'state.dart';
void main() { void main() {
@@ -45,7 +45,7 @@ class _OpenChamberAppState extends State<OpenChamberApp>
builder: (context, _) { builder: (context, _) {
final home = app.client == null final home = app.client == null
? ServersScreen(app: app) ? ServersScreen(app: app)
: SessionsScreen(app: app); : HomeScreen(app: app);
return MaterialApp( return MaterialApp(
title: 'OpenChamber', title: 'OpenChamber',
theme: ThemeData( theme: ThemeData(
+477 -12
View File
@@ -18,7 +18,16 @@ import 'files_panel.dart';
class ChatScreen extends StatefulWidget { class ChatScreen extends StatefulWidget {
final AppState app; final AppState app;
final Session session; 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 @override
State<ChatScreen> createState() => _ChatScreenState(); State<ChatScreen> createState() => _ChatScreenState();
@@ -36,6 +45,9 @@ class _ChatScreenState extends State<ChatScreen> {
List<_Attach> _attachments = []; List<_Attach> _attachments = [];
bool _attaching = false; bool _attaching = false;
/// Decoded user attachments, so a rebuild does not base64-decode again.
final Map<String, Uint8List> _userImages = {};
/// `/` palette: the highlighted row, and the draft Esc closed it at. /// `/` palette: the highlighted row, and the draft Esc closed it at.
int _slashIndex = 0; int _slashIndex = 0;
String? _slashDismissed; String? _slashDismissed;
@@ -90,6 +102,13 @@ class _ChatScreenState extends State<ChatScreen> {
final theme = Theme.of(context); final theme = Theme.of(context);
return Scaffold( return Scaffold(
appBar: AppBar( 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, title: Text(widget.session.title.isEmpty ? '会话' : widget.session.title,
maxLines: 1, overflow: TextOverflow.ellipsis), maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [ actions: [
@@ -131,6 +150,7 @@ class _ChatScreenState extends State<ChatScreen> {
), ),
Expanded(child: _messageList()), Expanded(child: _messageList()),
_permissions(), _permissions(),
_forms(),
_composer(), _composer(),
], ],
), ),
@@ -376,8 +396,15 @@ class _ChatScreenState extends State<ChatScreen> {
Widget _userRow(String id) { Widget _userRow(String id) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
final images = chat.imagePaths[id] ?? [];
final theme = Theme.of(context); 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 <String>[];
final otherFiles = m.files.where((f) => !f.isImage).toList();
return Align( return Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: Container( child: Container(
@@ -393,20 +420,43 @@ class _ChatScreenState extends State<ChatScreen> {
children: [ children: [
if (m.text.isNotEmpty) if (m.text.isNotEmpty)
Text(m.text, style: TextStyle(color: theme.colorScheme.onPrimary)), Text(m.text, style: TextStyle(color: theme.colorScheme.onPrimary)),
for (final p in images) for (final i in attachedImages)
Padding( Padding(
padding: const EdgeInsets.only(top: 4), padding: const EdgeInsets.only(top: 6),
child: GestureDetector(
onTap: () => _previewAttachment(m.files[i]),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Image.file(File(p), width: 200, height: 150, fit: BoxFit.cover), child: _attachmentImage(id, i, m.files[i]),
), ),
), ),
if (m.files.isNotEmpty) ),
for (final p in localImages)
Padding( Padding(
padding: const EdgeInsets.only(top: 4), padding: const EdgeInsets.only(top: 4),
child: Text( child: GestureDetector(
m.files.map((f) => '📎 ${f.name}').join('\n'), onTap: () => _openPreview(_ImageRef(p, p.split('/').last)),
style: TextStyle(color: theme.colorScheme.onPrimary, fontSize: 13), 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<ChatScreen> {
); );
} }
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) { Widget _userActions(String id) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
final stamp = m.created > 0 final stamp = m.created > 0
@@ -1747,6 +1819,14 @@ class _ChatScreenState extends State<ChatScreen> {
// ---------------------------------------------------------- permissions // ---------------------------------------------------------- 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() { Widget _permissions() {
final perms = widget.app.perms final perms = widget.app.perms
.where((p) => p.sessionId.isEmpty || p.sessionId == chat.id) .where((p) => p.sessionId.isEmpty || p.sessionId == chat.id)
@@ -1922,12 +2002,15 @@ class _ChatScreenState extends State<ChatScreen> {
// ------------------------------------------------------------ previews // ------------------------------------------------------------ previews
Future<void> _openPreview(_ImageRef ref) async { Future<void> _openPreview(_ImageRef ref) =>
_showImageDialog(ref.label, source: ref.source);
Future<void> _showImageDialog(String title, {required String source}) async {
await showDialog( await showDialog(
context: context, context: context,
builder: (_) => _ImagePreviewDialog( builder: (_) => _ImagePreviewDialog(
title: ref.label, title: title,
source: ref.source, source: source,
directory: chat.dir, directory: chat.dir,
client: widget.app.client!, 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<String, Object?> _values = {};
final Map<String, TextEditingController> _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<String>.from((f.defaultValue as List).whereType<String>())
: <String>[];
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<void> _submit() async {
final visible = widget.form.fields.where(_visible).toList();
final missing = <String>[];
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 = <String, Object?>{};
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<String>.from(
(_values[f.key] as List?)?.whereType<String>() ?? 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)),
);
}
}
}
+126
View File
@@ -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<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final GlobalKey<ScaffoldState> _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('打开会话列表'),
),
],
],
),
),
);
}
}
+59 -37
View File
@@ -5,18 +5,23 @@ import 'package:flutter/material.dart';
import '../api/models.dart'; import '../api/models.dart';
import '../state.dart'; import '../state.dart';
import 'servers_screen.dart'; import 'servers_screen.dart';
import 'chat_screen.dart';
/// The connected screen: the live session list. /// The session list: a drawer on a phone, a persistent column on a wide
class SessionsScreen extends StatefulWidget { /// 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; 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 @override
State<SessionsScreen> createState() => _SessionsScreenState(); State<SessionListPane> createState() => _SessionListPaneState();
} }
class _SessionsScreenState extends State<SessionsScreen> { class _SessionListPaneState extends State<SessionListPane> {
bool _searchOpen = false; bool _searchOpen = false;
Timer? _timer; Timer? _timer;
late final TextEditingController _searchCtrl; late final TextEditingController _searchCtrl;
@@ -51,15 +56,24 @@ class _SessionsScreenState extends State<SessionsScreen> {
return ListenableBuilder( return ListenableBuilder(
listenable: app, listenable: app,
builder: (context, _) { builder: (context, _) {
return Scaffold( final scheme = Theme.of(context).colorScheme;
appBar: AppBar( return SafeArea(
title: const Text('会话'), child: Column(
leading: IconButton( children: [
Padding(
padding: const EdgeInsets.fromLTRB(4, 6, 4, 0),
child: Row(
children: [
IconButton(
icon: const Icon(Icons.dns_outlined), icon: const Icon(Icons.dns_outlined),
tooltip: '服务器', tooltip: '服务器',
onPressed: _instancesSheet, onPressed: _instancesSheet,
), ),
actions: [ const Expanded(
child: Text('会话',
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.w600)),
),
IconButton( IconButton(
icon: Icon(_searchOpen ? Icons.close : Icons.search), icon: Icon(_searchOpen ? Icons.close : Icons.search),
tooltip: '搜索', tooltip: '搜索',
@@ -80,11 +94,10 @@ class _SessionsScreenState extends State<SessionsScreen> {
), ),
], ],
), ),
body: Column( ),
children: [
if (_searchOpen) if (_searchOpen)
Padding( Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 4), padding: const EdgeInsets.fromLTRB(12, 2, 12, 4),
child: TextField( child: TextField(
controller: _searchCtrl, controller: _searchCtrl,
autofocus: true, autofocus: true,
@@ -99,14 +112,17 @@ class _SessionsScreenState extends State<SessionsScreen> {
), ),
if (app.error != null) if (app.error != null)
Padding( Padding(
padding: const EdgeInsets.symmetric(horizontal: 16), padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text(app.error!, 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<SessionsScreen> {
children: [ children: [
const Text('暂无会话'), const Text('暂无会话'),
const SizedBox(height: 8), const SizedBox(height: 8),
FilledButton(onPressed: _newSessionSheet, child: const Text('新建会话')), FilledButton(
onPressed: _newSessionSheet, child: const Text('新建会话')),
], ],
), ),
); );
@@ -142,7 +159,9 @@ class _SessionsScreenState extends State<SessionsScreen> {
itemBuilder: (context, i) { itemBuilder: (context, i) {
final s = app.sessions[i]; final s = app.sessions[i];
final running = app.active.contains(s.id); final running = app.active.contains(s.id);
final selected = widget.app.chat?.session.id == s.id;
return ListTile( return ListTile(
selected: selected,
title: Text(s.title.isEmpty ? '(无标题会话)' : s.title, title: Text(s.title.isEmpty ? '(无标题会话)' : s.title,
maxLines: 1, overflow: TextOverflow.ellipsis), maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text(_subtitle(s), subtitle: Text(_subtitle(s),
@@ -153,7 +172,9 @@ class _SessionsScreenState extends State<SessionsScreen> {
if (running) if (running)
Padding( Padding(
padding: const EdgeInsets.only(right: 8), 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<String>( PopupMenuButton<String>(
onSelected: (v) => _sessionAction(s, v), onSelected: (v) => _sessionAction(s, v),
@@ -167,10 +188,7 @@ class _SessionsScreenState extends State<SessionsScreen> {
), ),
onTap: () { onTap: () {
app.openChat(s); app.openChat(s);
Navigator.push( widget.onOpened?.call();
context,
MaterialPageRoute(builder: (_) => ChatScreen(app: app, session: s)),
);
}, },
); );
}, },
@@ -212,7 +230,9 @@ class _SessionsScreenState extends State<SessionsScreen> {
title: const Text('重命名'), title: const Text('重命名'),
content: TextField(controller: ctrl, autofocus: true), content: TextField(controller: ctrl, autofocus: true),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton( FilledButton(
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
@@ -232,7 +252,9 @@ class _SessionsScreenState extends State<SessionsScreen> {
title: const Text('删除会话?'), title: const Text('删除会话?'),
content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'), content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'),
actions: [ actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')), TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消')),
FilledButton( FilledButton(
onPressed: () { onPressed: () {
Navigator.pop(context); Navigator.pop(context);
@@ -257,12 +279,14 @@ class _SessionsScreenState extends State<SessionsScreen> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
const Text('新建会话', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const Text('新建会话',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
const SizedBox(height: 12), const SizedBox(height: 12),
TextField( TextField(
controller: ctrl, controller: ctrl,
autofocus: true, autofocus: true,
decoration: const InputDecoration(hintText: '标题(可选)', border: OutlineInputBorder()), decoration: const InputDecoration(
hintText: '标题(可选)', border: OutlineInputBorder()),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
FilledButton( FilledButton(
@@ -274,12 +298,7 @@ class _SessionsScreenState extends State<SessionsScreen> {
widget.app.sessions.insert(0, s); widget.app.sessions.insert(0, s);
widget.app.touch(); widget.app.touch();
widget.app.openChat(s); widget.app.openChat(s);
if (mounted) { widget.onOpened?.call();
Navigator.push(
context,
MaterialPageRoute(builder: (_) => ChatScreen(app: widget.app, session: s)),
);
}
} }
}, },
child: const Text('创建'), child: const Text('创建'),
@@ -300,14 +319,18 @@ class _SessionsScreenState extends State<SessionsScreen> {
children: [ children: [
const Padding( const Padding(
padding: EdgeInsets.all(12), 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) ...[ for (final c in app.connections) ...[
ListTile( ListTile(
title: Text(c.label), title: Text(c.label),
subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), subtitle: Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'),
trailing: app.conn?.id == c.id 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, : null,
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
@@ -321,8 +344,7 @@ class _SessionsScreenState extends State<SessionsScreen> {
onTap: () { onTap: () {
Navigator.pop(context); Navigator.pop(context);
Navigator.of(context).push(MaterialPageRoute( Navigator.of(context).push(MaterialPageRoute(
builder: (_) => builder: (_) => ServersScreen(app: app, startEditing: true),
ServersScreen(app: app, startEditing: true),
)); ));
}, },
), ),
+69 -1
View File
@@ -41,6 +41,9 @@ const _eventTypes = [
'session.compaction.delta', 'session.compaction.delta',
'session.compaction.ended', 'session.compaction.ended',
'session.compaction.failed', 'session.compaction.failed',
'form.created',
'form.replied',
'form.cancelled',
'permission.asked', 'permission.asked',
'permission.replied', 'permission.replied',
]; ];
@@ -328,7 +331,11 @@ class AppState extends ChangeNotifier {
final type = ev['type'] as String? ?? ''; final type = ev['type'] as String? ?? '';
final data = ev['data'] as Map<String, dynamic>? ?? {}; final data = ev['data'] as Map<String, dynamic>? ?? {};
if (chat != null) { if (chat != null) {
final sid = data['sessionID'] as String?; final form = data['form'];
final sid = data['sessionID'] as String? ??
(form is Map<String, dynamic>
? form['sessionID'] as String?
: null);
if (sid != null && sid == chat!.session.id) { if (sid != null && sid == chat!.session.id) {
chat!.handleEvent(type, data, ev['created'] as int? ?? 0); chat!.handleEvent(type, data, ev['created'] as int? ?? 0);
} }
@@ -468,6 +475,8 @@ class AppState extends ChangeNotifier {
Future<void> openChat(Session s) async { Future<void> openChat(Session s) async {
chat = ChatState(this, s); chat = ChatState(this, s);
// The shell shows the new session at once; its messages follow.
notifyListeners();
await chat!.load(); await chat!.load();
notifyListeners(); notifyListeners();
} }
@@ -529,6 +538,9 @@ class ChatState extends ChangeNotifier {
ModelRef? selectedModel; ModelRef? selectedModel;
String selectedAgent; String selectedAgent;
/// The agent's pending questions (native forms), oldest first.
List<FormInfo> forms = [];
/// `/` palette contents, loaded once per open chat. /// `/` palette contents, loaded once per open chat.
List<SlashItem> slashItems = []; List<SlashItem> slashItems = [];
bool slashLoading = false; bool slashLoading = false;
@@ -559,6 +571,7 @@ class ChatState extends ChangeNotifier {
error = null; error = null;
notifyListeners(); notifyListeners();
await reloadTail(); await reloadTail();
await reloadForms();
} catch (e) { } catch (e) {
loading = false; loading = false;
error = e.toString(); 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<void> reloadForms() async {
final cl = app.client;
if (cl == null) return;
try {
forms = await cl.forms(id, directory: dir);
notifyListeners();
} catch (_) {}
}
Future<void> replyForm(FormInfo form, Map<String, Object?> 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<void> 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 /// Refreshes the newest page without dropping the older pages that were
/// already loaded; the server's copy wins for messages it returns. /// already loaded; the server's copy wins for messages it returns.
Future<void> reloadTail() async { Future<void> reloadTail() async {
@@ -1003,6 +1054,23 @@ class ChatState extends ChangeNotifier {
case 'session.tool.progress': case 'session.tool.progress':
if (mid != null) _applyTool(mid, type, data); if (mid != null) _applyTool(mid, type, data);
break; break;
case 'form.created':
final raw = data['form'];
if (raw is Map<String, dynamic>) {
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': case 'session.compaction.started':
final cid = data['inputID'] as String?; final cid = data['inputID'] as String?;
if (cid != null && byId[cid] == null) { if (cid != null && byId[cid] == null) {
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.3.9+309 version: 0.3.10+310
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0