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';
|
2026-11-18 22:18:45 +08:00
|
|
|
import 'dart:io';
|
2026-11-18 19:08:06 +08:00
|
|
|
|
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
|
|
|
|
|
|
import 'api/client.dart';
|
|
|
|
|
import 'api/models.dart';
|
|
|
|
|
import 'storage.dart';
|
2026-11-21 02:49:07 +08:00
|
|
|
import 'terminal_state.dart';
|
2026-11-18 19:08:06 +08:00
|
|
|
|
|
|
|
|
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',
|
2026-11-21 18:32:57 +08:00
|
|
|
'session.inbox.enqueued',
|
|
|
|
|
'session.inbox.delivered',
|
|
|
|
|
'session.inbox.cancelled',
|
|
|
|
|
'session.inbox.delivery.changed',
|
2026-11-18 19:08:06 +08:00
|
|
|
'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',
|
2026-11-20 12:26:15 +08:00
|
|
|
'session.compaction.started',
|
|
|
|
|
'session.compaction.delta',
|
|
|
|
|
'session.compaction.ended',
|
|
|
|
|
'session.compaction.failed',
|
2026-11-21 01:16:10 +08:00
|
|
|
'form.created',
|
|
|
|
|
'form.replied',
|
|
|
|
|
'form.cancelled',
|
2026-11-18 19:08:06 +08:00
|
|
|
'permission.asked',
|
|
|
|
|
'permission.replied',
|
|
|
|
|
];
|
|
|
|
|
|
2026-11-21 14:29:52 +08:00
|
|
|
/// A new session the user started but has not sent yet. Nothing exists on the
|
|
|
|
|
/// server until the first message creates the session.
|
|
|
|
|
class SessionDraft {
|
|
|
|
|
String directory;
|
|
|
|
|
ModelRef? model;
|
|
|
|
|
String agent;
|
|
|
|
|
String text = '';
|
|
|
|
|
int attachments = 0;
|
|
|
|
|
String? error;
|
|
|
|
|
|
|
|
|
|
SessionDraft({required this.directory, this.model, this.agent = ''});
|
|
|
|
|
|
|
|
|
|
bool get isEmpty => text.trim().isEmpty && attachments == 0;
|
|
|
|
|
|
|
|
|
|
String get firstLine {
|
|
|
|
|
for (final line in text.split('\n')) {
|
|
|
|
|
if (line.trim().isNotEmpty) return line.trim();
|
|
|
|
|
}
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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;
|
|
|
|
|
|
2026-11-21 14:29:52 +08:00
|
|
|
/// Projects the server knows, for the new-session picker and the sidebar's
|
|
|
|
|
/// group headers.
|
|
|
|
|
List<ProjectInfo> projects = [];
|
|
|
|
|
|
|
|
|
|
/// The unsent new-session draft, kept in memory. Null when there is none.
|
|
|
|
|
SessionDraft? draft;
|
|
|
|
|
bool sendingDraft = false;
|
|
|
|
|
|
|
|
|
|
/// Whether the shell is showing the draft. A draft can exist while another
|
|
|
|
|
/// session is open (its row waits in the sidebar).
|
|
|
|
|
bool draftOpen = false;
|
|
|
|
|
|
|
|
|
|
/// Archived sessions, fetched only when the sidebar asks for them.
|
|
|
|
|
List<Session> archivedSessions = [];
|
|
|
|
|
bool archivedLoading = false;
|
|
|
|
|
bool archivedLoaded = false;
|
|
|
|
|
|
|
|
|
|
/// Where the next page of the session list starts.
|
|
|
|
|
String? _sessionsNext;
|
|
|
|
|
bool loadingMoreSessions = false;
|
|
|
|
|
|
2026-11-21 02:49:07 +08:00
|
|
|
/// Terminals by workspace directory: switching sessions or tabs keeps the
|
|
|
|
|
/// shell alive, and each directory gets its own.
|
|
|
|
|
final Map<String, TerminalSessionState> terminals = {};
|
|
|
|
|
|
|
|
|
|
TerminalSessionState terminalFor(String directory) => terminals.putIfAbsent(
|
|
|
|
|
directory, () => TerminalSessionState(this, directory));
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
/// 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;
|
2026-11-18 22:18:45 +08:00
|
|
|
error = friendlyConnectError(e);
|
2026-11-18 19:08:06 +08:00
|
|
|
if (!silent) {
|
|
|
|
|
// Surface in the form: the UI reads error itself.
|
2026-11-18 22:18:45 +08:00
|
|
|
_lastError = error;
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 22:18:45 +08:00
|
|
|
/// A short, actionable message for a failed connect.
|
|
|
|
|
String friendlyConnectError(Object e) {
|
|
|
|
|
if (e is ApiError) return e.message;
|
|
|
|
|
if (e is ArgumentError) return e.message?.toString() ?? e.toString();
|
|
|
|
|
if (e is TimeoutException) return '连接超时:检查服务器与代理地址';
|
|
|
|
|
final s = e.toString();
|
|
|
|
|
if (e is SocketException) {
|
|
|
|
|
if (s.contains('Connection refused')) {
|
|
|
|
|
return '连接被拒绝:服务器或代理未启动,或端口不对';
|
|
|
|
|
}
|
|
|
|
|
if (s.contains('Failed host lookup') || s.contains('nodename nor servname')) {
|
|
|
|
|
return '无法解析地址:检查服务器或代理主机名';
|
|
|
|
|
}
|
|
|
|
|
if (s.contains('Network is unreachable')) return '网络不可达';
|
|
|
|
|
if (s.contains('Connection closed') || s.contains('reset by peer')) {
|
|
|
|
|
return '连接被断开:检查代理是否可用';
|
|
|
|
|
}
|
|
|
|
|
return '网络错误:$s';
|
|
|
|
|
}
|
|
|
|
|
return s;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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();
|
2026-11-21 14:29:52 +08:00
|
|
|
refreshProjects();
|
2026-11-18 19:08:06 +08:00
|
|
|
refreshActive();
|
|
|
|
|
refreshPerms();
|
|
|
|
|
refreshModels();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> disconnect() async {
|
2026-11-21 02:49:07 +08:00
|
|
|
for (final terminal in terminals.values) {
|
|
|
|
|
// Closing the shell on the server is right when the connection itself
|
|
|
|
|
// goes away; a panel close only detaches.
|
|
|
|
|
await terminal.closeSession();
|
|
|
|
|
terminal.dispose();
|
|
|
|
|
}
|
|
|
|
|
terminals.clear();
|
2026-11-18 19:08:06 +08:00
|
|
|
client?.close();
|
|
|
|
|
client = null;
|
|
|
|
|
conn = null;
|
|
|
|
|
chat = null;
|
2026-11-21 14:29:52 +08:00
|
|
|
draft = null;
|
|
|
|
|
draftOpen = false;
|
|
|
|
|
sendingDraft = false;
|
2026-11-18 19:08:06 +08:00
|
|
|
sessions = [];
|
2026-11-21 14:29:52 +08:00
|
|
|
projects = [];
|
|
|
|
|
archivedSessions = [];
|
|
|
|
|
archivedLoaded = false;
|
|
|
|
|
_sessionsNext = null;
|
2026-11-18 19:08:06 +08:00
|
|
|
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 {
|
2026-11-21 14:29:52 +08:00
|
|
|
final page = await cl.listSessions(archived: false);
|
2026-11-18 19:08:06 +08:00
|
|
|
sessions = page.data;
|
2026-11-21 14:29:52 +08:00
|
|
|
_sessionsNext = page.next;
|
2026-11-18 19:08:06 +08:00
|
|
|
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 {
|
2026-11-21 14:29:52 +08:00
|
|
|
final page = await cl.listSessions(search: q, archived: false);
|
2026-11-18 19:08:06 +08:00
|
|
|
sessions = page.data;
|
2026-11-21 14:29:52 +08:00
|
|
|
// Search results are one page; "load more" would append unsearched
|
|
|
|
|
// sessions.
|
|
|
|
|
_sessionsNext = null;
|
2026-11-18 19:08:06 +08:00
|
|
|
sessionsLoading = false;
|
|
|
|
|
} catch (_) {
|
|
|
|
|
sessionsLoading = false;
|
|
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 14:29:52 +08:00
|
|
|
Future<void> refreshProjects() async {
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
projects = await cl.listProjects();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (_) {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Loads the next (older) page of the session list.
|
|
|
|
|
Future<void> loadMoreSessions() async {
|
|
|
|
|
final cl = client;
|
|
|
|
|
final cursor = _sessionsNext;
|
|
|
|
|
if (cl == null || cursor == null || loadingMoreSessions) return;
|
|
|
|
|
loadingMoreSessions = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
|
|
|
|
final page = await cl.listSessions(cursor: cursor, archived: false);
|
|
|
|
|
final known = sessions.map((s) => s.id).toSet();
|
|
|
|
|
sessions = [
|
|
|
|
|
...sessions,
|
|
|
|
|
...page.data.where((s) => !known.contains(s.id)),
|
|
|
|
|
];
|
|
|
|
|
_sessionsNext = page.next;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
} finally {
|
|
|
|
|
loadingMoreSessions = false;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> refreshArchived() async {
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
archivedLoading = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
|
|
|
|
final page = await cl.listSessions(archived: true, limit: 100);
|
|
|
|
|
archivedSessions = page.data;
|
|
|
|
|
archivedLoaded = true;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
} finally {
|
|
|
|
|
archivedLoading = false;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
bool get hasMoreSessions => _sessionsNext != null;
|
|
|
|
|
|
2026-11-21 17:03:22 +08:00
|
|
|
/// Commands and skills of one directory, cached. The chat and the draft
|
|
|
|
|
/// both read this; the client-local `compact` is left out for a session
|
|
|
|
|
/// that does not exist yet.
|
|
|
|
|
final Map<String, List<SlashItem>> _slashCache = {};
|
|
|
|
|
|
|
|
|
|
Future<List<SlashItem>> slashItemsFor(String directory,
|
|
|
|
|
{bool includeLocal = true}) async {
|
|
|
|
|
final key = '${includeLocal ? 1 : 0}:$directory';
|
|
|
|
|
final cached = _slashCache[key];
|
|
|
|
|
if (cached != null) return cached;
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return const [];
|
|
|
|
|
final results = await Future.wait([
|
|
|
|
|
cl.commands(directory: directory),
|
|
|
|
|
cl.skills(directory: directory),
|
|
|
|
|
]);
|
|
|
|
|
const local = [
|
|
|
|
|
SlashItem(
|
|
|
|
|
name: 'compact',
|
|
|
|
|
description: '使用 AI 压缩会话历史以减少上下文大小',
|
|
|
|
|
action: 'compact',
|
|
|
|
|
),
|
|
|
|
|
];
|
|
|
|
|
final localNames = {for (final c in local) c.name};
|
|
|
|
|
final items = [
|
|
|
|
|
if (includeLocal) ...local,
|
|
|
|
|
for (final c in results[0])
|
|
|
|
|
if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name']))
|
|
|
|
|
SlashItem(name: c['name']!, description: c['description'] ?? ''),
|
|
|
|
|
for (final k in results[1])
|
|
|
|
|
if ((k['name'] ?? '').isNotEmpty)
|
|
|
|
|
SlashItem(
|
|
|
|
|
name: k['name']!,
|
|
|
|
|
description: k['description'] ?? '',
|
|
|
|
|
skill: true,
|
|
|
|
|
id: k['id'] ?? '',
|
|
|
|
|
),
|
|
|
|
|
];
|
|
|
|
|
_slashCache[key] = items;
|
|
|
|
|
return items;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The catalog entry for a model reference, when the list has it.
|
|
|
|
|
ModelInfo? modelInfo(ModelRef? ref) {
|
|
|
|
|
if (ref == null) return null;
|
|
|
|
|
for (final model in modelList) {
|
|
|
|
|
if (model.id == ref.id && model.providerId == ref.providerId) {
|
|
|
|
|
return model;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 14:29:52 +08:00
|
|
|
String projectLabelFor(String directory) {
|
|
|
|
|
if (directory.isEmpty) return '';
|
|
|
|
|
for (final project in projects) {
|
|
|
|
|
if (project.canonical == directory) return project.label;
|
|
|
|
|
}
|
|
|
|
|
final trimmed = directory.replaceAll(RegExp(r'/+$'), '');
|
|
|
|
|
final index = trimmed.lastIndexOf('/');
|
|
|
|
|
return index >= 0 ? trimmed.substring(index + 1) : trimmed;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ProjectInfo? projectFor(String directory) {
|
|
|
|
|
for (final project in projects) {
|
|
|
|
|
if (project.canonical == directory) return project;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Pins live in the session's metadata, so every client sees them.
|
|
|
|
|
Future<void> togglePin(Session session) async {
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
final metadata = Map<String, dynamic>.from(session.metadata);
|
|
|
|
|
final openchamber = metadata['openchamber'] is Map
|
|
|
|
|
? Map<String, dynamic>.from(metadata['openchamber'] as Map)
|
|
|
|
|
: <String, dynamic>{};
|
|
|
|
|
if (session.isPinned) {
|
|
|
|
|
openchamber.remove('pinned');
|
|
|
|
|
} else {
|
|
|
|
|
openchamber['pinned'] = {
|
|
|
|
|
'at': DateTime.now().millisecondsSinceEpoch,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
if (openchamber.isEmpty) {
|
|
|
|
|
metadata.remove('openchamber');
|
|
|
|
|
} else {
|
|
|
|
|
metadata['openchamber'] = openchamber;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
await cl.updateSession(session.id, metadata: metadata);
|
|
|
|
|
_patchSession(session.id, (s) => s.copyWith(metadata: metadata));
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> setArchived(Session session, bool archived) async {
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
await cl.updateSession(session.id, archived: archived);
|
|
|
|
|
if (archived) {
|
|
|
|
|
sessions.removeWhere((s) => s.id == session.id);
|
|
|
|
|
if (archivedLoaded) {
|
|
|
|
|
archivedSessions.insert(
|
|
|
|
|
0,
|
|
|
|
|
session.copyWith(
|
|
|
|
|
archived: DateTime.now().millisecondsSinceEpoch));
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
archivedSessions.removeWhere((s) => s.id == session.id);
|
|
|
|
|
final restored = session.copyWith(archived: 0);
|
|
|
|
|
if (!sessions.any((s) => s.id == restored.id)) {
|
|
|
|
|
sessions.insert(0, restored);
|
|
|
|
|
}
|
|
|
|
|
_sortSessions();
|
|
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void _sortSessions() =>
|
|
|
|
|
sessions.sort((a, b) => b.updated.compareTo(a.updated));
|
|
|
|
|
|
|
|
|
|
// ------------------------------------------------------------------ draft
|
|
|
|
|
|
|
|
|
|
/// Opens (or reopens) the single in-memory draft. A non-empty draft wins
|
|
|
|
|
/// over the directory a caller asks for; an empty one takes the directory.
|
|
|
|
|
SessionDraft openDraft({String? directory}) {
|
|
|
|
|
final current = draft;
|
|
|
|
|
if (current != null) {
|
|
|
|
|
if (current.isEmpty &&
|
|
|
|
|
directory != null &&
|
|
|
|
|
directory.isNotEmpty &&
|
|
|
|
|
directory != current.directory) {
|
|
|
|
|
current.directory = directory;
|
|
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return current;
|
|
|
|
|
}
|
|
|
|
|
final fallback = directory ??
|
|
|
|
|
chat?.session.directory ??
|
|
|
|
|
(sessions.isNotEmpty ? sessions.first.directory : '');
|
|
|
|
|
final latest = sessions.isNotEmpty ? sessions.first : null;
|
|
|
|
|
final dir = fallback.isNotEmpty
|
|
|
|
|
? fallback
|
|
|
|
|
: (projects.isNotEmpty ? projects.first.canonical : '');
|
|
|
|
|
final created = SessionDraft(
|
|
|
|
|
directory: dir,
|
|
|
|
|
model: chat?.selectedModel ?? latest?.model,
|
|
|
|
|
agent: (chat != null && chat!.selectedAgent.isNotEmpty)
|
|
|
|
|
? chat!.selectedAgent
|
|
|
|
|
: (latest?.agent ?? ''),
|
|
|
|
|
);
|
|
|
|
|
draft = created;
|
|
|
|
|
draftOpen = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return created;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Brings the draft back on screen without touching what it holds.
|
|
|
|
|
void showDraft() {
|
|
|
|
|
if (draft == null) return;
|
|
|
|
|
draftOpen = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void discardDraft() {
|
|
|
|
|
if (draft == null) return;
|
|
|
|
|
draft = null;
|
|
|
|
|
draftOpen = false;
|
|
|
|
|
sendingDraft = false;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void updateDraftText(String text) {
|
|
|
|
|
final current = draft;
|
|
|
|
|
if (current == null) return;
|
|
|
|
|
current.text = text;
|
|
|
|
|
// The sidebar's draft row shows the first line; a rebuild per keystroke is
|
|
|
|
|
// cheap at this size.
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void updateDraftTarget(String directory) {
|
|
|
|
|
final current = draft;
|
|
|
|
|
if (current == null) return;
|
|
|
|
|
current.directory = directory;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void updateDraftModel(ModelRef? model, {String? agent}) {
|
|
|
|
|
final current = draft;
|
|
|
|
|
if (current == null) return;
|
|
|
|
|
if (model != null) current.model = model;
|
|
|
|
|
if (agent != null) current.agent = agent;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// The first send is what creates the session: until then nothing exists on
|
|
|
|
|
/// the server, so an untouched draft never leaves an empty session behind.
|
|
|
|
|
Future<void> sendDraft({
|
|
|
|
|
required String text,
|
|
|
|
|
List<Map<String, String>>? files,
|
|
|
|
|
List<String> images = const [],
|
|
|
|
|
}) async {
|
|
|
|
|
final current = draft;
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (current == null || cl == null || sendingDraft) return;
|
|
|
|
|
current.error = null;
|
|
|
|
|
sendingDraft = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
final Session created;
|
|
|
|
|
try {
|
|
|
|
|
created = await cl.createSession(
|
|
|
|
|
directory: current.directory,
|
|
|
|
|
model: current.model,
|
|
|
|
|
agent: current.agent,
|
|
|
|
|
);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
sendingDraft = false;
|
|
|
|
|
current.error = e is ApiError ? e.message : '$e';
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
draft = null;
|
|
|
|
|
sendingDraft = false;
|
|
|
|
|
if (!sessions.any((s) => s.id == created.id)) {
|
|
|
|
|
sessions.insert(0, created);
|
|
|
|
|
}
|
|
|
|
|
await openChat(created);
|
|
|
|
|
final id = await chat?.send(text: text, files: files);
|
|
|
|
|
if (id != null && id.isNotEmpty && images.isNotEmpty) {
|
|
|
|
|
chat!.imagePaths[id] = images;
|
|
|
|
|
chat!.touch();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 20:18:04 +08:00
|
|
|
StreamSubscription<Map<String, dynamic>>? _events;
|
|
|
|
|
int _streamGen = 0;
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
void _startStream() {
|
|
|
|
|
final cl = client;
|
|
|
|
|
if (cl == null) return;
|
2026-11-19 20:18:04 +08:00
|
|
|
final gen = ++_streamGen;
|
|
|
|
|
_events?.cancel().ignore();
|
2026-11-18 19:08:06 +08:00
|
|
|
Future<void> loop() async {
|
2026-11-19 20:18:04 +08:00
|
|
|
while (client == cl && gen == _streamGen) {
|
|
|
|
|
final done = Completer<void>();
|
|
|
|
|
_events = cl.streamEvents(types: _eventTypes).listen(
|
|
|
|
|
(ev) {
|
2026-11-18 19:08:06 +08:00
|
|
|
if (client != cl) return;
|
2026-11-20 18:25:28 +08:00
|
|
|
// Anything arriving means the stream is back (the server greets
|
|
|
|
|
// every connection with `server.connected`), so the "reconnecting"
|
|
|
|
|
// banner has done its job.
|
|
|
|
|
if (error == '连接中断,正在重连…') error = null;
|
2026-11-18 19:08:06 +08:00
|
|
|
_applyEvent(ev);
|
2026-11-19 20:18:04 +08:00
|
|
|
},
|
|
|
|
|
onError: (Object _) {
|
|
|
|
|
if (!done.isCompleted) done.complete();
|
|
|
|
|
},
|
|
|
|
|
onDone: () {
|
|
|
|
|
if (!done.isCompleted) done.complete();
|
|
|
|
|
},
|
|
|
|
|
cancelOnError: true,
|
|
|
|
|
);
|
|
|
|
|
await done.future;
|
|
|
|
|
if (client != cl || gen != _streamGen) return;
|
2026-11-18 19:08:06 +08:00
|
|
|
error = '连接中断,正在重连…';
|
|
|
|
|
notifyListeners();
|
|
|
|
|
await Future.delayed(const Duration(seconds: 2));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
loop();
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 20:18:04 +08:00
|
|
|
/// Reopens the event stream and refreshes what is on screen. Called when the
|
|
|
|
|
/// app comes back to the foreground: a socket that died while the process
|
|
|
|
|
/// was in the background never reports it.
|
|
|
|
|
Future<void> onResumed() async {
|
|
|
|
|
if (client == null) return;
|
|
|
|
|
_startStream();
|
|
|
|
|
await refreshSessions();
|
2026-11-21 18:32:57 +08:00
|
|
|
if (chat != null) {
|
|
|
|
|
await chat!.reloadTail();
|
|
|
|
|
await chat!.reloadInbox();
|
|
|
|
|
}
|
2026-11-21 02:49:07 +08:00
|
|
|
for (final terminal in terminals.values) {
|
|
|
|
|
await terminal.reconnectIfNeeded();
|
|
|
|
|
}
|
2026-11-19 20:18:04 +08:00
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
void _applyEvent(Map<String, dynamic> ev) {
|
|
|
|
|
final type = ev['type'] as String? ?? '';
|
|
|
|
|
final data = ev['data'] as Map<String, dynamic>? ?? {};
|
|
|
|
|
if (chat != null) {
|
2026-11-21 01:16:10 +08:00
|
|
|
final form = data['form'];
|
|
|
|
|
final sid = data['sessionID'] as String? ??
|
|
|
|
|
(form is Map<String, dynamic>
|
|
|
|
|
? form['sessionID'] as String?
|
|
|
|
|
: null);
|
2026-11-18 19:08:06 +08:00
|
|
|
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;
|
2026-11-21 14:29:52 +08:00
|
|
|
_patchSession(id, (s) => s.copyWith(title: title));
|
2026-11-18 19:08:06 +08:00
|
|
|
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;
|
2026-11-21 14:29:52 +08:00
|
|
|
_patchSession(id, (s) => s.copyWith(model: model));
|
2026-11-18 19:08:06 +08:00
|
|
|
break;
|
|
|
|
|
case 'session.agent.selected':
|
|
|
|
|
final id = data['sessionID'] as String?;
|
|
|
|
|
final agent = data['agent'] as String?;
|
|
|
|
|
if (id == null || agent == null) return;
|
2026-11-21 14:29:52 +08:00
|
|
|
_patchSession(id, (s) => s.copyWith(agent: agent));
|
|
|
|
|
break;
|
|
|
|
|
case 'session.metadata.updated':
|
|
|
|
|
final id = data['sessionID'] as String?;
|
|
|
|
|
final metadata = data['metadata'];
|
|
|
|
|
if (id != null && metadata is Map<String, dynamic>) {
|
|
|
|
|
_patchSession(
|
|
|
|
|
id,
|
|
|
|
|
(s) => s.copyWith(
|
|
|
|
|
metadata: Map<String, dynamic>.from(metadata)));
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
2026-11-18 19:08:06 +08:00
|
|
|
break;
|
|
|
|
|
case 'session.archived':
|
2026-11-21 14:29:52 +08:00
|
|
|
final id = data['sessionID'] as String?;
|
|
|
|
|
if (id != null) {
|
|
|
|
|
final gone = sessions.firstWhere((s) => s.id == id,
|
|
|
|
|
orElse: () => Session(id: id, title: ''));
|
|
|
|
|
sessions.removeWhere((s) => s.id == id);
|
|
|
|
|
if (archivedLoaded && gone.title.isNotEmpty) {
|
|
|
|
|
archivedSessions.insert(
|
|
|
|
|
0,
|
|
|
|
|
gone.copyWith(
|
|
|
|
|
archived: DateTime.now().millisecondsSinceEpoch));
|
|
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
break;
|
2026-11-18 19:08:06 +08:00
|
|
|
case 'session.deleted':
|
|
|
|
|
final id = data['sessionID'] as String?;
|
2026-11-21 14:29:52 +08:00
|
|
|
if (id != null) {
|
|
|
|
|
sessions.removeWhere((s) => s.id == id);
|
|
|
|
|
archivedSessions.removeWhere((s) => s.id == id);
|
|
|
|
|
}
|
2026-11-18 19:08:06 +08:00
|
|
|
break;
|
|
|
|
|
case 'session.unarchived':
|
2026-11-21 14:29:52 +08:00
|
|
|
refreshSessions();
|
|
|
|
|
if (archivedLoaded) refreshArchived();
|
|
|
|
|
return;
|
2026-11-18 19:08:06 +08:00
|
|
|
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 {
|
2026-11-21 14:29:52 +08:00
|
|
|
draftOpen = false;
|
2026-11-18 19:08:06 +08:00
|
|
|
chat = ChatState(this, s);
|
2026-11-21 01:16:10 +08:00
|
|
|
// The shell shows the new session at once; its messages follow.
|
|
|
|
|
notifyListeners();
|
2026-11-18 19:08:06 +08:00
|
|
|
await chat!.load();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void closeChat() {
|
|
|
|
|
chat = null;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
void dispose() {
|
|
|
|
|
super.dispose();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
// The open chat.
|
|
|
|
|
// ---------------------------------------------------------------------------
|
|
|
|
|
|
2026-11-20 02:20:35 +08:00
|
|
|
/// One entry of the composer's `/` palette: a command registered for the
|
|
|
|
|
/// directory, or a skill opencode can attach to a prompt.
|
|
|
|
|
class SlashItem {
|
|
|
|
|
final String name;
|
|
|
|
|
final String description;
|
|
|
|
|
final bool skill;
|
|
|
|
|
final String id;
|
2026-11-20 12:26:15 +08:00
|
|
|
|
|
|
|
|
/// A command the client runs itself (`compact`), rather than a prompt.
|
|
|
|
|
final String action;
|
2026-11-20 02:20:35 +08:00
|
|
|
const SlashItem({
|
|
|
|
|
required this.name,
|
|
|
|
|
this.description = '',
|
|
|
|
|
this.skill = false,
|
|
|
|
|
this.id = '',
|
2026-11-20 12:26:15 +08:00
|
|
|
this.action = '',
|
2026-11-20 02:20:35 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
/// Commands whose description shows an argument form (`[commit|branch|pr]`)
|
|
|
|
|
/// expect one; the palette completes those and runs the rest outright.
|
|
|
|
|
bool get takesArgs => description.contains('[');
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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 = {};
|
2026-11-19 12:34:25 +08:00
|
|
|
ModelRef? selectedModel;
|
|
|
|
|
String selectedAgent;
|
2026-11-18 19:08:06 +08:00
|
|
|
|
2026-11-21 01:16:10 +08:00
|
|
|
/// The agent's pending questions (native forms), oldest first.
|
|
|
|
|
List<FormInfo> forms = [];
|
|
|
|
|
|
2026-11-21 18:32:57 +08:00
|
|
|
/// Prompts waiting in the server's inbox (queued, or steering the running
|
|
|
|
|
/// turn), oldest first. They enter the transcript only when delivered.
|
|
|
|
|
List<InboxItem> inbox = [];
|
|
|
|
|
|
2026-11-20 02:20:35 +08:00
|
|
|
/// `/` palette contents, loaded once per open chat.
|
|
|
|
|
List<SlashItem> slashItems = [];
|
|
|
|
|
bool slashLoading = false;
|
|
|
|
|
bool _slashLoaded = false;
|
|
|
|
|
|
2026-11-19 12:34:25 +08:00
|
|
|
ChatState(this.app, this.session)
|
|
|
|
|
: selectedModel = session.model,
|
|
|
|
|
selectedAgent = session.agent;
|
2026-11-18 19:08:06 +08:00
|
|
|
|
|
|
|
|
/// 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);
|
2026-11-19 20:18:04 +08:00
|
|
|
// A desc page's `next` cursor points at the older side. The server also
|
|
|
|
|
// hands out a cursor for a page that already holds everything, so a
|
|
|
|
|
// short page means there is nothing older.
|
2026-11-19 12:34:25 +08:00
|
|
|
olderCursor = page.next;
|
2026-11-19 20:18:04 +08:00
|
|
|
hasMore = page.next != null && page.data.length >= _pageSize;
|
2026-11-18 19:08:06 +08:00
|
|
|
loading = false;
|
2026-11-20 02:20:35 +08:00
|
|
|
error = null;
|
2026-11-18 19:08:06 +08:00
|
|
|
notifyListeners();
|
|
|
|
|
await reloadTail();
|
2026-11-21 01:16:10 +08:00
|
|
|
await reloadForms();
|
2026-11-21 18:32:57 +08:00
|
|
|
await reloadInbox();
|
2026-11-18 19:08:06 +08:00
|
|
|
} catch (e) {
|
|
|
|
|
loading = false;
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-20 02:20:35 +08:00
|
|
|
/// Loads the directory's commands and skills for the `/` palette. Called
|
|
|
|
|
/// when the palette first opens and before a `/name` send, so a typed
|
|
|
|
|
/// command never falls through to the model as plain text.
|
|
|
|
|
Future<void> ensureSlash() async {
|
|
|
|
|
if (_slashLoaded || slashLoading) return;
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
slashLoading = true;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
2026-11-21 17:03:22 +08:00
|
|
|
slashItems = await app.slashItemsFor(dir);
|
2026-11-20 02:20:35 +08:00
|
|
|
_slashLoaded = true;
|
|
|
|
|
} catch (_) {
|
|
|
|
|
// Keep the palette empty; a send falls back to a plain prompt.
|
|
|
|
|
}
|
|
|
|
|
slashLoading = false;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
SlashItem? slashFor(String text) {
|
|
|
|
|
final m = RegExp(r'^/([^\s/]+)').firstMatch(text.trimLeft());
|
|
|
|
|
if (m == null) return null;
|
|
|
|
|
final name = m.group(1)!;
|
|
|
|
|
for (final item in slashItems) {
|
|
|
|
|
if (item.name == name) return item;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-20 09:18:04 +08:00
|
|
|
/// A page keeps large tool outputs out (`x-openchamber-part-shells`); the
|
|
|
|
|
/// message itself still carries them. Such a part reads as an empty text.
|
|
|
|
|
static bool _shelledPart(ContentPart p) =>
|
|
|
|
|
p.type == 'tool' &&
|
|
|
|
|
(p.state?.metadata?.containsKey('openchamberContentShell') ?? false);
|
|
|
|
|
|
|
|
|
|
/// The server's copy of a message, except that a tool output already loaded
|
|
|
|
|
/// in full is kept: taking the shell back would turn the step's output into
|
|
|
|
|
/// "无输出" again on the next tail refresh.
|
|
|
|
|
static Message _keepLoadedOutput(Message local, Message server) {
|
|
|
|
|
if (!server.content.any(_shelledPart)) return server;
|
|
|
|
|
final parts = <ContentPart>[];
|
|
|
|
|
for (var i = 0; i < server.content.length; i++) {
|
|
|
|
|
final s = server.content[i];
|
|
|
|
|
final l = i < local.content.length ? local.content[i] : null;
|
|
|
|
|
final loaded = l != null &&
|
|
|
|
|
l.type == 'tool' &&
|
|
|
|
|
l.id == s.id &&
|
|
|
|
|
(l.state?.content.any((c) => c.text.isNotEmpty) ?? false);
|
|
|
|
|
parts.add(_shelledPart(s) && loaded ? l : s);
|
|
|
|
|
}
|
|
|
|
|
return Message(
|
|
|
|
|
id: server.id,
|
|
|
|
|
type: server.type,
|
|
|
|
|
created: server.created,
|
|
|
|
|
completed: server.completed,
|
|
|
|
|
agent: server.agent,
|
|
|
|
|
model: server.model,
|
|
|
|
|
content: parts,
|
|
|
|
|
text: server.text,
|
|
|
|
|
files: server.files,
|
|
|
|
|
finish: server.finish,
|
|
|
|
|
cost: server.cost,
|
|
|
|
|
tokens: server.tokens,
|
|
|
|
|
error: server.error,
|
|
|
|
|
status: server.status,
|
|
|
|
|
reason: server.reason,
|
2026-11-20 12:26:15 +08:00
|
|
|
summary: server.summary,
|
2026-11-20 09:18:04 +08:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 01:16:10 +08:00
|
|
|
/// Fetches the pending forms, which may have been asked while the stream
|
|
|
|
|
/// was down (the events alone would miss them).
|
|
|
|
|
Future<void> reloadForms() async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
forms = await cl.forms(id, directory: dir);
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (_) {}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 18:32:57 +08:00
|
|
|
/// Fetches the prompts waiting in the inbox, which may have been queued by
|
|
|
|
|
/// another client while this one was closed.
|
|
|
|
|
Future<void> reloadInbox() async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
inbox = await cl.inbox(id, directory: dir);
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (_) {}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Takes a waiting prompt out of the inbox and puts its text back into the
|
|
|
|
|
/// composer, as dsh-Go's 撤回 does.
|
|
|
|
|
Future<bool> withdrawInbox(String inboxId) async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return false;
|
|
|
|
|
final item = inbox.where((i) => i.id == inboxId).firstOrNull;
|
|
|
|
|
try {
|
|
|
|
|
await cl.cancelInbox(id, inboxId, directory: dir);
|
|
|
|
|
inbox.removeWhere((i) => i.id == inboxId);
|
|
|
|
|
if (item != null) draft = item.text;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return true;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Switches a waiting prompt between steering the running turn and waiting
|
|
|
|
|
/// for it to end.
|
|
|
|
|
Future<void> changeInboxDelivery(String inboxId, String delivery) async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
await cl.updateInbox(id, inboxId, delivery, directory: dir);
|
|
|
|
|
inbox = [
|
|
|
|
|
for (final i in inbox)
|
|
|
|
|
i.id == inboxId ? i.withDelivery(delivery) : i,
|
|
|
|
|
];
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 01:16:10 +08:00
|
|
|
Future<void> replyForm(FormInfo form, Map<String, Object?> answer) async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
await cl.replyForm(id, form.id, answer, directory: dir);
|
|
|
|
|
forms.removeWhere((f) => f.id == form.id);
|
|
|
|
|
error = null;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> cancelForm(FormInfo form) async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
await cl.cancelForm(id, form.id, directory: dir);
|
|
|
|
|
forms.removeWhere((f) => f.id == form.id);
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 20:18:04 +08:00
|
|
|
/// Refreshes the newest page without dropping the older pages that were
|
|
|
|
|
/// already loaded; the server's copy wins for messages it returns.
|
2026-11-18 19:08:06 +08:00
|
|
|
Future<void> reloadTail() async {
|
|
|
|
|
try {
|
|
|
|
|
final page = await app.client!.listMessages(id, directory: dir);
|
2026-11-19 20:18:04 +08:00
|
|
|
if (msgs.isEmpty) {
|
|
|
|
|
_setMessages(page.data);
|
|
|
|
|
} else {
|
|
|
|
|
final fresh = {for (final m in page.data) m.id: m};
|
|
|
|
|
final merged = <Message>[
|
2026-11-20 09:18:04 +08:00
|
|
|
for (final m in msgs)
|
|
|
|
|
switch (fresh.remove(m.id)) {
|
|
|
|
|
final Message s => _keepLoadedOutput(m, s),
|
|
|
|
|
null => m,
|
|
|
|
|
},
|
2026-11-19 20:18:04 +08:00
|
|
|
for (final m in page.data)
|
|
|
|
|
if (fresh.containsKey(m.id)) m,
|
|
|
|
|
];
|
|
|
|
|
msgs = merged;
|
|
|
|
|
_sortMsgs();
|
|
|
|
|
}
|
2026-11-18 19:08:06 +08:00
|
|
|
notifyListeners();
|
|
|
|
|
} catch (_) {}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-19 20:18:04 +08:00
|
|
|
static const _pageSize = 30;
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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];
|
2026-11-19 12:34:25 +08:00
|
|
|
_sortMsgs();
|
|
|
|
|
olderCursor = page.next;
|
2026-11-19 20:18:04 +08:00
|
|
|
hasMore = page.next != null && page.data.length >= _pageSize;
|
2026-11-18 19:08:06 +08:00
|
|
|
} catch (_) {}
|
|
|
|
|
loadingOlder = false;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void _setMessages(List<Message> list) {
|
|
|
|
|
msgs = list;
|
2026-11-19 12:34:25 +08:00
|
|
|
_sortMsgs();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Oldest first: a page arrives newest-first (order: desc).
|
|
|
|
|
void _sortMsgs() {
|
|
|
|
|
msgs.sort((a, b) {
|
|
|
|
|
if (a.created == b.created) return a.id.compareTo(b.id);
|
|
|
|
|
return a.created.compareTo(b.created);
|
|
|
|
|
});
|
2026-11-18 19:08:06 +08:00
|
|
|
_reindex();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void _reindex() {
|
|
|
|
|
byId = {for (final m in msgs) m.id: m};
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 18:32:57 +08:00
|
|
|
/// Sends [text]. [delivery] is 'steer' (join the running turn at its next
|
|
|
|
|
/// step) or 'queue' (wait for it to end); with none, an idle session starts
|
|
|
|
|
/// a turn. Queue and steer prompts show as pending bubbles until the server
|
|
|
|
|
/// delivers them, so no user message is written here.
|
|
|
|
|
Future<String?> send({String? text,
|
|
|
|
|
List<Map<String, String>>? files,
|
|
|
|
|
String? delivery}) async {
|
2026-11-18 19:08:06 +08:00
|
|
|
final t = (text ?? draft).trim();
|
|
|
|
|
if (t.isEmpty && (files == null || files.isEmpty)) return null;
|
2026-11-20 02:20:35 +08:00
|
|
|
if (t.startsWith('/')) {
|
|
|
|
|
await ensureSlash();
|
|
|
|
|
final item = slashFor(t);
|
|
|
|
|
if (item != null) {
|
|
|
|
|
final args =
|
|
|
|
|
(RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim();
|
|
|
|
|
draft = '';
|
2026-11-20 12:26:15 +08:00
|
|
|
if (item.action == 'compact') {
|
|
|
|
|
try {
|
|
|
|
|
final cid = await app.client!.compact(this.id, directory: dir);
|
|
|
|
|
error = null;
|
|
|
|
|
if (cid != null && byId[cid] == null) {
|
|
|
|
|
msgs.add(Message(
|
|
|
|
|
id: cid,
|
|
|
|
|
type: 'compaction',
|
|
|
|
|
status: 'running',
|
|
|
|
|
reason: 'manual',
|
|
|
|
|
created: DateTime.now().millisecondsSinceEpoch,
|
|
|
|
|
));
|
|
|
|
|
_sortMsgs();
|
|
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
await reloadTail();
|
|
|
|
|
return '';
|
|
|
|
|
} catch (e) {
|
|
|
|
|
draft = t;
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-20 02:20:35 +08:00
|
|
|
if (!item.skill) {
|
|
|
|
|
// A command is expanded by the server, which also writes the user
|
|
|
|
|
// message; there is no id to show optimistically.
|
|
|
|
|
try {
|
|
|
|
|
await app.client!.command(this.id,
|
|
|
|
|
name: item.name, text: args, directory: dir, files: files);
|
|
|
|
|
error = null;
|
|
|
|
|
await reloadTail();
|
|
|
|
|
return '';
|
|
|
|
|
} catch (e) {
|
|
|
|
|
draft = t;
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-21 18:32:57 +08:00
|
|
|
// A skill can be queued like any prompt.
|
|
|
|
|
if (delivery != null) {
|
|
|
|
|
return _sendToInbox(t, files, delivery, skillIds: [item.id]);
|
|
|
|
|
}
|
2026-11-20 02:20:35 +08:00
|
|
|
final id = _newMsgId();
|
|
|
|
|
msgs.add(Message(
|
|
|
|
|
id: id,
|
|
|
|
|
type: 'user',
|
|
|
|
|
text: t,
|
|
|
|
|
created: DateTime.now().millisecondsSinceEpoch,
|
|
|
|
|
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
|
|
|
|
|
));
|
|
|
|
|
_sortMsgs();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
|
|
|
|
// The skill is attached by id; the text still names it, as the
|
|
|
|
|
// official composer sends it.
|
|
|
|
|
await app.client!.prompt(this.id,
|
|
|
|
|
text: t, messageId: id, directory: dir, files: files,
|
|
|
|
|
skillIds: [item.id]);
|
|
|
|
|
error = null;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return id;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
msgs.removeWhere((m) => m.id == id);
|
|
|
|
|
_reindex();
|
|
|
|
|
draft = t;
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-21 18:32:57 +08:00
|
|
|
if (delivery != null) {
|
|
|
|
|
return _sendToInbox(t, files, delivery);
|
|
|
|
|
}
|
2026-11-18 19:08:06 +08:00
|
|
|
final id = _newMsgId();
|
|
|
|
|
draft = '';
|
2026-11-20 02:20:35 +08:00
|
|
|
error = null;
|
2026-11-18 19:08:06 +08:00
|
|
|
msgs.add(Message(
|
|
|
|
|
id: id,
|
|
|
|
|
type: 'user',
|
|
|
|
|
text: t,
|
|
|
|
|
created: DateTime.now().millisecondsSinceEpoch,
|
|
|
|
|
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
|
|
|
|
|
));
|
2026-11-19 12:34:25 +08:00
|
|
|
_sortMsgs();
|
2026-11-18 19:08:06 +08:00
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
|
|
|
|
await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files);
|
2026-11-20 02:20:35 +08:00
|
|
|
if (error != null) {
|
|
|
|
|
error = null;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
2026-11-18 19:08:06 +08:00
|
|
|
return id;
|
|
|
|
|
} catch (e) {
|
2026-11-18 20:11:49 +08:00
|
|
|
// The prompt did not reach the server: take the optimistic message back
|
|
|
|
|
// and keep what was typed, so a retry is not a duplicate.
|
|
|
|
|
msgs.removeWhere((m) => m.id == id);
|
|
|
|
|
_reindex();
|
|
|
|
|
draft = t;
|
2026-11-18 19:08:06 +08:00
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
2026-11-18 20:11:49 +08:00
|
|
|
return null;
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 18:32:57 +08:00
|
|
|
/// A prompt for the server's inbox: it shows as a pending bubble at the end
|
|
|
|
|
/// of the chat until the server delivers it into the transcript.
|
|
|
|
|
Future<String?> _sendToInbox(String text,
|
|
|
|
|
List<Map<String, String>>? files, String delivery,
|
|
|
|
|
{List<String>? skillIds}) async {
|
|
|
|
|
final id = _newMsgId();
|
|
|
|
|
final item = InboxItem(
|
|
|
|
|
id: id,
|
|
|
|
|
text: text,
|
|
|
|
|
delivery: delivery,
|
|
|
|
|
created: DateTime.now().millisecondsSinceEpoch,
|
|
|
|
|
files: files
|
|
|
|
|
?.map((f) => FileAttachment(f['name'] ?? '附件', ''))
|
|
|
|
|
.toList() ??
|
|
|
|
|
const [],
|
|
|
|
|
);
|
|
|
|
|
draft = '';
|
|
|
|
|
error = null;
|
|
|
|
|
inbox = [...inbox, item]..sort((a, b) => a.created.compareTo(b.created));
|
|
|
|
|
notifyListeners();
|
|
|
|
|
try {
|
|
|
|
|
final serverId = await app.client!.prompt(this.id,
|
|
|
|
|
text: text,
|
|
|
|
|
messageId: id,
|
|
|
|
|
directory: dir,
|
|
|
|
|
files: files,
|
|
|
|
|
delivery: delivery,
|
|
|
|
|
skillIds: skillIds);
|
|
|
|
|
// The server names the inbox item; keep the bubble keyed to it so the
|
|
|
|
|
// cancel and delivery events find it.
|
|
|
|
|
if (serverId != null && serverId != id) {
|
|
|
|
|
inbox = [
|
|
|
|
|
for (final i in inbox)
|
|
|
|
|
i.id == id
|
|
|
|
|
? InboxItem(
|
|
|
|
|
id: serverId,
|
|
|
|
|
text: i.text,
|
|
|
|
|
delivery: i.delivery,
|
|
|
|
|
created: i.created,
|
|
|
|
|
files: i.files)
|
|
|
|
|
: i,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
error = null;
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return serverId ?? id;
|
|
|
|
|
} catch (e) {
|
|
|
|
|
inbox.removeWhere((i) => i.id == id);
|
|
|
|
|
draft = text;
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
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);
|
2026-11-19 12:34:25 +08:00
|
|
|
selectedModel = model;
|
|
|
|
|
notifyListeners();
|
2026-11-18 19:08:06 +08:00
|
|
|
} catch (e) {
|
|
|
|
|
error = e.toString();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Future<void> switchAgent(String agent) async {
|
|
|
|
|
try {
|
|
|
|
|
await app.client!.switchAgent(id, agent, directory: dir);
|
2026-11-19 12:34:25 +08:00
|
|
|
selectedAgent = agent;
|
|
|
|
|
notifyListeners();
|
2026-11-18 19:08:06 +08:00
|
|
|
} 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;
|
2026-11-20 02:20:35 +08:00
|
|
|
// A command's user message is written by the server, and another
|
|
|
|
|
// client may have sent it: take the tail from the server.
|
|
|
|
|
reloadTail();
|
2026-11-18 19:08:06 +08:00
|
|
|
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
|
2026-11-20 02:20:35 +08:00
|
|
|
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>),
|
|
|
|
|
error: data['error'] == null
|
|
|
|
|
? m.error
|
|
|
|
|
: MessageError.fromJson(data['error'] as Map<String, dynamic>),
|
|
|
|
|
status: m.status,
|
2026-11-20 12:26:15 +08:00
|
|
|
reason: m.reason,
|
|
|
|
|
summary: m.summary));
|
2026-11-20 00:26:09 +08:00
|
|
|
// Live events name a tool only by id, so a streamed step would keep
|
|
|
|
|
// a generic label ("工具") until the session was reopened. The
|
|
|
|
|
// finished message has the names, inputs and attachments.
|
|
|
|
|
_refreshMessage(mid);
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
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;
|
2026-11-21 01:16:10 +08:00
|
|
|
case 'form.created':
|
|
|
|
|
final raw = data['form'];
|
|
|
|
|
if (raw is Map<String, dynamic>) {
|
|
|
|
|
final form = FormInfo.fromJson(raw);
|
|
|
|
|
forms.removeWhere((f) => f.id == form.id);
|
|
|
|
|
forms.add(form);
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case 'form.replied':
|
|
|
|
|
case 'form.cancelled':
|
|
|
|
|
final id = data['id'] as String?;
|
|
|
|
|
if (id != null) {
|
|
|
|
|
forms.removeWhere((f) => f.id == id);
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
break;
|
2026-11-20 12:26:15 +08:00
|
|
|
case 'session.compaction.started':
|
|
|
|
|
final cid = data['inputID'] as String?;
|
|
|
|
|
if (cid != null && byId[cid] == null) {
|
|
|
|
|
msgs.add(Message(
|
|
|
|
|
id: cid,
|
|
|
|
|
type: 'compaction',
|
|
|
|
|
status: 'running',
|
|
|
|
|
reason: data['reason'] as String? ?? '',
|
|
|
|
|
created: created,
|
|
|
|
|
));
|
|
|
|
|
_sortMsgs();
|
|
|
|
|
} else if (cid == null) {
|
|
|
|
|
reloadTail();
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case 'session.compaction.delta':
|
|
|
|
|
final text = data['text'] as String? ?? '';
|
|
|
|
|
if (text.isNotEmpty) {
|
|
|
|
|
for (var i = msgs.length - 1; i >= 0; i--) {
|
|
|
|
|
final m = msgs[i];
|
|
|
|
|
if (m.type == 'compaction' && m.status == 'running') {
|
|
|
|
|
msgs[i] = Message(
|
|
|
|
|
id: m.id,
|
|
|
|
|
type: m.type,
|
|
|
|
|
created: m.created,
|
|
|
|
|
completed: m.completed,
|
|
|
|
|
agent: m.agent,
|
|
|
|
|
model: m.model,
|
|
|
|
|
content: m.content,
|
|
|
|
|
text: m.text,
|
|
|
|
|
files: m.files,
|
|
|
|
|
finish: m.finish,
|
|
|
|
|
cost: m.cost,
|
|
|
|
|
tokens: m.tokens,
|
|
|
|
|
error: m.error,
|
|
|
|
|
status: m.status,
|
|
|
|
|
reason: m.reason,
|
|
|
|
|
summary: m.summary + text,
|
|
|
|
|
);
|
|
|
|
|
_reindex();
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case 'session.compaction.ended':
|
|
|
|
|
case 'session.compaction.failed':
|
|
|
|
|
reloadTail();
|
|
|
|
|
break;
|
2026-11-19 12:34:25 +08:00
|
|
|
case 'session.model.selected':
|
|
|
|
|
final model = data['model'];
|
|
|
|
|
if (model is Map<String, dynamic>) {
|
|
|
|
|
selectedModel = ModelRef.fromJson(model);
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case 'session.agent.selected':
|
|
|
|
|
final agent = data['agent'];
|
|
|
|
|
if (agent is String && agent.isNotEmpty) selectedAgent = agent;
|
|
|
|
|
break;
|
2026-11-21 18:32:57 +08:00
|
|
|
case 'session.inbox.enqueued':
|
|
|
|
|
final iid = data['inboxID'] as String?;
|
|
|
|
|
final raw = data['item'];
|
|
|
|
|
if (iid != null && raw is Map<String, dynamic> && raw['type'] == 'user') {
|
|
|
|
|
final parsed = InboxItem.fromEvent(iid, raw, created);
|
|
|
|
|
inbox = [
|
|
|
|
|
for (final i in inbox)
|
|
|
|
|
if (i.id != iid) i,
|
|
|
|
|
parsed,
|
|
|
|
|
]..sort((a, b) => a.created.compareTo(b.created));
|
|
|
|
|
} else {
|
|
|
|
|
reloadInbox();
|
|
|
|
|
}
|
|
|
|
|
break;
|
|
|
|
|
case 'session.inbox.delivered':
|
|
|
|
|
final iid = data['inboxID'] as String?;
|
|
|
|
|
if (iid != null) inbox.removeWhere((i) => i.id == iid);
|
|
|
|
|
// The message enters the transcript now: take the server's copy.
|
|
|
|
|
reloadTail();
|
|
|
|
|
break;
|
|
|
|
|
case 'session.inbox.cancelled':
|
|
|
|
|
final iid = data['inboxID'] as String?;
|
|
|
|
|
if (iid != null) inbox.removeWhere((i) => i.id == iid);
|
|
|
|
|
break;
|
|
|
|
|
case 'session.inbox.delivery.changed':
|
|
|
|
|
final iid = data['inboxID'] as String?;
|
|
|
|
|
final d = data['delivery'] as String?;
|
|
|
|
|
if (iid != null && d != null) {
|
|
|
|
|
inbox = [
|
|
|
|
|
for (final i in inbox) i.id == iid ? i.withDelivery(d) : i,
|
|
|
|
|
];
|
|
|
|
|
}
|
|
|
|
|
break;
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-20 00:26:09 +08:00
|
|
|
/// Swaps a just-finished streamed message for the server's copy.
|
|
|
|
|
Future<void> _refreshMessage(String mid) async {
|
|
|
|
|
final cl = app.client;
|
|
|
|
|
if (cl == null) return;
|
|
|
|
|
try {
|
|
|
|
|
final m = await cl.getMessage(id, mid, directory: dir);
|
|
|
|
|
final i = msgs.indexWhere((x) => x.id == mid);
|
|
|
|
|
if (i < 0 || app.client != cl) return;
|
|
|
|
|
msgs[i] = m;
|
|
|
|
|
_sortMsgs();
|
|
|
|
|
notifyListeners();
|
|
|
|
|
} catch (_) {}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 19:08:06 +08:00
|
|
|
void _ensureAssistant(String id, int created) {
|
|
|
|
|
if (byId.containsKey(id)) return;
|
|
|
|
|
msgs.add(Message(id: id, type: 'assistant', created: created));
|
2026-11-19 12:34:25 +08:00
|
|
|
_sortMsgs();
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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,
|
2026-11-20 02:20:35 +08:00
|
|
|
tokens: m.tokens,
|
|
|
|
|
error: m.error,
|
|
|
|
|
status: m.status,
|
2026-11-20 12:26:15 +08:00
|
|
|
reason: m.reason,
|
|
|
|
|
summary: m.summary);
|
2026-11-18 19:08:06 +08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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,
|
2026-11-20 02:20:35 +08:00
|
|
|
tokens: m.tokens,
|
|
|
|
|
error: m.error,
|
|
|
|
|
status: m.status,
|
2026-11-20 12:26:15 +08:00
|
|
|
reason: m.reason,
|
|
|
|
|
summary: m.summary);
|
2026-11-18 19:08:06 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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,
|
2026-11-20 02:20:35 +08:00
|
|
|
tokens: m.tokens,
|
|
|
|
|
error: m.error,
|
|
|
|
|
status: m.status,
|
2026-11-20 12:26:15 +08:00
|
|
|
reason: m.reason,
|
|
|
|
|
summary: m.summary);
|
2026-11-18 19:08:06 +08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|