Files
openchamber-android-native/lib/state.dart
T

868 lines
25 KiB
Dart
Raw Normal View History

2026-11-18 19:08:06 +08:00
// 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;
}
}