merge(app): bring main into chat-cmd-session; /new /close /rename tests
This commit is contained in:
@@ -8,6 +8,7 @@ import '../../../core/api_gateway.dart';
|
||||
import '../domain/chat_attachment_draft.dart';
|
||||
import '../domain/chat_attachment_picker.dart';
|
||||
import '../domain/chat_attachment_wire.dart';
|
||||
import '../domain/chat_clipboard_paste.dart';
|
||||
import '../domain/chat_commands.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_command_actions.dart';
|
||||
@@ -27,6 +28,9 @@ const String chatAttachLabel = 'Attach file';
|
||||
/// The unknown-command report's two actions, verbatim from the web client.
|
||||
const String chatCommandSendAsMessageLabel = 'Send as message';
|
||||
const String chatCommandCancelLabel = 'Cancel';
|
||||
const String chatCommandNoticeLabel = 'Command';
|
||||
const String chatCommandFailedLabel = 'Command failed';
|
||||
const String chatCommandDismissLabel = 'Dismiss command notice';
|
||||
|
||||
/// Shown while the reply says this prompt waits behind the running turn.
|
||||
const String chatQueuedNotice =
|
||||
@@ -42,14 +46,16 @@ const String chatQueuedNotice =
|
||||
/// above the field: rows are filtered by name prefix, Up/Down move the
|
||||
/// highlight, Enter or a tap completes the highlighted command, Escape closes
|
||||
/// the palette. A slash draft is never handed to the prompt path: `/new`,
|
||||
/// `/close` and `/rename` consume the draft and run through [commands], the
|
||||
/// other recorded commands report that they are not available yet, and text
|
||||
/// naming no recorded command becomes the web client's local no-send report
|
||||
/// with its explicit "Send as message" offer. Picked files are memory-only chips:
|
||||
/// `/close` and `/rename` run through [commands], `/stop` and `/help` run
|
||||
/// locally or through the existing Stop path; text naming no recorded command
|
||||
/// becomes the web client's local no-send report with its explicit "Send as
|
||||
/// message" offer. Picked files are memory-only chips:
|
||||
/// their names are shown with the host's own remove action and the bounded
|
||||
/// draft owns every refusal. Send carries the chips as the landed wire parts,
|
||||
/// keeps them until the prompt is accepted and leaves them in place on a
|
||||
/// refusal; paste is not wired.
|
||||
/// refusal. Pasting files takes the same draft path as the picker; pasting text
|
||||
/// stays with the host field, so its caret, selection and draft behave exactly
|
||||
/// as typing does.
|
||||
class ChatComposerBar extends StatefulWidget {
|
||||
const ChatComposerBar({
|
||||
super.key,
|
||||
@@ -57,6 +63,7 @@ class ChatComposerBar extends StatefulWidget {
|
||||
required this.running,
|
||||
this.picker,
|
||||
this.commands,
|
||||
this.paste,
|
||||
});
|
||||
|
||||
final ChatComposerController composer;
|
||||
@@ -71,6 +78,9 @@ class ChatComposerBar extends StatefulWidget {
|
||||
/// The host picker seam; production uses [hostChatAttachmentPicker].
|
||||
final ChatAttachmentPicker? picker;
|
||||
|
||||
/// The host clipboard-file seam; production uses [hostChatClipboardPaste].
|
||||
final ChatClipboardPaste? paste;
|
||||
|
||||
@override
|
||||
State<ChatComposerBar> createState() => _ChatComposerBarState();
|
||||
}
|
||||
@@ -100,13 +110,18 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
/// command carries [_commandOffer] back for an explicit "Send as message".
|
||||
String? _commandNotice;
|
||||
String? _commandOffer;
|
||||
bool _commandFailed = false;
|
||||
|
||||
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
|
||||
ChatClipboardPaste get _paste => widget.paste ?? hostChatClipboardPaste;
|
||||
|
||||
ChatPasteUnsubscribe? _stopPaste;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.composer.addListener(_syncDraft);
|
||||
_listenForPaste();
|
||||
unawaited(widget.composer.loadDraft());
|
||||
}
|
||||
|
||||
@@ -118,6 +133,42 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
widget.composer.addListener(_syncDraft);
|
||||
_syncDraft();
|
||||
}
|
||||
if (oldWidget.paste != widget.paste) {
|
||||
_stopListeningForPaste();
|
||||
_listenForPaste();
|
||||
}
|
||||
}
|
||||
|
||||
void _listenForPaste() {
|
||||
if (!_paste.isSupported) return;
|
||||
_stopPaste = _paste.listen(
|
||||
onFiles: _onPastedFiles,
|
||||
canAccept: _canAcceptPaste,
|
||||
onError: _onPasteError,
|
||||
);
|
||||
}
|
||||
|
||||
void _stopListeningForPaste() {
|
||||
final stop = _stopPaste;
|
||||
_stopPaste = null;
|
||||
stop?.call();
|
||||
}
|
||||
|
||||
/// A pasted file is taken only while this composer owns the field and no
|
||||
/// prompt is in flight, which is the same window as the attach control. The
|
||||
/// host checks this before it suppresses the paste's default behaviour, so a
|
||||
/// paste elsewhere is never swallowed.
|
||||
bool _canAcceptPaste() =>
|
||||
mounted && _focus.hasFocus && !widget.composer.sending;
|
||||
|
||||
void _onPastedFiles(List<ChatPickedFile> files) {
|
||||
if (!mounted) return;
|
||||
_addFiles(files);
|
||||
}
|
||||
|
||||
void _onPasteError(Object error) {
|
||||
if (!mounted) return;
|
||||
setState(() => _attachmentError = '$error');
|
||||
}
|
||||
|
||||
/// External draft changes (saved-draft load, send clear, refusal restore)
|
||||
@@ -219,36 +270,44 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
|
||||
/// Routes the current slash draft to the command surface. A session command
|
||||
/// consumes the draft (text and persisted copy) and runs; a recorded command
|
||||
/// without an action here reports that it is unavailable and keeps its
|
||||
/// draft; an unknown word takes the web client's report and consumes the
|
||||
/// draft into the offer. None of them posts a prompt.
|
||||
/// Routes a slash draft locally or through the existing Stop controller path.
|
||||
void _runSlashDraft() {
|
||||
final draft = widget.composer.draft;
|
||||
final word = chatCommandWord(draft);
|
||||
if (word == null) return;
|
||||
final command = chatCommandNamed(draft);
|
||||
final actions = widget.commands;
|
||||
if (command != null && actions != null && ChatCommandActions.runs(command)) {
|
||||
final argument = chatCommandArgument(draft);
|
||||
setState(_dismissCommandReport);
|
||||
_text.clear();
|
||||
unawaited(widget.composer.setDraft(''));
|
||||
_focus.requestFocus();
|
||||
unawaited(actions.run(command, argument));
|
||||
return;
|
||||
}
|
||||
if (command != null) {
|
||||
setState(() {
|
||||
_commandOffer = null;
|
||||
_commandNotice = chatCommandUnavailableReport('/${command.name}');
|
||||
});
|
||||
_focus.requestFocus();
|
||||
final argument = chatCommandArgument(draft);
|
||||
if (!command.takesArgument && argument.isNotEmpty) {
|
||||
_consumeCommandDraft();
|
||||
_showCommandNotice(
|
||||
'${command.usage} does not take an argument.',
|
||||
failed: true,
|
||||
);
|
||||
} else if (actions != null && ChatCommandActions.runs(command)) {
|
||||
_consumeCommandDraft();
|
||||
setState(_dismissCommandReport);
|
||||
unawaited(actions.run(command, argument));
|
||||
} else if (command.name == chatCommandStop) {
|
||||
_consumeCommandDraft();
|
||||
if (widget.running) {
|
||||
unawaited(widget.composer.stop());
|
||||
} else {
|
||||
_showCommandNotice('No turn is running in this chat.', failed: true);
|
||||
}
|
||||
} else if (command.name == chatCommandHelp) {
|
||||
_consumeCommandDraft();
|
||||
_showCommandNotice(chatCommandHelpText());
|
||||
} else {
|
||||
_consumeCommandDraft();
|
||||
_showCommandNotice(chatCommandUnavailableReport('/${command.name}'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
final offer = draft.trim();
|
||||
setState(() {
|
||||
_commandFailed = true;
|
||||
_commandOffer = offer;
|
||||
_commandNotice = chatUnknownCommandReport(word);
|
||||
});
|
||||
@@ -257,11 +316,26 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
_focus.requestFocus();
|
||||
}
|
||||
|
||||
void _consumeCommandDraft() {
|
||||
_text.clear();
|
||||
unawaited(widget.composer.setDraft(''));
|
||||
_focus.requestFocus();
|
||||
}
|
||||
|
||||
void _showCommandNotice(String text, {bool failed = false}) {
|
||||
setState(() {
|
||||
_commandFailed = failed;
|
||||
_commandOffer = null;
|
||||
_commandNotice = text;
|
||||
});
|
||||
}
|
||||
|
||||
/// Closes whatever local command report is showing. Callers wrap this in
|
||||
/// [setState]; it owns no rebuild of its own.
|
||||
void _dismissCommandReport() {
|
||||
_commandNotice = null;
|
||||
_commandOffer = null;
|
||||
_commandFailed = false;
|
||||
}
|
||||
|
||||
/// The offer's one explicit route to the agent: take the reported draft back
|
||||
@@ -340,12 +414,19 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
return;
|
||||
}
|
||||
if (!mounted || files == null) return;
|
||||
final picked = files;
|
||||
_addFiles(files);
|
||||
}
|
||||
|
||||
/// Adds each file through the landed attachment draft. A refusal keeps every
|
||||
/// attachment already in the draft and shows the draft's own words; the
|
||||
/// refused file's bytes are never retained. Picking and pasting share this
|
||||
/// path so both apply the same name and 1 MiB decisions.
|
||||
void _addFiles(List<ChatPickedFile> files) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_attachmentError = null;
|
||||
for (final file in picked) {
|
||||
final attachment = file.attachment;
|
||||
final refusal = _attachments.add(attachment);
|
||||
for (final file in files) {
|
||||
final refusal = _attachments.add(file.attachment);
|
||||
if (refusal != null) {
|
||||
_attachmentError = refusal.message;
|
||||
} else {
|
||||
@@ -395,6 +476,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_stopListeningForPaste();
|
||||
widget.composer.removeListener(_syncDraft);
|
||||
_text.dispose();
|
||||
_focus.dispose();
|
||||
@@ -679,12 +761,48 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
|
||||
key: const Key('chat-composer-command-notice'),
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
_commandFailed
|
||||
? chatCommandFailedLabel
|
||||
: chatCommandNoticeLabel,
|
||||
style: TextStyle(
|
||||
color: _commandFailed
|
||||
? (cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error)
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (cupertino)
|
||||
Semantics(
|
||||
button: true,
|
||||
label: chatCommandDismissLabel,
|
||||
child: CupertinoButton(
|
||||
key: const Key('chat-command-dismiss'),
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: () => setState(_dismissCommandReport),
|
||||
child: const Text('Dismiss'),
|
||||
),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
key: const Key('chat-command-dismiss'),
|
||||
tooltip: chatCommandDismissLabel,
|
||||
onPressed: () => setState(_dismissCommandReport),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
_notice(
|
||||
context,
|
||||
cupertino,
|
||||
key: const Key('chat-composer-command-text'),
|
||||
text: _commandNotice!,
|
||||
failed: true,
|
||||
failed: _commandFailed,
|
||||
),
|
||||
if (offer != null)
|
||||
Padding(
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'chat_attachment_picker.dart';
|
||||
import 'chat_clipboard_paste_stub.dart'
|
||||
if (dart.library.js_interop) 'chat_clipboard_paste_web.dart'
|
||||
as impl;
|
||||
|
||||
/// Receives the files one paste carried, in clipboard order.
|
||||
typedef ChatPasteFiles = void Function(List<ChatPickedFile> files);
|
||||
|
||||
/// Whether the composer would take a pasted file right now. The host asks this
|
||||
/// before it suppresses the paste's default behaviour.
|
||||
typedef ChatPasteCanAccept = bool Function();
|
||||
|
||||
/// Reports a clipboard file whose bytes could not be read.
|
||||
typedef ChatPasteFailed = void Function(Object error);
|
||||
|
||||
/// Stops observing paste events for one composer.
|
||||
typedef ChatPasteUnsubscribe = void Function();
|
||||
|
||||
/// Registers [onFiles] for file pastes the composer may take and returns the
|
||||
/// cancellation for that registration.
|
||||
///
|
||||
/// A text-only paste is never reported: it stays with the host field, so caret,
|
||||
/// selection and the draft update exactly as typing does.
|
||||
typedef ChatPasteSubscribe =
|
||||
ChatPasteUnsubscribe Function(
|
||||
ChatPasteFiles onFiles,
|
||||
ChatPasteCanAccept canAccept,
|
||||
ChatPasteFailed onError,
|
||||
);
|
||||
|
||||
/// The clipboard seam for one host.
|
||||
///
|
||||
/// The web host observes the browser's own `paste` event. A paste carrying at
|
||||
/// least one file is consumed ([ChatPasteCanAccept] permitting) and handed to
|
||||
/// the composer as [ChatPickedFile] rows, so the landed attachment draft owns
|
||||
/// every size decision and refusal. A clipboard file the browser recorded
|
||||
/// without a name takes the web client's pasted name. A host without
|
||||
/// clipboard-file paste constructs [ChatClipboardPaste.unsupported] and the
|
||||
/// composer simply keeps its native text behaviour. Tests inject a fake
|
||||
/// [subscribe].
|
||||
class ChatClipboardPaste {
|
||||
const ChatClipboardPaste({required ChatPasteSubscribe this.subscribe})
|
||||
: unsupportedMessage = null;
|
||||
|
||||
const ChatClipboardPaste.unsupported(String message)
|
||||
: subscribe = null,
|
||||
unsupportedMessage = message;
|
||||
|
||||
/// The host's paste listener, or null when this host cannot observe files.
|
||||
final ChatPasteSubscribe? subscribe;
|
||||
|
||||
/// Why this host cannot observe pasted files, when [subscribe] is null.
|
||||
final String? unsupportedMessage;
|
||||
|
||||
bool get isSupported => subscribe != null;
|
||||
|
||||
/// Starts observing the host's paste event. A host without the capability
|
||||
/// throws [UnsupportedError] with [unsupportedMessage].
|
||||
ChatPasteUnsubscribe listen({
|
||||
required ChatPasteFiles onFiles,
|
||||
required ChatPasteCanAccept canAccept,
|
||||
required ChatPasteFailed onError,
|
||||
}) {
|
||||
final subscribe = this.subscribe;
|
||||
if (subscribe == null) throw UnsupportedError(unsupportedMessage!);
|
||||
return subscribe(onFiles, canAccept, onError);
|
||||
}
|
||||
}
|
||||
|
||||
/// The web composer's recorded name for a clipboard file that arrived without
|
||||
/// one: the MIME subtype becomes the extension, with the web client's `jpeg`
|
||||
/// to `jpg` mapping and `bin` fallback.
|
||||
String chatPastedAttachmentName(String mime, int sequence) {
|
||||
final subtype = mime.split('/').last.toLowerCase();
|
||||
final extension = subtype == 'jpeg'
|
||||
? 'jpg'
|
||||
: subtype.replaceAll(RegExp('[^a-z0-9]'), '');
|
||||
return 'pasted-$sequence.${extension.isEmpty ? 'bin' : extension}';
|
||||
}
|
||||
|
||||
/// The clipboard seam for the running host.
|
||||
ChatClipboardPaste get hostChatClipboardPaste => impl.hostChatClipboardPaste;
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'chat_clipboard_paste.dart';
|
||||
|
||||
/// Native fallback for clipboard-file paste.
|
||||
///
|
||||
/// The composer keeps the host field's own text paste on every platform; this
|
||||
/// slice observes clipboard files on web only. A non-web host reports that
|
||||
/// missing capability rather than pretending no paste happened.
|
||||
const String chatClipboardPasteUnsupportedMessage =
|
||||
'Pasting files is not supported on this platform yet.';
|
||||
|
||||
ChatClipboardPaste get hostChatClipboardPaste =>
|
||||
const ChatClipboardPaste.unsupported(chatClipboardPasteUnsupportedMessage);
|
||||
@@ -0,0 +1,126 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'chat_attachment_picker.dart';
|
||||
import 'chat_clipboard_paste.dart';
|
||||
|
||||
/// The browser's clipboard-file paste, observed at the document once per
|
||||
/// composer.
|
||||
///
|
||||
/// Declared with `dart:js_interop` rather than `package:web`, so the same source
|
||||
/// compiles for the JavaScript and WebAssembly web targets. A paste carrying no
|
||||
/// file is left completely alone: the field's own text paste keeps its caret,
|
||||
/// selection and draft behaviour. Only a paste with files the composer will
|
||||
/// accept is consumed, and its bytes are read before the files join the
|
||||
/// composer's attachment draft.
|
||||
@JS('document')
|
||||
external _Document get _document;
|
||||
|
||||
extension type _Document._(JSObject _) implements JSObject {
|
||||
external void addEventListener(JSString type, JSFunction listener);
|
||||
|
||||
external void removeEventListener(JSString type, JSFunction listener);
|
||||
}
|
||||
|
||||
extension type _ClipboardEvent._(JSObject _) implements JSObject {
|
||||
external bool get defaultPrevented;
|
||||
|
||||
external _ClipboardData? get clipboardData;
|
||||
|
||||
external void preventDefault();
|
||||
}
|
||||
|
||||
extension type _ClipboardData._(JSObject _) implements JSObject {
|
||||
external _DataTransferItemList get items;
|
||||
}
|
||||
|
||||
extension type _DataTransferItemList._(JSObject _) implements JSObject {
|
||||
external int get length;
|
||||
}
|
||||
|
||||
extension type _DataTransferItem._(JSObject _) implements JSObject {
|
||||
external JSString get kind;
|
||||
|
||||
external _ClipboardFile? getAsFile();
|
||||
}
|
||||
|
||||
extension type _ClipboardFile._(JSObject _) implements JSObject {
|
||||
external JSString get name;
|
||||
|
||||
external JSString get type;
|
||||
|
||||
external JSPromise<JSArrayBuffer> arrayBuffer();
|
||||
}
|
||||
|
||||
ChatClipboardPaste get hostChatClipboardPaste =>
|
||||
const ChatClipboardPaste(subscribe: _subscribeToPaste);
|
||||
|
||||
ChatPasteUnsubscribe _subscribeToPaste(
|
||||
ChatPasteFiles onFiles,
|
||||
ChatPasteCanAccept canAccept,
|
||||
ChatPasteFailed onError,
|
||||
) {
|
||||
var sequence = 0;
|
||||
|
||||
void handlePaste(JSObject raw) {
|
||||
final event = _ClipboardEvent._(raw);
|
||||
if (event.defaultPrevented) return;
|
||||
final data = event.clipboardData;
|
||||
if (data == null) return;
|
||||
final items = data.items;
|
||||
final files = <_ClipboardFile>[];
|
||||
for (var index = 0; index < items.length; index += 1) {
|
||||
// DataTransferItemList is indexed, not a method list like FileList.
|
||||
final raw = items.getProperty<JSObject?>('$index'.toJS);
|
||||
if (raw == null) continue;
|
||||
final item = _DataTransferItem._(raw);
|
||||
if (item.kind.toDart != 'file') continue;
|
||||
final file = item.getAsFile();
|
||||
if (file != null) files.add(file);
|
||||
}
|
||||
// A text-only clipboard keeps the field's native paste untouched.
|
||||
if (files.isEmpty || !canAccept()) return;
|
||||
event.preventDefault();
|
||||
unawaited(_readFiles(files, onFiles, onError, () => ++sequence));
|
||||
}
|
||||
|
||||
final listener = handlePaste.toJS;
|
||||
_document.addEventListener('paste'.toJS, listener);
|
||||
return () => _document.removeEventListener('paste'.toJS, listener);
|
||||
}
|
||||
|
||||
Future<void> _readFiles(
|
||||
List<_ClipboardFile> files,
|
||||
ChatPasteFiles onFiles,
|
||||
ChatPasteFailed onError,
|
||||
int Function() nextSequence,
|
||||
) async {
|
||||
final pasted = <ChatPickedFile>[];
|
||||
final failures = <Object>[];
|
||||
for (final file in files) {
|
||||
try {
|
||||
final buffer = await file.arrayBuffer().toDart;
|
||||
final mime = file.type.toDart;
|
||||
final recorded = file.name.toDart.trim();
|
||||
pasted.add(
|
||||
ChatPickedFile(
|
||||
name: recorded.isEmpty
|
||||
? chatPastedAttachmentName(mime, nextSequence())
|
||||
: recorded,
|
||||
mime: mime,
|
||||
bytes: buffer.toDart.asUint8List(),
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
// One unreadable clipboard file must not hide the others.
|
||||
failures.add(error);
|
||||
}
|
||||
}
|
||||
// Deliver the readable files first: the composer's add clears an older
|
||||
// error, so a partial failure is reported after its kept files.
|
||||
if (pasted.isNotEmpty) onFiles(pasted);
|
||||
for (final failure in failures) {
|
||||
onError(failure);
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,18 @@ ChatCommand? chatCommandNamed(String draft) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The trimmed text after the command word, or empty when there is no argument.
|
||||
String chatCommandArgument(String draft) {
|
||||
final word = chatCommandWord(draft);
|
||||
if (word == null) return '';
|
||||
return draft.trimLeft().substring(word.length).trim();
|
||||
}
|
||||
|
||||
/// `/help`'s local listing, in the same order and wording as the palette.
|
||||
String chatCommandHelpText() => chatCommands
|
||||
.map((command) => '${command.usage} — ${command.summary}')
|
||||
.join('\n');
|
||||
|
||||
/// The local no-send report for a slash draft naming no recorded command,
|
||||
/// verbatim from the web client's unknown-command notice. The report offers the
|
||||
/// draft back, so only an explicit "Send as message" reaches the agent.
|
||||
@@ -131,15 +143,6 @@ const String chatDefaultSessionInstructions =
|
||||
/// The title every `/new` session is created with, as the web client sends it.
|
||||
const String chatNewSessionTitle = 'New chat';
|
||||
|
||||
/// The text after the slash word, trimmed; empty when the draft carries none.
|
||||
/// `/rename My chat ` yields `My chat`; `/close` yields the empty string.
|
||||
String chatCommandArgument(String draft) {
|
||||
final trimmed = draft.trim();
|
||||
final word = chatCommandWord(trimmed);
|
||||
if (word == null) return '';
|
||||
return trimmed.substring(word.length).trim();
|
||||
}
|
||||
|
||||
/// `/new` and `/close` act on the open session alone, so an argument is a
|
||||
/// usage error the web reports in these exact words.
|
||||
String chatCommandArgumentReport(ChatCommand command) =>
|
||||
|
||||
@@ -185,6 +185,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
controller: _sessions,
|
||||
onOpen: _open,
|
||||
onSessions: _adoptRows,
|
||||
activeSessionId: selected,
|
||||
),
|
||||
),
|
||||
if (selected != null)
|
||||
|
||||
@@ -7,18 +7,38 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
///
|
||||
/// Titles, stars and the closed state are server-owned and deliberately absent.
|
||||
class ChatSessionLocal {
|
||||
const ChatSessionLocal({this.hidden = const [], this.seenAt = const {}});
|
||||
const ChatSessionLocal({
|
||||
this.hidden = const [],
|
||||
this.seenAt = const {},
|
||||
this.unseen = const [],
|
||||
});
|
||||
|
||||
final List<String> hidden;
|
||||
final Map<String, int> seenAt;
|
||||
final List<String> unseen;
|
||||
|
||||
bool isHidden(String id) => hidden.contains(id);
|
||||
|
||||
int watermark(String id) => seenAt[id] ?? 0;
|
||||
|
||||
bool isUnseen(String id) => unseen.contains(id);
|
||||
|
||||
ChatSessionLocal markUnseen(String id) {
|
||||
if (id.trim().isEmpty || unseen.contains(id)) return this;
|
||||
return ChatSessionLocal(
|
||||
hidden: hidden,
|
||||
seenAt: seenAt,
|
||||
unseen: [...unseen, id],
|
||||
);
|
||||
}
|
||||
|
||||
ChatSessionLocal hide(String id) {
|
||||
if (id.isEmpty || hidden.contains(id)) return this;
|
||||
return ChatSessionLocal(hidden: [...hidden, id], seenAt: seenAt);
|
||||
return ChatSessionLocal(
|
||||
hidden: [...hidden, id],
|
||||
seenAt: seenAt,
|
||||
unseen: unseen,
|
||||
);
|
||||
}
|
||||
|
||||
ChatSessionLocal restore(String id) {
|
||||
@@ -26,14 +46,23 @@ class ChatSessionLocal {
|
||||
return ChatSessionLocal(
|
||||
hidden: hidden.where((entry) => entry != id).toList(),
|
||||
seenAt: seenAt,
|
||||
unseen: unseen,
|
||||
);
|
||||
}
|
||||
|
||||
/// Advances only for a strictly newer recency, so a stale list read can never
|
||||
/// mark newer activity as already seen.
|
||||
ChatSessionLocal read(String id, int updatedAt) {
|
||||
if (id.isEmpty || updatedAt <= watermark(id)) return this;
|
||||
return ChatSessionLocal(hidden: hidden, seenAt: {...seenAt, id: updatedAt});
|
||||
final nextUnseen = unseen.where((entry) => entry != id).toList();
|
||||
if (id.isEmpty ||
|
||||
(updatedAt <= watermark(id) && nextUnseen.length == unseen.length)) {
|
||||
return this;
|
||||
}
|
||||
return ChatSessionLocal(
|
||||
hidden: hidden,
|
||||
seenAt: updatedAt > watermark(id) ? {...seenAt, id: updatedAt} : seenAt,
|
||||
unseen: nextUnseen,
|
||||
);
|
||||
}
|
||||
|
||||
/// The first sight of a session baselines it, so pre-existing chats are not
|
||||
@@ -46,12 +75,14 @@ class ChatSessionLocal {
|
||||
next = ChatSessionLocal(
|
||||
hidden: next.hidden,
|
||||
seenAt: {...next.seenAt, row.id: row.updatedAt},
|
||||
unseen: next.unseen,
|
||||
);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
String encode() => jsonEncode({'hidden': hidden, 'seenAt': seenAt});
|
||||
String encode() =>
|
||||
jsonEncode({'hidden': hidden, 'seenAt': seenAt, 'unseen': unseen});
|
||||
|
||||
static ChatSessionLocal decode(Object? value) {
|
||||
try {
|
||||
@@ -59,6 +90,7 @@ class ChatSessionLocal {
|
||||
if (parsed is! Map) return const ChatSessionLocal();
|
||||
final hidden = parsed['hidden'];
|
||||
final seenAt = parsed['seenAt'];
|
||||
final unseen = parsed['unseen'];
|
||||
return ChatSessionLocal(
|
||||
hidden: hidden is List
|
||||
? hidden.whereType<String>().where((id) => id.isNotEmpty).toList()
|
||||
@@ -70,6 +102,13 @@ class ChatSessionLocal {
|
||||
'${entry.key}': entry.value as int,
|
||||
}
|
||||
: const {},
|
||||
unseen: unseen is List
|
||||
? unseen
|
||||
.whereType<String>()
|
||||
.where((id) => id.trim().isNotEmpty)
|
||||
.toSet()
|
||||
.toList()
|
||||
: const [],
|
||||
);
|
||||
} catch (_) {
|
||||
return const ChatSessionLocal();
|
||||
|
||||
@@ -17,7 +17,9 @@ import 'chat_session_local.dart';
|
||||
class ChatSessionsController extends ChangeNotifier {
|
||||
ChatSessionsController(this.repository, {ChatSessionLocalStore? localStore})
|
||||
: _localStore =
|
||||
localStore ?? const SharedPreferencesChatSessionLocalStore();
|
||||
localStore ?? const SharedPreferencesChatSessionLocalStore() {
|
||||
_listenFrames();
|
||||
}
|
||||
|
||||
ChatRepository repository;
|
||||
final ChatSessionLocalStore _localStore;
|
||||
@@ -31,6 +33,42 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
Future<void>? _localLoading;
|
||||
bool _disposed = false;
|
||||
int _generation = 0;
|
||||
StreamSubscription<JsonMap>? _frameSubscription;
|
||||
String? activeSessionId;
|
||||
|
||||
void _listenFrames() {
|
||||
_frameSubscription?.cancel();
|
||||
_frameSubscription = repository.gateway.frames.listen(_onFrame);
|
||||
}
|
||||
|
||||
void _onFrame(JsonMap frame) {
|
||||
final type = frame['type'];
|
||||
String? id;
|
||||
if (type == 'chat_event') {
|
||||
final event = frame['chat_event'];
|
||||
if (event is! Map || event['kind'] == 'usage') return;
|
||||
id = event['session_id'] is String ? event['session_id'] as String : null;
|
||||
} else if (type == 'chat_permission') {
|
||||
final permission = frame['chat_permission'];
|
||||
if (permission is! Map) return;
|
||||
id = permission['session_id'] is String
|
||||
? permission['session_id'] as String
|
||||
: null;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
if (id == null || id.isEmpty || id == activeSessionId) return;
|
||||
unawaited(_markUnseen(id));
|
||||
}
|
||||
|
||||
Future<void> _markUnseen(String id) async {
|
||||
await _ensureLocal();
|
||||
final next = _local.markUnseen(id);
|
||||
if (identical(next, _local)) return;
|
||||
_local = next;
|
||||
_notify();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
List<JsonMap> get sessions => [
|
||||
for (final session in _sessions)
|
||||
@@ -48,6 +86,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
|
||||
bool isUnseen(JsonMap session) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id == activeSessionId) return false;
|
||||
// Closed chats keep their recency from the close, but they are not new
|
||||
// work: both the web list and the Android list suppress unseen there.
|
||||
if (!_localLoaded ||
|
||||
@@ -57,6 +96,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
session['closed'] == true) {
|
||||
return false;
|
||||
}
|
||||
if (_local.isUnseen(id)) return true;
|
||||
final updatedAt = chatSessionMillis(session['updated_at']);
|
||||
return updatedAt > 0 && updatedAt > _local.watermark(id);
|
||||
}
|
||||
@@ -64,6 +104,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
void replaceRepository(ChatRepository next) {
|
||||
if (identical(next.gateway, repository.gateway)) return;
|
||||
repository = next;
|
||||
_listenFrames();
|
||||
refresh();
|
||||
}
|
||||
|
||||
@@ -160,6 +201,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
Future<void> markOpened(JsonMap session) async {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
activeSessionId = id;
|
||||
await _ensureLocal();
|
||||
final next = _local.read(id, chatSessionMillis(session['updated_at']));
|
||||
if (identical(next, _local)) return;
|
||||
@@ -251,6 +293,7 @@ class ChatSessionsController extends ChangeNotifier {
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_generation++;
|
||||
unawaited(_frameSubscription?.cancel());
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ class ChatSessionsScreen extends StatefulWidget {
|
||||
this.onSessions,
|
||||
this.localStore,
|
||||
this.controller,
|
||||
this.activeSessionId,
|
||||
});
|
||||
final ApiGateway gateway;
|
||||
final void Function(JsonMap session) onOpen;
|
||||
@@ -40,6 +41,10 @@ class ChatSessionsScreen extends StatefulWidget {
|
||||
/// title and model facts as a tapped row without a second list request.
|
||||
final ValueChanged<List<JsonMap>>? onSessions;
|
||||
|
||||
/// The conversation open above this list, or null when the list is showing.
|
||||
/// Pushed activity for it is being read, so it never raises a New mark.
|
||||
final String? activeSessionId;
|
||||
|
||||
/// Overrides the device-local hidden/read store in tests.
|
||||
final ChatSessionLocalStore? localStore;
|
||||
|
||||
@@ -59,6 +64,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
ChatRepository(widget.gateway),
|
||||
localStore: widget.localStore,
|
||||
))
|
||||
..activeSessionId = widget.activeSessionId
|
||||
..refresh();
|
||||
final _search = TextEditingController();
|
||||
Timer? _undoTimer;
|
||||
@@ -82,6 +88,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_controller.activeSessionId = widget.activeSessionId;
|
||||
if (oldWidget.gateway != widget.gateway) {
|
||||
_controller.replaceRepository(ChatRepository(widget.gateway));
|
||||
} else if (oldWidget.syncToken != widget.syncToken) {
|
||||
|
||||
Reference in New Issue
Block a user