feat: port the client to Flutter (0.3.0)
Replace the MyGo/Go app with a Flutter client that keeps the feature set: - servers: saved servers, passwordless and password login, HTTP/SOCKS5 proxy via dart:io, self-signed certificates and pinning, tokens in flutter_secure_storage (Keystore) - sessions: list with live events, search, new/rename/archive/delete, instance sheet - chat: streaming Markdown (flutter_markdown), reasoning and tool rows, image previews, context usage ring and sheet, model/agent switching, fork/revert, attachments (file_picker), permissions - Android 7.0 (API 24)+, plain http:// works in release (Dart dials sockets directly) - build: China mirrors for Gradle/NDK, Aliyun Maven repositories, and the Gradle distribution pre-seeded; release signed with the test keystore Read-aloud is dropped as requested. Version 0.3.0.
This commit is contained in:
1 parent
24a311f234
commit
aee560172c
2616 files changed
+5810
-672083
No files matched your search
@@ -0,0 +1,415 @@
|
||||
// The OpenChamber HTTP client in Dart: same endpoints and headers as the
|
||||
// Go client (auth, sessions, messages, SSE, proxy, certificate pinning).
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
class ApiError implements Exception {
|
||||
final int status;
|
||||
final String message;
|
||||
ApiError(this.status, this.message);
|
||||
@override
|
||||
String toString() => message.isEmpty ? 'HTTP $status' : message;
|
||||
}
|
||||
|
||||
class Client {
|
||||
final Uri base;
|
||||
final String? proxy; // http://host:port or socks5://host:port
|
||||
final bool insecure;
|
||||
final String? fingerprint;
|
||||
String? token;
|
||||
late HttpClient _http;
|
||||
|
||||
Client(
|
||||
this.base, {
|
||||
this.proxy,
|
||||
this.insecure = false,
|
||||
this.fingerprint,
|
||||
}) {
|
||||
_http = HttpClient();
|
||||
_http.connectionTimeout = const Duration(seconds: 20);
|
||||
if (proxy != null && proxy!.isNotEmpty) {
|
||||
_http.findProxy = (uri) {
|
||||
final u = Uri.parse(proxy!);
|
||||
final scheme = u.scheme.toLowerCase();
|
||||
if (scheme == 'socks5' || scheme == 'socks') {
|
||||
return 'SOCKS ${u.host}:${u.port}';
|
||||
}
|
||||
return 'PROXY ${u.host}:${u.port}';
|
||||
};
|
||||
}
|
||||
if (insecure || (fingerprint != null && fingerprint!.isNotEmpty)) {
|
||||
_http.badCertificateCallback = (cert, host, port) {
|
||||
if (insecure) return true;
|
||||
final der = _sha256(cert.der);
|
||||
return der == fingerprint!.replaceAll(':', '');
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
String get baseUrl => base.toString();
|
||||
|
||||
Future<Map<String, dynamic>> sessionStatus() async {
|
||||
final r = await _json('GET', '/auth/session');
|
||||
return r;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> login(String password, String installId,
|
||||
{String label = 'OpenChamber Native', String clientKind = 'mobile'}) async {
|
||||
return _json('POST', '/auth/session', body: {
|
||||
'password': password,
|
||||
'trustDevice': true,
|
||||
'issueClientToken': true,
|
||||
'dedupeKey': installId,
|
||||
'clientLabel': label,
|
||||
'clientKind': clientKind,
|
||||
'devicePlatform': 'android',
|
||||
});
|
||||
}
|
||||
|
||||
Future<Page<Session>> listSessions({
|
||||
int limit = 50,
|
||||
String? cursor,
|
||||
String order = 'desc',
|
||||
String? search,
|
||||
String? directory,
|
||||
}) async {
|
||||
final query = <String, String>{
|
||||
'limit': '$limit',
|
||||
'order': order,
|
||||
if (cursor != null) 'cursor': cursor,
|
||||
if (search != null && search.isNotEmpty) 'search': search,
|
||||
if (directory != null && directory.isNotEmpty) 'directory': directory,
|
||||
};
|
||||
final r = await _json('GET', '/api/session', query: query, directory: directory);
|
||||
final data = (r['data'] as List? ?? [])
|
||||
.map((e) => Session.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final cursorMap = r['cursor'] as Map<String, dynamic>?;
|
||||
return Page(data,
|
||||
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
|
||||
}
|
||||
|
||||
Future<Set<String>> activeSessions() async {
|
||||
final r = await _json('GET', '/api/session/active');
|
||||
final data = r['data'] as Map<String, dynamic>? ?? {};
|
||||
return data.keys.toSet();
|
||||
}
|
||||
|
||||
Future<Session> createSession({String? title, String? directory}) async {
|
||||
final r = await _json('POST', '/api/session', body: {
|
||||
if (title != null && title.isNotEmpty) 'title': title,
|
||||
if (directory != null && directory.isNotEmpty)
|
||||
'location': {'directory': directory},
|
||||
});
|
||||
return Session.fromJson(r['data'] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> updateSession(String id, {String? title, bool? archived}) async {
|
||||
await _json('PATCH', '/api/session/${Uri.encodeComponent(id)}', body: {
|
||||
if (title != null) 'title': title,
|
||||
if (archived != null) 'archived': archived,
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> deleteSession(String id) async {
|
||||
await _json('DELETE', '/api/session/${Uri.encodeComponent(id)}');
|
||||
}
|
||||
|
||||
Future<Page<Message>> listMessages(String id,
|
||||
{int limit = 30, String? cursor, String order = 'desc', String? directory, bool partShells = true}) async {
|
||||
final query = <String, String>{
|
||||
'limit': '$limit',
|
||||
'order': order,
|
||||
if (cursor != null) 'cursor': cursor,
|
||||
};
|
||||
final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}/message',
|
||||
query: query, directory: directory, partShells: partShells);
|
||||
final data = (r['data'] as List? ?? [])
|
||||
.map((e) => Message.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final cursorMap = r['cursor'] as Map<String, dynamic>?;
|
||||
return Page(data,
|
||||
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
|
||||
}
|
||||
|
||||
Future<Message> getMessage(String sessionId, String messageId, {String? directory}) async {
|
||||
final r = await _json('GET',
|
||||
'/api/session/${Uri.encodeComponent(sessionId)}/message/${Uri.encodeComponent(messageId)}',
|
||||
directory: directory);
|
||||
return Message.fromJson(r);
|
||||
}
|
||||
|
||||
Future<List<ModelInfo>> models(String directory) async {
|
||||
final r = await _json('GET', '/api/model',
|
||||
query: directory.isNotEmpty ? {'location[directory]': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => ModelInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<AgentInfo>> agents(String directory) async {
|
||||
final r = await _json('GET', '/api/agent',
|
||||
query: directory.isNotEmpty ? {'location[directory]': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => AgentInfo.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<List<PermissionRequest>> pendingPermissions(String directory) async {
|
||||
final r = await _json('GET', '/api/permission/request',
|
||||
query: directory.isNotEmpty ? {'directory': directory} : null);
|
||||
return (r['data'] as List? ?? [])
|
||||
.map((e) => PermissionRequest.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> replyPermission(String sessionId, String requestId, String decision,
|
||||
{String message = ''}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/permission/${Uri.encodeComponent(requestId)}/reply',
|
||||
body: {'decision': decision, if (message.isNotEmpty) 'message': message});
|
||||
}
|
||||
|
||||
Future<void> prompt(String sessionId,
|
||||
{String text = '', String? messageId, String? directory, List<Map<String, String>>? files}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
|
||||
body: {
|
||||
if (text.isNotEmpty) 'text': text,
|
||||
if (messageId != null) 'id': messageId,
|
||||
if (files != null && files.isNotEmpty) 'files': files,
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> interrupt(String sessionId, {String? directory}) async {
|
||||
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/interrupt',
|
||||
directory: directory, body: const {});
|
||||
return r['interrupted'] as bool? ?? false;
|
||||
}
|
||||
|
||||
Future<Session> forkSession(String sessionId, {String? directory, String? before}) async {
|
||||
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/fork',
|
||||
directory: directory, body: {if (before != null && before.isNotEmpty) 'before': before});
|
||||
return Session.fromJson(r['data'] as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> stageRevert(String sessionId, {String? directory, required String messageId}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/revert/stage',
|
||||
directory: directory, body: {'messageID': messageId});
|
||||
}
|
||||
|
||||
Future<void> commitRevert(String sessionId, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/revert/commit',
|
||||
directory: directory, body: const {});
|
||||
}
|
||||
|
||||
Future<void> switchModel(String sessionId, ModelRef model, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/model',
|
||||
directory: directory, body: model.toJson());
|
||||
}
|
||||
|
||||
Future<void> switchAgent(String sessionId, String agent, {String? directory}) async {
|
||||
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/agent',
|
||||
directory: directory, body: {'agent': agent});
|
||||
}
|
||||
|
||||
Future<List<int>> rawFile(String path, {String? directory}) async {
|
||||
final res = await _request('GET', '/api/fs/raw',
|
||||
query: {
|
||||
'path': path,
|
||||
'allowOutsideWorkspace': 'true',
|
||||
},
|
||||
directory: directory);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
throw ApiError(res.statusCode, utf8.decode(res.body, allowMalformed: true));
|
||||
}
|
||||
return res.body;
|
||||
}
|
||||
|
||||
/// Subscribes to GET /api/event, yielding each SSE event. The stream ends
|
||||
/// when the connection drops; the caller restarts it with backoff.
|
||||
Stream<Map<String, dynamic>> streamEvents({List<String>? types}) async* {
|
||||
final query = <String, String>{
|
||||
if (types != null) for (final t in types) 'types': t,
|
||||
};
|
||||
final uri = base.resolve('/api/event')
|
||||
.replace(queryParameters: query.isEmpty ? null : query);
|
||||
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');
|
||||
}
|
||||
String data = '';
|
||||
await for (final line in utf8.decoder.bind(res).transform(const LineSplitter())) {
|
||||
if (line.isEmpty) {
|
||||
if (data.isNotEmpty) {
|
||||
final ev = jsonDecode(data) as Map<String, dynamic>;
|
||||
data = '';
|
||||
yield ev;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('data:')) {
|
||||
data = (data.isEmpty ? '' : data + '\n') + line.substring(5).trimLeft();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- transport
|
||||
|
||||
Future<Map<String, dynamic>> _json(String method, String path,
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = false}) async {
|
||||
final res = await _request(method, path,
|
||||
query: query, body: body, directory: directory, partShells: partShells);
|
||||
final text = utf8.decode(res.body, allowMalformed: true);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
String msg = text;
|
||||
try {
|
||||
final j = jsonDecode(text) as Map<String, dynamic>;
|
||||
msg = (j['error'] as String?) ?? ((j['message'] as String?) ?? text);
|
||||
} catch (_) {}
|
||||
throw ApiError(res.statusCode, msg.trim());
|
||||
}
|
||||
if (text.isEmpty) return const {};
|
||||
try {
|
||||
return jsonDecode(text) as Map<String, dynamic>;
|
||||
} catch (_) {
|
||||
throw ApiError(res.statusCode, 'invalid JSON');
|
||||
}
|
||||
}
|
||||
|
||||
Future<_Response> _request(String method, String path,
|
||||
{Map<String, String>? query,
|
||||
Map<String, dynamic>? body,
|
||||
String? directory,
|
||||
bool partShells = 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);
|
||||
req.headers.set('Accept', 'application/json');
|
||||
req.headers.set('User-Agent', 'openchamber-native/0.3');
|
||||
if (body != null) {
|
||||
req.headers.contentType = ContentType.json;
|
||||
req.write(jsonEncode(body));
|
||||
}
|
||||
if (token != null && token!.isNotEmpty) {
|
||||
req.headers.set('Authorization', 'Bearer $token');
|
||||
}
|
||||
if (directory != null && directory.isNotEmpty) {
|
||||
req.headers.set('x-opencode-directory', Uri.encodeComponent(directory));
|
||||
req.headers.set('x-opencode-directory-encoding', 'uri');
|
||||
}
|
||||
if (partShells) {
|
||||
req.headers.set('x-openchamber-part-shells', 'v1');
|
||||
}
|
||||
if (path == '/api/event') {
|
||||
req.headers.set('Accept', 'text/event-stream');
|
||||
req.headers.set('Cache-Control', 'no-cache');
|
||||
}
|
||||
final res = await req.close();
|
||||
final bodyBytes = await res.fold<List<int>>(<int>[], (a, b) => a..addAll(b));
|
||||
return _Response(res.statusCode, bodyBytes);
|
||||
}
|
||||
|
||||
void close() => _http.close();
|
||||
}
|
||||
|
||||
class _Response {
|
||||
final int statusCode;
|
||||
final List<int> body;
|
||||
_Response(this.statusCode, this.body);
|
||||
}
|
||||
|
||||
String _sha256(List<int> bytes) {
|
||||
return _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,
|
||||
]);
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
// OpenChamber API models, ported from the Go client's protocol knowledge.
|
||||
library;
|
||||
|
||||
class ModelRef {
|
||||
final String id;
|
||||
final String providerId;
|
||||
final String? variant;
|
||||
ModelRef(this.id, this.providerId, [this.variant]);
|
||||
factory ModelRef.fromJson(Map<String, dynamic> j) =>
|
||||
ModelRef(j['id'] as String, j['providerID'] as String, j['variant'] as String?);
|
||||
Map<String, dynamic> toJson() =>
|
||||
{'id': id, 'providerID': providerId, if (variant != null) 'variant': variant};
|
||||
}
|
||||
|
||||
class TokenUsage {
|
||||
final int? total;
|
||||
final int input;
|
||||
final int output;
|
||||
final int reasoning;
|
||||
final int cacheRead;
|
||||
final int cacheWrite;
|
||||
TokenUsage({
|
||||
this.total,
|
||||
this.input = 0,
|
||||
this.output = 0,
|
||||
this.reasoning = 0,
|
||||
this.cacheRead = 0,
|
||||
this.cacheWrite = 0,
|
||||
});
|
||||
factory TokenUsage.fromJson(Map<String, dynamic> j) {
|
||||
final cache = j['cache'] as Map<String, dynamic>? ?? {};
|
||||
return TokenUsage(
|
||||
total: j['total'] as int?,
|
||||
input: (j['input'] as num?)?.toInt() ?? 0,
|
||||
output: (j['output'] as num?)?.toInt() ?? 0,
|
||||
reasoning: (j['reasoning'] as num?)?.toInt() ?? 0,
|
||||
cacheRead: (cache['read'] as num?)?.toInt() ?? 0,
|
||||
cacheWrite: (cache['write'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
int get used =>
|
||||
(total ?? 0) > 0 ? total! : input + output + reasoning + cacheRead + cacheWrite;
|
||||
}
|
||||
|
||||
class Location {
|
||||
final String directory;
|
||||
final String? projectId;
|
||||
Location(this.directory, [this.projectId]);
|
||||
factory Location.fromJson(Map<String, dynamic> j) =>
|
||||
Location(j['directory'] as String? ?? '', j['projectId'] as String?);
|
||||
}
|
||||
|
||||
class Session {
|
||||
final String id;
|
||||
final String title;
|
||||
final String agent;
|
||||
final ModelRef? model;
|
||||
final Location? location;
|
||||
final int created;
|
||||
final int updated;
|
||||
Session({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.agent = '',
|
||||
this.model,
|
||||
this.location,
|
||||
this.created = 0,
|
||||
this.updated = 0,
|
||||
});
|
||||
factory Session.fromJson(Map<String, dynamic> j) {
|
||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||
return Session(
|
||||
id: j['id'] as String,
|
||||
title: j['title'] as String? ?? '',
|
||||
agent: j['agent'] as String? ?? '',
|
||||
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
||||
location: j['location'] == null ? null : Location.fromJson(j['location'] as Map<String, dynamic>),
|
||||
created: (t['created'] as num?)?.toInt() ?? 0,
|
||||
updated: (t['updated'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
String get directory => location?.directory ?? '';
|
||||
}
|
||||
|
||||
class ContentPart {
|
||||
final String type;
|
||||
final String text;
|
||||
final String? id;
|
||||
final String? name;
|
||||
final ToolState? state;
|
||||
final String? mime;
|
||||
final String? url;
|
||||
final String? uri;
|
||||
final String? filename;
|
||||
ContentPart({
|
||||
this.type = '',
|
||||
this.text = '',
|
||||
this.id,
|
||||
this.name,
|
||||
this.state,
|
||||
this.mime,
|
||||
this.url,
|
||||
this.uri,
|
||||
this.filename,
|
||||
});
|
||||
factory ContentPart.fromJson(Map<String, dynamic> j) => ContentPart(
|
||||
type: j['type'] as String? ?? '',
|
||||
text: j['text'] as String? ?? '',
|
||||
id: j['id'] as String?,
|
||||
name: j['name'] as String?,
|
||||
state: j['state'] == null ? null : ToolState.fromJson(j['state'] as Map<String, dynamic>),
|
||||
mime: j['mime'] as String?,
|
||||
url: j['url'] as String?,
|
||||
uri: j['uri'] as String?,
|
||||
filename: j['filename'] as String?,
|
||||
);
|
||||
Map<String, dynamic> toJson() => {
|
||||
if (type.isNotEmpty) 'type': type,
|
||||
if (text.isNotEmpty) 'text': text,
|
||||
if (state != null) 'state': state!.toJson(),
|
||||
};
|
||||
}
|
||||
|
||||
class ToolState {
|
||||
String status;
|
||||
Map<String, dynamic> input;
|
||||
List<ContentPart> content;
|
||||
List<ContentPart> attachments;
|
||||
Map<String, dynamic>? metadata;
|
||||
String? error;
|
||||
ToolState({
|
||||
this.status = '',
|
||||
Map<String, dynamic>? input,
|
||||
List<ContentPart>? content,
|
||||
List<ContentPart>? attachments,
|
||||
this.metadata,
|
||||
this.error,
|
||||
}) : input = input ?? {},
|
||||
content = content ?? [],
|
||||
attachments = attachments ?? [];
|
||||
factory ToolState.fromJson(Map<String, dynamic> j) => ToolState(
|
||||
status: j['status'] as String? ?? '',
|
||||
input: j['input'] as Map<String, dynamic>? ?? {},
|
||||
content: (j['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
attachments: (j['attachments'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
metadata: j['metadata'] as Map<String, dynamic>?,
|
||||
error: j['error'] == null ? null : _jsonString(j['error']),
|
||||
);
|
||||
Map<String, dynamic> toJson() => {
|
||||
'status': status,
|
||||
if (input.isNotEmpty) 'input': input,
|
||||
if (content.isNotEmpty) 'content': content.map((e) => e.toJson()).toList(),
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
};
|
||||
}
|
||||
|
||||
class Message {
|
||||
final String id;
|
||||
final String type;
|
||||
final int created;
|
||||
final int completed;
|
||||
final String agent;
|
||||
final ModelRef? model;
|
||||
final List<ContentPart> content;
|
||||
final String text;
|
||||
final List<FileAttachment> files;
|
||||
final String finish;
|
||||
final double cost;
|
||||
final TokenUsage? tokens;
|
||||
Message({
|
||||
required this.id,
|
||||
required this.type,
|
||||
this.created = 0,
|
||||
this.completed = 0,
|
||||
this.agent = '',
|
||||
this.model,
|
||||
this.content = const [],
|
||||
this.text = '',
|
||||
this.files = const [],
|
||||
this.finish = '',
|
||||
this.cost = 0,
|
||||
this.tokens,
|
||||
});
|
||||
factory Message.fromJson(Map<String, dynamic> j) {
|
||||
final t = j['time'] as Map<String, dynamic>? ?? {};
|
||||
return Message(
|
||||
id: j['id'] as String,
|
||||
type: j['type'] as String? ?? '',
|
||||
created: (t['created'] as num?)?.toInt() ?? 0,
|
||||
completed: (t['completed'] as num?)?.toInt() ?? 0,
|
||||
agent: j['agent'] as String? ?? '',
|
||||
model: j['model'] == null ? null : ModelRef.fromJson(j['model'] as Map<String, dynamic>),
|
||||
content: (j['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
text: j['text'] as String? ?? '',
|
||||
files: (j['files'] as List?)
|
||||
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
const [],
|
||||
finish: j['finish'] as String? ?? '',
|
||||
cost: (j['cost'] as num?)?.toDouble() ?? 0,
|
||||
tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>),
|
||||
);
|
||||
}
|
||||
String get partText {
|
||||
final buf = StringBuffer();
|
||||
for (final p in content) {
|
||||
if (p.type == 'text' && p.text.isNotEmpty) buf.write(p.text);
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class FileAttachment {
|
||||
final String name;
|
||||
final String mime;
|
||||
FileAttachment(this.name, this.mime);
|
||||
factory FileAttachment.fromJson(Map<String, dynamic> j) =>
|
||||
FileAttachment(j['name'] as String? ?? '', j['mime'] as String? ?? '');
|
||||
}
|
||||
|
||||
class Page<T> {
|
||||
final List<T> data;
|
||||
final String? next;
|
||||
final String? previous;
|
||||
Page(this.data, {this.next, this.previous});
|
||||
}
|
||||
|
||||
class AuthStatus {
|
||||
final bool authenticated;
|
||||
final bool disabled;
|
||||
final bool locked;
|
||||
AuthStatus(this.authenticated, this.disabled, this.locked);
|
||||
}
|
||||
|
||||
class ModelInfo {
|
||||
final String id;
|
||||
final String providerId;
|
||||
final String name;
|
||||
final int context;
|
||||
final int output;
|
||||
ModelInfo(this.id, this.providerId, this.name, this.context, this.output);
|
||||
factory ModelInfo.fromJson(Map<String, dynamic> j) {
|
||||
final lim = j['limit'] as Map<String, dynamic>? ?? {};
|
||||
return ModelInfo(
|
||||
j['id'] as String,
|
||||
j['providerID'] as String? ?? '',
|
||||
j['name'] as String? ?? (j['id'] as String? ?? ''),
|
||||
(lim['context'] as num?)?.toInt() ?? 0,
|
||||
(lim['output'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AgentInfo {
|
||||
final String id;
|
||||
final String name;
|
||||
final String mode;
|
||||
AgentInfo(this.id, this.name, this.mode);
|
||||
factory AgentInfo.fromJson(Map<String, dynamic> j) =>
|
||||
AgentInfo(j['id'] as String, j['name'] as String? ?? '', j['mode'] as String? ?? '');
|
||||
}
|
||||
|
||||
class PermissionRequest {
|
||||
final String id;
|
||||
final String sessionId;
|
||||
final String action;
|
||||
final List<String> resources;
|
||||
PermissionRequest(this.id, this.sessionId, this.action, this.resources);
|
||||
factory PermissionRequest.fromJson(Map<String, dynamic> j) => PermissionRequest(
|
||||
j['id'] as String,
|
||||
j['sessionID'] as String? ?? '',
|
||||
j['action'] as String? ?? '',
|
||||
(j['resources'] as List?)?.map((e) => e.toString()).toList() ?? const [],
|
||||
);
|
||||
}
|
||||
|
||||
String _jsonString(Object? o) {
|
||||
if (o is String) return o;
|
||||
return o.toString();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'screens/servers_screen.dart';
|
||||
import 'screens/sessions_screen.dart';
|
||||
import 'state.dart';
|
||||
|
||||
void main() {
|
||||
runApp(const OpenChamberApp());
|
||||
}
|
||||
|
||||
class OpenChamberApp extends StatefulWidget {
|
||||
const OpenChamberApp({super.key});
|
||||
@override
|
||||
State<OpenChamberApp> createState() => _OpenChamberAppState();
|
||||
}
|
||||
|
||||
class _OpenChamberAppState extends State<OpenChamberApp> {
|
||||
final AppState app = AppState();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
app.init();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: app,
|
||||
builder: (context, _) {
|
||||
final home = app.client == null
|
||||
? ServersScreen(app: app)
|
||||
: SessionsScreen(app: app);
|
||||
return MaterialApp(
|
||||
title: 'OpenChamber',
|
||||
theme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: const Color(0xFF6C5CE7),
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
useMaterial3: true,
|
||||
),
|
||||
darkTheme: ThemeData(
|
||||
colorScheme: ColorScheme.fromSeed(
|
||||
seedColor: const Color(0xFF6C5CE7),
|
||||
brightness: Brightness.dark,
|
||||
),
|
||||
useMaterial3: true,
|
||||
),
|
||||
home: home,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,317 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../state.dart';
|
||||
import '../storage.dart';
|
||||
|
||||
/// The first screen: the saved servers, or the connect form.
|
||||
class ServersScreen extends StatefulWidget {
|
||||
final AppState app;
|
||||
const ServersScreen({super.key, required this.app});
|
||||
|
||||
@override
|
||||
State<ServersScreen> createState() => _ServersScreenState();
|
||||
}
|
||||
|
||||
class _ServersScreenState extends State<ServersScreen> {
|
||||
bool _editing = false;
|
||||
bool _editNew = true;
|
||||
Connection? _edit;
|
||||
String _label = '';
|
||||
String _url = '';
|
||||
String _proxy = '';
|
||||
bool _insecure = false;
|
||||
String _fingerprint = '';
|
||||
String _password = '';
|
||||
bool _connecting = false;
|
||||
String? _formError;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListenableBuilder(
|
||||
listenable: widget.app,
|
||||
builder: (context, _) {
|
||||
if (_editing) return _form();
|
||||
return _list();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _list() {
|
||||
final theme = Theme.of(context);
|
||||
final conns = widget.app.connections;
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('OpenChamber',
|
||||
style: theme.textTheme.headlineMedium
|
||||
?.copyWith(fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
Text('连接你的 OpenChamber 服务器',
|
||||
style: theme.textTheme.bodyMedium
|
||||
?.copyWith(color: theme.hintColor)),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (widget.app.error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: Text(widget.app.error!,
|
||||
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
for (final c in conns) _serverCard(c),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => _startEdit(null),
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('添加服务器'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _serverCard(Connection c) {
|
||||
final theme = Theme.of(context);
|
||||
final connected = widget.app.conn?.id == c.id;
|
||||
return Card(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
child: ListTile(
|
||||
title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (connected)
|
||||
Text('已连接', style: TextStyle(color: theme.colorScheme.primary))
|
||||
else
|
||||
TextButton(onPressed: () => _connect(c), child: const Text('连接')),
|
||||
PopupMenuButton<String>(
|
||||
onSelected: (v) {
|
||||
if (v == 'edit') {
|
||||
_startEdit(c);
|
||||
} else if (v == 'delete') {
|
||||
_confirmDelete(c);
|
||||
}
|
||||
},
|
||||
itemBuilder: (_) => const [
|
||||
PopupMenuItem(value: 'edit', child: Text('编辑')),
|
||||
PopupMenuItem(value: 'delete', child: Text('删除')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _connect(Connection c) async {
|
||||
setState(() {
|
||||
_connecting = true;
|
||||
_editNew = false;
|
||||
_edit = c;
|
||||
});
|
||||
await widget.app.connect(c);
|
||||
if (mounted && widget.app.client == null && widget.app.lastError != null) {
|
||||
setState(() {
|
||||
_connecting = false;
|
||||
_editing = true;
|
||||
_edit = c;
|
||||
_label = c.label;
|
||||
_url = c.url;
|
||||
_proxy = c.proxy;
|
||||
_insecure = c.insecure;
|
||||
_fingerprint = c.fingerprint;
|
||||
_password = '';
|
||||
_formError = widget.app.lastError;
|
||||
});
|
||||
widget.app.clearLastError();
|
||||
} else if (mounted) {
|
||||
setState(() => _connecting = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _startEdit(Connection? c) {
|
||||
setState(() {
|
||||
_editing = true;
|
||||
_editNew = c == null;
|
||||
_edit = c;
|
||||
_label = c?.label ?? '';
|
||||
_url = c?.url ?? '';
|
||||
_proxy = c?.proxy ?? '';
|
||||
_insecure = c?.insecure ?? false;
|
||||
_fingerprint = c?.fingerprint ?? '';
|
||||
_password = '';
|
||||
_formError = null;
|
||||
});
|
||||
}
|
||||
|
||||
Widget _form() {
|
||||
final theme = Theme.of(context);
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => setState(() => _editing = false),
|
||||
),
|
||||
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
|
||||
),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
_labelText('名称'),
|
||||
TextField(
|
||||
controller: TextEditingController(text: _label),
|
||||
onChanged: (v) => _label = v,
|
||||
decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_labelText('服务器地址'),
|
||||
TextField(
|
||||
controller: TextEditingController(text: _url),
|
||||
onChanged: (v) => _url = v,
|
||||
keyboardType: TextInputType.url,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_labelText('代理(可选)'),
|
||||
TextField(
|
||||
controller: TextEditingController(text: _proxy),
|
||||
onChanged: (v) => _proxy = v,
|
||||
keyboardType: TextInputType.url,
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_labelText('自签证书指纹(可选)'),
|
||||
TextField(
|
||||
controller: TextEditingController(text: _fingerprint),
|
||||
onChanged: (v) => _fingerprint = v,
|
||||
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
|
||||
),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('信任自签名证书'),
|
||||
value: _insecure,
|
||||
onChanged: (v) => setState(() => _insecure = v),
|
||||
),
|
||||
if (!_editNew) ...[
|
||||
_labelText('密码'),
|
||||
TextField(
|
||||
controller: TextEditingController(text: _password),
|
||||
onChanged: (v) => _password = v,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '服务器密码', border: OutlineInputBorder()),
|
||||
),
|
||||
],
|
||||
if (_formError != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(_formError!,
|
||||
style: TextStyle(color: theme.colorScheme.error)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: _connecting ? null : _submit,
|
||||
child: _connecting
|
||||
? const SizedBox(
|
||||
height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('连接'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _labelText(String s) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Text(s, style: Theme.of(context).textTheme.bodySmall),
|
||||
);
|
||||
|
||||
Future<void> _submit() async {
|
||||
setState(() {
|
||||
_connecting = true;
|
||||
_formError = null;
|
||||
});
|
||||
final c = Connection(
|
||||
id: _edit?.id ?? _newId(),
|
||||
label: _label.isEmpty ? _hostOf(_url) : _label,
|
||||
url: _url,
|
||||
proxy: _proxy,
|
||||
insecure: _insecure,
|
||||
fingerprint: _fingerprint,
|
||||
);
|
||||
if (_editNew) {
|
||||
await widget.app.saveConnection(c);
|
||||
} else {
|
||||
final list = [...widget.app.connections];
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i].id == c.id) {
|
||||
list[i] = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
widget.app.connections = list;
|
||||
await widget.app.storage.saveConnections(list);
|
||||
}
|
||||
await widget.app.connect(c, password: _password);
|
||||
if (mounted) {
|
||||
if (widget.app.client != null) {
|
||||
setState(() => _editing = false);
|
||||
} else {
|
||||
setState(() {
|
||||
_connecting = false;
|
||||
_formError = widget.app.lastError;
|
||||
});
|
||||
widget.app.clearLastError();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _confirmDelete(Connection c) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('删除服务器?'),
|
||||
content: Text('“${c.label}”将从列表移除,设备令牌也会删除。'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
widget.app.removeConnection(c);
|
||||
},
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
static String _newId() =>
|
||||
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
|
||||
|
||||
static String _hostOf(String raw) {
|
||||
try {
|
||||
return Uri.parse(raw).host;
|
||||
} catch (_) {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../api/models.dart';
|
||||
import '../state.dart';
|
||||
import 'chat_screen.dart';
|
||||
|
||||
/// The connected screen: the live session list.
|
||||
class SessionsScreen extends StatefulWidget {
|
||||
final AppState app;
|
||||
const SessionsScreen({super.key, required this.app});
|
||||
|
||||
@override
|
||||
State<SessionsScreen> createState() => _SessionsScreenState();
|
||||
}
|
||||
|
||||
class _SessionsScreenState extends State<SessionsScreen> {
|
||||
bool _searchOpen = false;
|
||||
Timer? _timer;
|
||||
late final TextEditingController _searchCtrl;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_searchCtrl = TextEditingController();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
_searchCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onSearchChanged(String v) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer(const Duration(milliseconds: 350), () {
|
||||
if (v.isEmpty) {
|
||||
widget.app.refreshSessions();
|
||||
} else {
|
||||
widget.app.searchSessions(v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final app = widget.app;
|
||||
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(
|
||||
children: [
|
||||
if (_searchOpen)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 4),
|
||||
child: TextField(
|
||||
controller: _searchCtrl,
|
||||
autofocus: true,
|
||||
onChanged: _onSearchChanged,
|
||||
decoration: const InputDecoration(
|
||||
hintText: '搜索会话',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (app.error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(app.error!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 13)),
|
||||
),
|
||||
TextButton(onPressed: app.refreshSessions, child: const Text('重试')),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(child: _body()),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body() {
|
||||
final app = widget.app;
|
||||
if (app.sessionsLoading && app.sessions.isEmpty) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (app.sessions.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('暂无会话'),
|
||||
const SizedBox(height: 8),
|
||||
FilledButton(onPressed: _newSessionSheet, child: const Text('新建会话')),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return RefreshIndicator(
|
||||
onRefresh: app.refreshSessions,
|
||||
child: ListView.builder(
|
||||
itemCount: app.sessions.length,
|
||||
itemBuilder: (context, i) {
|
||||
final s = app.sessions[i];
|
||||
final running = app.active.contains(s.id);
|
||||
return ListTile(
|
||||
title: Text(s.title.isEmpty ? '(无标题会话)' : s.title,
|
||||
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: Text(_subtitle(s),
|
||||
maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (running)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: Icon(Icons.circle, size: 10, color: Theme.of(context).colorScheme.primary),
|
||||
),
|
||||
PopupMenuButton<String>(
|
||||
onSelected: (v) => _sessionAction(s, v),
|
||||
itemBuilder: (_) => const [
|
||||
PopupMenuItem(value: 'rename', child: Text('重命名')),
|
||||
PopupMenuItem(value: 'archive', child: Text('归档')),
|
||||
PopupMenuItem(value: 'delete', child: Text('删除')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
app.openChat(s);
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(builder: (_) => ChatScreen(app: app, session: s)),
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _subtitle(Session s) {
|
||||
final parts = <String>[];
|
||||
if (s.agent.isNotEmpty) parts.add(s.agent);
|
||||
if (s.model != null) parts.add(widget.app.modelName(s.model));
|
||||
if (s.updated > 0) {
|
||||
final t = DateTime.fromMillisecondsSinceEpoch(s.updated);
|
||||
parts.add('${t.month.toString().padLeft(2, '0')}-${t.day.toString().padLeft(2, '0')} '
|
||||
'${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}');
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
void _sessionAction(Session s, String v) {
|
||||
switch (v) {
|
||||
case 'rename':
|
||||
_rename(s);
|
||||
break;
|
||||
case 'archive':
|
||||
widget.app.client?.updateSession(s.id, archived: true);
|
||||
break;
|
||||
case 'delete':
|
||||
_confirmDelete(s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _rename(Session s) {
|
||||
final ctrl = TextEditingController(text: s.title);
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('重命名'),
|
||||
content: TextField(controller: ctrl, autofocus: true),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
widget.app.client?.updateSession(s.id, title: ctrl.text);
|
||||
},
|
||||
child: const Text('保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _confirmDelete(Session s) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('删除会话?'),
|
||||
content: Text('“${s.title}”及其子会话将被删除,且无法恢复。'),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
widget.app.client?.deleteSession(s.id);
|
||||
widget.app.sessions.removeWhere((x) => x.id == s.id);
|
||||
widget.app.touch();
|
||||
},
|
||||
child: const Text('删除'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _newSessionSheet() {
|
||||
final ctrl = TextEditingController();
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text('新建会话', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: ctrl,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(hintText: '标题(可选)', border: OutlineInputBorder()),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
Navigator.pop(context);
|
||||
final s = await widget.app.client?.createSession(
|
||||
title: ctrl.text, directory: widget.app.directory);
|
||||
if (s != null) {
|
||||
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)),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
child: const Text('创建'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _instancesSheet() {
|
||||
final app = widget.app;
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
builder: (context) => SafeArea(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(12),
|
||||
child: Text('服务器', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
),
|
||||
for (final c in app.connections) ...[
|
||||
ListTile(
|
||||
title: Text(c.label),
|
||||
subtitle: Text(c.url),
|
||||
trailing: app.conn?.id == c.id
|
||||
? Text('已连接', style: TextStyle(color: Theme.of(context).colorScheme.primary))
|
||||
: null,
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
if (app.conn?.id != c.id) app.switchTo(c);
|
||||
},
|
||||
),
|
||||
],
|
||||
ListTile(
|
||||
leading: const Icon(Icons.add),
|
||||
title: const Text('添加服务器'),
|
||||
onTap: () => Navigator.pop(context),
|
||||
),
|
||||
if (app.client != null)
|
||||
ListTile(
|
||||
leading: const Icon(Icons.link_off),
|
||||
title: const Text('断开当前连接'),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
app.disconnect();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+868
@@ -0,0 +1,868 @@
|
||||
// The app's state: connections, the live session list and the open chat.
|
||||
// SSE events fold into it and notify listeners, which rebuild the UI.
|
||||
library;
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'api/client.dart';
|
||||
import 'api/models.dart';
|
||||
import 'storage.dart';
|
||||
|
||||
const _eventTypes = [
|
||||
'session.created',
|
||||
'session.renamed',
|
||||
'session.archived',
|
||||
'session.unarchived',
|
||||
'session.deleted',
|
||||
'session.moved',
|
||||
'session.model.selected',
|
||||
'session.agent.selected',
|
||||
'session.metadata.updated',
|
||||
'session.execution.started',
|
||||
'session.execution.succeeded',
|
||||
'session.execution.failed',
|
||||
'session.execution.interrupted',
|
||||
'session.step.started',
|
||||
'session.step.ended',
|
||||
'session.step.failed',
|
||||
'session.text.started',
|
||||
'session.text.delta',
|
||||
'session.text.ended',
|
||||
'session.reasoning.started',
|
||||
'session.reasoning.delta',
|
||||
'session.reasoning.ended',
|
||||
'session.tool.called',
|
||||
'session.tool.success',
|
||||
'session.tool.failed',
|
||||
'permission.asked',
|
||||
'permission.replied',
|
||||
];
|
||||
|
||||
class AppState extends ChangeNotifier {
|
||||
final Storage storage = Storage();
|
||||
|
||||
Client? client;
|
||||
Connection? conn;
|
||||
bool busy = false;
|
||||
List<Connection> connections = [];
|
||||
List<Session> sessions = [];
|
||||
bool sessionsLoading = false;
|
||||
String? error;
|
||||
Set<String> active = {};
|
||||
List<PermissionRequest> perms = [];
|
||||
Map<String, String> modelNames = {};
|
||||
Map<String, (int, int)> modelLimits = {}; // "provider/id" -> (context, output)
|
||||
List<ModelInfo> modelList = [];
|
||||
List<AgentInfo> agentList = [];
|
||||
|
||||
ChatState? chat;
|
||||
|
||||
/// Public way to signal UI changes (notifyListeners is protected).
|
||||
void touch() => notifyListeners();
|
||||
|
||||
Future<void> init() async {
|
||||
connections = await storage.connections();
|
||||
if (connections.isNotEmpty) {
|
||||
connect(connections.first, silent: true);
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Client _buildClient(Connection c) {
|
||||
return Client(Uri.parse(c.url),
|
||||
proxy: c.proxy.isEmpty ? null : c.proxy,
|
||||
insecure: c.insecure,
|
||||
fingerprint: c.fingerprint.isEmpty ? null : c.fingerprint);
|
||||
}
|
||||
|
||||
Future<void> connect(Connection c, {String password = '', bool silent = false}) async {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
final cl = _buildClient(c);
|
||||
try {
|
||||
var token = await storage.loadToken(c.id);
|
||||
if (token == null || token.isEmpty) {
|
||||
// No saved token: a passwordless server needs none.
|
||||
try {
|
||||
final st = await cl.sessionStatus();
|
||||
if (st['disabled'] == true && st['locked'] != true) {
|
||||
token = '';
|
||||
}
|
||||
} on ApiError {
|
||||
if (password.isEmpty) {
|
||||
throw ApiError(401, '需要密码或已保存的凭据');
|
||||
}
|
||||
}
|
||||
if (token == null && password.isNotEmpty) {
|
||||
final res = await cl.login(password, await storage.installId());
|
||||
token = res['clientToken'] as String? ?? '';
|
||||
if (token.isEmpty) throw ApiError(401, '登录成功但没有返回令牌');
|
||||
await storage.saveToken(c.id, token);
|
||||
}
|
||||
}
|
||||
if (token != null && token.isNotEmpty) cl.token = token;
|
||||
busy = false;
|
||||
_connected(cl, c);
|
||||
} catch (e) {
|
||||
busy = false;
|
||||
error = e.toString();
|
||||
if (!silent) {
|
||||
// Surface in the form: the UI reads error itself.
|
||||
_lastError = e.toString();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
String? _lastError;
|
||||
String? get lastError => _lastError;
|
||||
void clearLastError() => _lastError = null;
|
||||
|
||||
void _connected(Client cl, Connection c) {
|
||||
client = cl;
|
||||
conn = c;
|
||||
final list = [...connections];
|
||||
var found = false;
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i].id == c.id) {
|
||||
list[i] = c.copyWith(lastUsedAt: DateTime.now().millisecondsSinceEpoch);
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
list.insert(0, c.copyWith(lastUsedAt: DateTime.now().millisecondsSinceEpoch));
|
||||
}
|
||||
connections = list;
|
||||
storage.saveConnections(list);
|
||||
_startStream();
|
||||
refreshSessions();
|
||||
refreshActive();
|
||||
refreshPerms();
|
||||
refreshModels();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
client?.close();
|
||||
client = null;
|
||||
conn = null;
|
||||
chat = null;
|
||||
sessions = [];
|
||||
perms = [];
|
||||
error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> switchTo(Connection c) async {
|
||||
await disconnect();
|
||||
await connect(c, silent: true);
|
||||
}
|
||||
|
||||
String get directory {
|
||||
if (chat != null) return chat!.session.directory;
|
||||
if (sessions.isNotEmpty) return sessions.first.directory;
|
||||
return '';
|
||||
}
|
||||
|
||||
Future<void> refreshSessions() async {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
sessionsLoading = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final page = await cl.listSessions();
|
||||
sessions = page.data;
|
||||
sessionsLoading = false;
|
||||
} catch (e) {
|
||||
sessionsLoading = false;
|
||||
error = e.toString();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> searchSessions(String q) async {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
sessionsLoading = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final page = await cl.listSessions(search: q);
|
||||
sessions = page.data;
|
||||
sessionsLoading = false;
|
||||
} catch (_) {
|
||||
sessionsLoading = false;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> refreshActive() async {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
try {
|
||||
active = await cl.activeSessions();
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> refreshPerms() async {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
try {
|
||||
perms = await cl.pendingPermissions(directory);
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> refreshModels() async {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
try {
|
||||
final models = await cl.models(directory);
|
||||
final names = <String, String>{};
|
||||
final limits = <String, (int, int)>{};
|
||||
for (final m in models) {
|
||||
names['${m.providerId}/${m.id}'] = m.name;
|
||||
names[m.id] = m.name;
|
||||
limits['${m.providerId}/${m.id}'] = (m.context, m.output);
|
||||
limits[m.id] = (m.context, m.output);
|
||||
}
|
||||
modelNames = names;
|
||||
modelLimits = limits;
|
||||
modelList = models;
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
try {
|
||||
agentList = await cl.agents(directory);
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
String modelName(ModelRef? m) {
|
||||
if (m == null) return '';
|
||||
return modelNames['${m.providerId}/${m.id}'] ??
|
||||
modelNames[m.id] ??
|
||||
m.id;
|
||||
}
|
||||
|
||||
void _startStream() {
|
||||
final cl = client;
|
||||
if (cl == null) return;
|
||||
Future<void> loop() async {
|
||||
while (client == cl) {
|
||||
try {
|
||||
await for (final ev in cl.streamEvents(types: _eventTypes)) {
|
||||
if (client != cl) return;
|
||||
_applyEvent(ev);
|
||||
}
|
||||
} catch (_) {
|
||||
// Connection dropped; fall through to the retry below.
|
||||
}
|
||||
if (client != cl) return;
|
||||
error = '连接中断,正在重连…';
|
||||
notifyListeners();
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
}
|
||||
}
|
||||
loop();
|
||||
}
|
||||
|
||||
void _applyEvent(Map<String, dynamic> ev) {
|
||||
final type = ev['type'] as String? ?? '';
|
||||
final data = ev['data'] as Map<String, dynamic>? ?? {};
|
||||
if (chat != null) {
|
||||
final sid = data['sessionID'] as String?;
|
||||
if (sid != null && sid == chat!.session.id) {
|
||||
chat!.handleEvent(type, data, ev['created'] as int? ?? 0);
|
||||
}
|
||||
}
|
||||
switch (type) {
|
||||
case 'session.created':
|
||||
final id = data['sessionID'] as String?;
|
||||
if (id == null) return;
|
||||
if (sessions.any((s) => s.id == id)) return;
|
||||
sessions.insert(
|
||||
0,
|
||||
Session(
|
||||
id: id,
|
||||
title: data['title'] as String? ?? '',
|
||||
agent: data['agent'] as String? ?? '',
|
||||
model: data['model'] == null
|
||||
? null
|
||||
: ModelRef.fromJson(data['model'] as Map<String, dynamic>),
|
||||
location: data['location'] == null
|
||||
? null
|
||||
: Location.fromJson(data['location'] as Map<String, dynamic>),
|
||||
created: ev['created'] as int? ?? 0,
|
||||
updated: ev['created'] as int? ?? 0,
|
||||
));
|
||||
break;
|
||||
case 'session.renamed':
|
||||
final id = data['sessionID'] as String?;
|
||||
final title = data['title'] as String?;
|
||||
if (id == null || title == null) return;
|
||||
_patchSession(id, (s) => Session(
|
||||
id: s.id,
|
||||
title: title,
|
||||
agent: s.agent,
|
||||
model: s.model,
|
||||
location: s.location,
|
||||
created: s.created,
|
||||
updated: s.updated));
|
||||
break;
|
||||
case 'session.model.selected':
|
||||
final id = data['sessionID'] as String?;
|
||||
final model = data['model'] == null
|
||||
? null
|
||||
: ModelRef.fromJson(data['model'] as Map<String, dynamic>);
|
||||
if (id == null) return;
|
||||
_patchSession(id, (s) => Session(
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
agent: s.agent,
|
||||
model: model,
|
||||
location: s.location,
|
||||
created: s.created,
|
||||
updated: s.updated));
|
||||
break;
|
||||
case 'session.agent.selected':
|
||||
final id = data['sessionID'] as String?;
|
||||
final agent = data['agent'] as String?;
|
||||
if (id == null || agent == null) return;
|
||||
_patchSession(id, (s) => Session(
|
||||
id: s.id,
|
||||
title: s.title,
|
||||
agent: agent,
|
||||
model: s.model,
|
||||
location: s.location,
|
||||
created: s.created,
|
||||
updated: s.updated));
|
||||
break;
|
||||
case 'session.archived':
|
||||
case 'session.deleted':
|
||||
final id = data['sessionID'] as String?;
|
||||
if (id != null) sessions.removeWhere((s) => s.id == id);
|
||||
break;
|
||||
case 'session.unarchived':
|
||||
case 'session.moved':
|
||||
refreshSessions();
|
||||
return;
|
||||
case 'session.execution.started':
|
||||
final id = data['sessionID'] as String?;
|
||||
if (id != null) active.add(id);
|
||||
break;
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted':
|
||||
final id = data['sessionID'] as String?;
|
||||
if (id != null) active.remove(id);
|
||||
break;
|
||||
case 'permission.asked':
|
||||
final id = data['id'] as String?;
|
||||
if (id == null || perms.any((p) => p.id == id)) return;
|
||||
perms.add(PermissionRequest(
|
||||
id,
|
||||
data['sessionID'] as String? ?? '',
|
||||
data['action'] as String? ?? '',
|
||||
(data['resources'] as List?)?.map((e) => e.toString()).toList() ?? const []));
|
||||
break;
|
||||
case 'permission.replied':
|
||||
final id = data['requestID'] as String?;
|
||||
if (id != null) perms.removeWhere((p) => p.id == id);
|
||||
break;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _patchSession(String id, Session Function(Session) patch) {
|
||||
for (var i = 0; i < sessions.length; i++) {
|
||||
if (sessions[i].id == id) {
|
||||
sessions[i] = patch(sessions[i]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveConnection(Connection c) async {
|
||||
final list = [...connections];
|
||||
var found = false;
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
if (list[i].id == c.id) {
|
||||
list[i] = c;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) list.add(c);
|
||||
connections = list;
|
||||
await storage.saveConnections(list);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> removeConnection(Connection c) async {
|
||||
connections.removeWhere((x) => x.id == c.id);
|
||||
await storage.clearToken(c.id);
|
||||
await storage.saveConnections(connections);
|
||||
if (conn?.id == c.id) {
|
||||
await disconnect();
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> openChat(Session s) async {
|
||||
chat = ChatState(this, s);
|
||||
await chat!.load();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void closeChat() {
|
||||
chat = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The open chat.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class ChatState extends ChangeNotifier {
|
||||
final AppState app;
|
||||
final Session session;
|
||||
List<Message> msgs = [];
|
||||
Map<String, Message> byId = {};
|
||||
bool running = false;
|
||||
bool loading = true;
|
||||
String draft = '';
|
||||
Set<String> expanded = {};
|
||||
Map<String, Map<int, int>> textSlots = {};
|
||||
Map<String, Map<int, int>> reasoningSlots = {};
|
||||
String? error;
|
||||
String? olderCursor;
|
||||
bool hasMore = false;
|
||||
bool loadingOlder = false;
|
||||
Map<String, List<String>> imagePaths = {};
|
||||
final Map<String, String> previewCache = {};
|
||||
bool previewOpen = false;
|
||||
String previewTitle = '';
|
||||
String? previewPath;
|
||||
bool previewLoading = false;
|
||||
int previewSeq = 0;
|
||||
|
||||
ChatState(this.app, this.session);
|
||||
|
||||
/// Public way to signal UI changes.
|
||||
void touch() => notifyListeners();
|
||||
|
||||
String get id => session.id;
|
||||
String get dir => session.directory;
|
||||
|
||||
Future<void> load() async {
|
||||
loading = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final page = await app.client!.listMessages(id, directory: dir);
|
||||
_setMessages(page.data);
|
||||
olderCursor = page.previous;
|
||||
hasMore = page.previous != null;
|
||||
loading = false;
|
||||
notifyListeners();
|
||||
await reloadTail();
|
||||
} catch (e) {
|
||||
loading = false;
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> reloadTail() async {
|
||||
try {
|
||||
final page = await app.client!.listMessages(id, directory: dir);
|
||||
_setMessages(page.data);
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> loadOlder() async {
|
||||
if (!hasMore || loadingOlder) return;
|
||||
loadingOlder = true;
|
||||
final cursor = olderCursor;
|
||||
notifyListeners();
|
||||
try {
|
||||
final page = await app.client!.listMessages(id, cursor: cursor, directory: dir);
|
||||
final seen = msgs.map((m) => m.id).toSet();
|
||||
final older = page.data.where((m) => !seen.contains(m.id)).toList();
|
||||
msgs = [...older, ...msgs];
|
||||
_reindex();
|
||||
olderCursor = page.previous;
|
||||
hasMore = page.previous != null;
|
||||
} catch (_) {}
|
||||
loadingOlder = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _setMessages(List<Message> list) {
|
||||
msgs = list;
|
||||
_reindex();
|
||||
}
|
||||
|
||||
void _reindex() {
|
||||
byId = {for (final m in msgs) m.id: m};
|
||||
}
|
||||
|
||||
Future<String?> send({String? text, List<Map<String, String>>? files}) async {
|
||||
final t = (text ?? draft).trim();
|
||||
if (t.isEmpty && (files == null || files.isEmpty)) return null;
|
||||
final id = _newMsgId();
|
||||
draft = '';
|
||||
msgs.add(Message(
|
||||
id: id,
|
||||
type: 'user',
|
||||
text: t,
|
||||
created: DateTime.now().millisecondsSinceEpoch,
|
||||
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
|
||||
));
|
||||
_reindex();
|
||||
notifyListeners();
|
||||
try {
|
||||
await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files);
|
||||
return id;
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
static String _newMsgId() =>
|
||||
'msg_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
|
||||
|
||||
Future<void> stop() async {
|
||||
try {
|
||||
await app.client!.interrupt(id, directory: dir);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> replyPermission(String requestId, String decision) async {
|
||||
try {
|
||||
await app.client!.replyPermission(id, requestId, decision);
|
||||
app.perms.removeWhere((p) => p.id == requestId);
|
||||
app.notifyListeners();
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> fork({String? before}) async {
|
||||
try {
|
||||
final s = await app.client!.forkSession(id, directory: dir, before: before);
|
||||
app.sessions.insert(0, s);
|
||||
app.touch();
|
||||
await app.openChat(s);
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> revert(String messageId) async {
|
||||
try {
|
||||
await app.client!.stageRevert(id, directory: dir, messageId: messageId);
|
||||
await app.client!.commitRevert(id, directory: dir);
|
||||
await reloadTail();
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> switchModel(ModelRef model) async {
|
||||
try {
|
||||
await app.client!.switchModel(id, model, directory: dir);
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> switchAgent(String agent) async {
|
||||
try {
|
||||
await app.client!.switchAgent(id, agent, directory: dir);
|
||||
} catch (e) {
|
||||
error = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> ensureToolLoaded(String messageId) async {
|
||||
final m = byId[messageId];
|
||||
if (m == null) return;
|
||||
for (final p in m.content) {
|
||||
final meta = p.state?.metadata;
|
||||
if (p.type == 'tool' && meta != null && meta.containsKey('openchamberContentShell')) {
|
||||
try {
|
||||
final full = await app.client!.getMessage(id, messageId, directory: dir);
|
||||
_patch(messageId, (_) => full);
|
||||
notifyListeners();
|
||||
} catch (_) {}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _patch(String messageId, Message Function(Message) patch) {
|
||||
for (var i = 0; i < msgs.length; i++) {
|
||||
if (msgs[i].id == messageId) {
|
||||
msgs[i] = patch(msgs[i]);
|
||||
_reindex();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ events
|
||||
|
||||
void handleEvent(String type, Map<String, dynamic> data, int created) {
|
||||
final mid = data['assistantMessageID'] as String?;
|
||||
if (mid != null) {
|
||||
_ensureAssistant(mid, created);
|
||||
}
|
||||
switch (type) {
|
||||
case 'session.execution.started':
|
||||
running = true;
|
||||
break;
|
||||
case 'session.execution.succeeded':
|
||||
case 'session.execution.failed':
|
||||
case 'session.execution.interrupted':
|
||||
running = false;
|
||||
break;
|
||||
case 'session.step.started':
|
||||
running = true;
|
||||
break;
|
||||
case 'session.step.ended':
|
||||
case 'session.step.failed':
|
||||
if (mid != null) {
|
||||
_patch(mid, (m) => Message(
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
created: m.created,
|
||||
completed: created,
|
||||
agent: m.agent,
|
||||
model: m.model,
|
||||
content: m.content,
|
||||
text: m.text,
|
||||
files: m.files,
|
||||
finish: data['finish'] as String? ?? m.finish,
|
||||
cost: (data['cost'] as num?)?.toDouble() ?? m.cost,
|
||||
tokens: data['tokens'] == null
|
||||
? m.tokens
|
||||
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>)));
|
||||
}
|
||||
break;
|
||||
case 'session.text.started':
|
||||
case 'session.text.delta':
|
||||
case 'session.text.ended':
|
||||
if (mid != null) {
|
||||
_applyDelta(mid, (data['ordinal'] as num?)?.toInt() ?? 0, 'text', type, data);
|
||||
}
|
||||
break;
|
||||
case 'session.reasoning.started':
|
||||
case 'session.reasoning.delta':
|
||||
case 'session.reasoning.ended':
|
||||
if (mid != null) {
|
||||
_applyDelta(mid, (data['ordinal'] as num?)?.toInt() ?? 0, 'reasoning', type, data);
|
||||
}
|
||||
break;
|
||||
case 'session.tool.input.started':
|
||||
case 'session.tool.input.ended':
|
||||
case 'session.tool.called':
|
||||
case 'session.tool.success':
|
||||
case 'session.tool.failed':
|
||||
case 'session.tool.progress':
|
||||
if (mid != null) _applyTool(mid, type, data);
|
||||
break;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _ensureAssistant(String id, int created) {
|
||||
if (byId.containsKey(id)) return;
|
||||
msgs.add(Message(id: id, type: 'assistant', created: created));
|
||||
_reindex();
|
||||
}
|
||||
|
||||
void _applyDelta(String mid, int ordinal, String kind, String type, Map<String, dynamic> data) {
|
||||
_patch(mid, (m) {
|
||||
final content = [...m.content];
|
||||
final slots = kind == 'text' ? textSlots : reasoningSlots;
|
||||
final byOrdinal = slots.putIfAbsent(mid, () => {});
|
||||
int idx;
|
||||
if (byOrdinal.containsKey(ordinal) && byOrdinal[ordinal]! < content.length) {
|
||||
idx = byOrdinal[ordinal]!;
|
||||
} else {
|
||||
content.add(ContentPart(type: kind));
|
||||
idx = content.length - 1;
|
||||
byOrdinal[ordinal] = idx;
|
||||
}
|
||||
final prev = content[idx];
|
||||
if (type.endsWith('.started')) {
|
||||
content[idx] = ContentPart(type: kind);
|
||||
} else if (type.endsWith('.delta')) {
|
||||
content[idx] = ContentPart(type: kind, text: prev.text + (data['delta'] as String? ?? ''));
|
||||
} else if (type.endsWith('.ended')) {
|
||||
content[idx] = ContentPart(type: kind, text: data['text'] as String? ?? prev.text);
|
||||
}
|
||||
return Message(
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
created: m.created,
|
||||
completed: m.completed,
|
||||
agent: m.agent,
|
||||
model: m.model,
|
||||
content: content,
|
||||
text: m.text,
|
||||
files: m.files,
|
||||
finish: m.finish,
|
||||
cost: m.cost,
|
||||
tokens: m.tokens);
|
||||
});
|
||||
}
|
||||
|
||||
void _applyTool(String mid, String type, Map<String, dynamic> data) {
|
||||
final callId = data['id'] as String?;
|
||||
if (callId == null) return;
|
||||
_patch(mid, (m) {
|
||||
final content = [...m.content];
|
||||
var part = _findToolPart(content, callId);
|
||||
final st = part.state ?? ToolState();
|
||||
switch (type) {
|
||||
case 'session.tool.called':
|
||||
st.status = 'running';
|
||||
st.input = data['input'] as Map<String, dynamic>? ?? st.input;
|
||||
break;
|
||||
case 'session.tool.input.started':
|
||||
case 'session.tool.input.ended':
|
||||
st.status = 'streaming';
|
||||
break;
|
||||
case 'session.tool.progress':
|
||||
st.metadata = data['metadata'] as Map<String, dynamic>?;
|
||||
break;
|
||||
case 'session.tool.success':
|
||||
st.status = 'completed';
|
||||
st.input = data['input'] as Map<String, dynamic>? ?? st.input;
|
||||
st.content = (data['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
st.content;
|
||||
st.metadata = data['metadata'] as Map<String, dynamic>?;
|
||||
st.error = null;
|
||||
break;
|
||||
case 'session.tool.failed':
|
||||
st.status = 'error';
|
||||
st.input = data['input'] as Map<String, dynamic>? ?? st.input;
|
||||
st.content = (data['content'] as List?)
|
||||
?.map((e) => ContentPart.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
st.content;
|
||||
st.metadata = data['metadata'] as Map<String, dynamic>?;
|
||||
st.error = data['error'] == null ? null : data['error'].toString();
|
||||
break;
|
||||
}
|
||||
part = ContentPart(type: 'tool', id: callId, name: part.name, state: st);
|
||||
for (var i = 0; i < content.length; i++) {
|
||||
if (content[i].id == callId || (content[i].id == null && content[i].type == 'tool')) {
|
||||
content[i] = part;
|
||||
return Message(
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
created: m.created,
|
||||
completed: m.completed,
|
||||
agent: m.agent,
|
||||
model: m.model,
|
||||
content: content,
|
||||
text: m.text,
|
||||
files: m.files,
|
||||
finish: m.finish,
|
||||
cost: m.cost,
|
||||
tokens: m.tokens);
|
||||
}
|
||||
}
|
||||
content.add(part);
|
||||
return Message(
|
||||
id: m.id,
|
||||
type: m.type,
|
||||
created: m.created,
|
||||
completed: m.completed,
|
||||
agent: m.agent,
|
||||
model: m.model,
|
||||
content: content,
|
||||
text: m.text,
|
||||
files: m.files,
|
||||
finish: m.finish,
|
||||
cost: m.cost,
|
||||
tokens: m.tokens);
|
||||
});
|
||||
}
|
||||
|
||||
ContentPart _findToolPart(List<ContentPart> content, String callId) {
|
||||
for (final p in content) {
|
||||
if (p.type == 'tool' && p.id == callId) return p;
|
||||
}
|
||||
for (final p in content) {
|
||||
if (p.type == 'tool' && p.id == null) {
|
||||
return ContentPart(type: 'tool', id: callId, name: p.name, state: p.state);
|
||||
}
|
||||
}
|
||||
return ContentPart(type: 'tool', id: callId, state: ToolState());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ usage
|
||||
|
||||
(int, int, int, double, bool, double) usageReading() {
|
||||
Message? last;
|
||||
for (var i = msgs.length - 1; i >= 0; i--) {
|
||||
if (msgs[i].type == 'assistant' && msgs[i].tokens != null) {
|
||||
last = msgs[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (last == null) return (0, 0, 0, 0, false, 0);
|
||||
ModelRef? model = last.model;
|
||||
if (model == null) {
|
||||
for (var i = msgs.length - 1; i >= 0 && model == null; i--) {
|
||||
model = msgs[i].model;
|
||||
}
|
||||
}
|
||||
if (model == null) return (0, 0, 0, 0, false, 0);
|
||||
final used = last.tokens!.used;
|
||||
final lim = app.modelLimits['${model.providerId}/${model.id}'] ??
|
||||
app.modelLimits[model.id] ??
|
||||
(0, 0);
|
||||
final context = lim.$1;
|
||||
var output = lim.$2;
|
||||
if (context <= 0 || used <= 0) return (used, context, output, 0, false, 0);
|
||||
var reserve = output > 32000 ? 32000 : output;
|
||||
final threshold = (context - reserve) < 1 ? 1 : context - reserve;
|
||||
final pct = used / threshold * 100;
|
||||
return (used, context, output, pct, true, 0);
|
||||
}
|
||||
|
||||
double get turnCost {
|
||||
var cost = 0.0;
|
||||
for (var i = msgs.length - 1; i >= 0; i--) {
|
||||
if (msgs[i].type == 'user') break;
|
||||
cost += msgs[i].cost;
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Persistence: saved servers in SharedPreferences, device tokens in the
|
||||
// platform's secure storage (Android Keystore).
|
||||
library;
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class Connection {
|
||||
final String id;
|
||||
final String label;
|
||||
final String url;
|
||||
final String proxy;
|
||||
final bool insecure;
|
||||
final String fingerprint;
|
||||
final int lastUsedAt;
|
||||
Connection({
|
||||
required this.id,
|
||||
required this.label,
|
||||
required this.url,
|
||||
this.proxy = '',
|
||||
this.insecure = false,
|
||||
this.fingerprint = '',
|
||||
this.lastUsedAt = 0,
|
||||
});
|
||||
|
||||
factory Connection.fromJson(Map<String, dynamic> j) => Connection(
|
||||
id: j['id'] as String? ?? '',
|
||||
label: j['label'] as String? ?? '',
|
||||
url: j['url'] as String? ?? '',
|
||||
proxy: j['proxy'] as String? ?? '',
|
||||
insecure: j['insecure'] as bool? ?? false,
|
||||
fingerprint: j['fingerprint'] as String? ?? '',
|
||||
lastUsedAt: (j['lastUsedAt'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'label': label,
|
||||
'url': url,
|
||||
'proxy': proxy,
|
||||
'insecure': insecure,
|
||||
'fingerprint': fingerprint,
|
||||
'lastUsedAt': lastUsedAt,
|
||||
};
|
||||
|
||||
Connection copyWith({
|
||||
String? label,
|
||||
String? url,
|
||||
String? proxy,
|
||||
bool? insecure,
|
||||
String? fingerprint,
|
||||
int? lastUsedAt,
|
||||
}) =>
|
||||
Connection(
|
||||
id: id,
|
||||
label: label ?? this.label,
|
||||
url: url ?? this.url,
|
||||
proxy: proxy ?? this.proxy,
|
||||
insecure: insecure ?? this.insecure,
|
||||
fingerprint: fingerprint ?? this.fingerprint,
|
||||
lastUsedAt: lastUsedAt ?? this.lastUsedAt,
|
||||
);
|
||||
}
|
||||
|
||||
class Storage {
|
||||
static const _connsKey = 'openchamber.connections';
|
||||
static const _installKey = 'openchamber.installId';
|
||||
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
|
||||
final _secure = const FlutterSecureStorage();
|
||||
|
||||
Future<List<Connection>> connections() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_connsKey);
|
||||
if (raw == null || raw.isEmpty) return [];
|
||||
try {
|
||||
final list = jsonDecode(raw) as List;
|
||||
final out = list
|
||||
.map((e) => Connection.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
out.sort((a, b) => b.lastUsedAt.compareTo(a.lastUsedAt));
|
||||
return out;
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> saveConnections(List<Connection> list) async {
|
||||
final sorted = [...list]..sort((a, b) => b.lastUsedAt.compareTo(a.lastUsedAt));
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
|
||||
}
|
||||
|
||||
Future<String> installId() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
var id = prefs.getString(_installKey);
|
||||
if (id == null || id.isEmpty) {
|
||||
id = _newId();
|
||||
await prefs.setString(_installKey, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
Future<String?> loadToken(String connectionId) async {
|
||||
return _secure.read(key: _tokenKey(connectionId));
|
||||
}
|
||||
|
||||
Future<void> saveToken(String connectionId, String token) async {
|
||||
await _secure.write(key: _tokenKey(connectionId), value: token);
|
||||
}
|
||||
|
||||
Future<void> clearToken(String connectionId) async {
|
||||
await _secure.delete(key: _tokenKey(connectionId));
|
||||
}
|
||||
|
||||
String _tokenKey(String id) {
|
||||
final digest = _sha1(id);
|
||||
return 'openchamber.token.$digest';
|
||||
}
|
||||
|
||||
static String _newId() =>
|
||||
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}';
|
||||
|
||||
static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff;
|
||||
}
|
||||
|
||||
String _sha1(String s) {
|
||||
// A small, dependency-free FNV-ish key is fine for a storage key: it only
|
||||
// names the secret, never secures it.
|
||||
var h = 0x811c9dc5;
|
||||
for (final c in s.codeUnits) {
|
||||
h ^= c;
|
||||
h = (h * 0x01000193) & 0xffffffff;
|
||||
}
|
||||
return h.toRadixString(16).padLeft(8, '0');
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The composer's context usage ring, colored by the official thresholds.
|
||||
class UsageRing extends StatelessWidget {
|
||||
final double pct; // 0..100
|
||||
final double size;
|
||||
final Color accent;
|
||||
const UsageRing({super.key, required this.pct, this.size = 18, required this.accent});
|
||||
|
||||
Color get _color {
|
||||
if (pct >= 90) return Colors.red.shade600;
|
||||
if (pct >= 75) return Colors.orange.shade700;
|
||||
return Colors.green.shade600;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
width: size,
|
||||
height: size,
|
||||
child: CustomPaint(
|
||||
painter: _RingPainter(pct: pct.clamp(0, 100), color: _color, bg: accent.withValues(alpha: 0.2)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RingPainter extends CustomPainter {
|
||||
final double pct;
|
||||
final Color color;
|
||||
final Color bg;
|
||||
_RingPainter({required this.pct, required this.color, required this.bg});
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final stroke = size.width * 0.14;
|
||||
final rect = Offset.zero & size;
|
||||
final paint = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = stroke
|
||||
..color = bg;
|
||||
canvas.drawArc(rect.deflate(stroke / 2), 0, 3.14159 * 2, false, paint);
|
||||
final sweep = 3.14159 * 2 * (pct / 100);
|
||||
final fg = Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = stroke
|
||||
..strokeCap = StrokeCap.round
|
||||
..color = color;
|
||||
canvas.drawArc(rect.deflate(stroke / 2), -3.14159 / 2, sweep, false, fg);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_RingPainter old) =>
|
||||
old.pct != pct || old.color != color || old.bg != bg;
|
||||
}
|
||||
Reference in new issue
Block a user