Follow-ups to Phase E (ADR-15): - Recordings over 25 MB are cut into pieces and transcribed in turn: with ffmpeg (now in the server and all-in-one images) any format is re-encoded to 16 kHz mono MP3 in 20-minute pieces; without it, MP3 is cut at frame boundaries and WAV at sample boundaries in Go. - PDFs without a text layer are written out by a document-capable chat model (Anthropic document input, OpenAI file input); Ollama is skipped. - Phone app: AI answers render as Markdown with tappable citations; the editing toolbar opens the writing actions on the selection; audio files get Transcribe. Editor bridge protocol 4 adds setAi, getSelection, insertMarkdown and transcribe/transcribed. - The transcript HTML builder moves to @docwell/editor, shared by the web app and the phone editor. - An integration test runs chat, Transcribe and writing actions on a device against a live server; the editor test no longer expects headings to have only a level. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
270 lines
8.4 KiB
Dart
270 lines
8.4 KiB
Dart
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// The native side of the editor bridge (ADR-4). The editor page lives in
|
|
// Packages/editor-bridge; keep these messages in sync with its protocol.ts.
|
|
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
/// Protocol version this app speaks. The page reports its own in "ready".
|
|
const editorProtocolVersion = 4;
|
|
|
|
/// Formatting the native toolbar can apply.
|
|
enum EditorCommand {
|
|
bold,
|
|
italic,
|
|
strike,
|
|
code,
|
|
heading1,
|
|
heading2,
|
|
heading3,
|
|
bulletList,
|
|
orderedList,
|
|
blockquote,
|
|
codeBlock,
|
|
underline,
|
|
taskList,
|
|
callout,
|
|
table,
|
|
undo,
|
|
redo,
|
|
}
|
|
|
|
/// Toolbar state reported by the page.
|
|
@immutable
|
|
class EditorState {
|
|
const EditorState({
|
|
this.active = const {},
|
|
this.canUndo = false,
|
|
this.canRedo = false,
|
|
this.focused = false,
|
|
});
|
|
|
|
factory EditorState.fromJson(Map<String, dynamic> json) => EditorState(
|
|
active: {
|
|
for (final name in (json['active'] as List).cast<String>())
|
|
...EditorCommand.values.where((c) => c.name == name),
|
|
},
|
|
canUndo: json['canUndo'] as bool,
|
|
canRedo: json['canRedo'] as bool,
|
|
focused: json['focused'] as bool,
|
|
);
|
|
|
|
final Set<EditorCommand> active;
|
|
final bool canUndo;
|
|
final bool canRedo;
|
|
final bool focused;
|
|
}
|
|
|
|
/// Drives the editor page. It does not know about the WebView: [evaluate]
|
|
/// runs JavaScript in the page, and the host passes every message the page
|
|
/// sends to [handleMessage].
|
|
class EditorBridge extends ChangeNotifier {
|
|
EditorBridge({required this.evaluate, this._content});
|
|
|
|
final Future<void> Function(String script) evaluate;
|
|
|
|
Map<String, dynamic>? _content;
|
|
EditorState _state = const EditorState();
|
|
bool _ready = false;
|
|
String? _error;
|
|
final _readyCompleter = Completer<void>();
|
|
final _changes = StreamController<Map<String, dynamic>>.broadcast();
|
|
final _navigations = StreamController<String>.broadcast();
|
|
|
|
/// The latest document (Tiptap JSON), null until there is one.
|
|
Map<String, dynamic>? get content => _content;
|
|
EditorState get state => _state;
|
|
bool get isReady => _ready;
|
|
|
|
/// Live-editing status after [connect]: connecting, connected, offline,
|
|
/// denied or changed (see CollabStatus in @docwell/editor).
|
|
String? get collabStatus => _collabStatus;
|
|
String? _collabStatus;
|
|
|
|
/// Whether a panel or menu is open over the text (a database record, a
|
|
/// property picker). The back button closes it with [dismiss].
|
|
bool get overlayOpen => _overlayOpen;
|
|
bool _overlayOpen = false;
|
|
|
|
/// Set when the page is missing, outdated or reported a problem.
|
|
String? get error => _error;
|
|
|
|
/// Completes once the page answered and holds the initial content.
|
|
Future<void> get ready => _readyCompleter.future;
|
|
|
|
/// Every edit the user makes.
|
|
Stream<Map<String, dynamic>> get changes => _changes.stream;
|
|
|
|
/// App routes of page links the user followed, e.g. `/p/<id>`.
|
|
Stream<String> get navigations => _navigations.stream;
|
|
|
|
/// Call once the page has loaded.
|
|
Future<void> hello() => _post({'type': 'hello'});
|
|
|
|
// ---- AI (ADR-15) ---------------------------------------------------------
|
|
|
|
/// Called when the user taps Transcribe on an audio or video file: work
|
|
/// out the result and pass it to [answerTranscript] with the same id.
|
|
void Function(int id, String src, String name)? onTranscribe;
|
|
|
|
Completer<({String text, String before})>? _selection;
|
|
|
|
/// Whether media files get a Transcribe button, with its words.
|
|
Future<void> setAi({
|
|
required bool transcribe,
|
|
required Map<String, String> words,
|
|
}) => _post({'type': 'setAi', 'transcribe': transcribe, 'words': words});
|
|
|
|
/// The selected text and the text before it; the page keeps the range
|
|
/// for [insertMarkdown].
|
|
Future<({String text, String before})> selection() {
|
|
_selection?.completeError(StateError('replaced'));
|
|
final c = _selection = Completer();
|
|
unawaited(_post({'type': 'getSelection'}));
|
|
return c.future.timeout(const Duration(seconds: 5));
|
|
}
|
|
|
|
/// Puts Markdown over the range [selection] reported ("replace"), or
|
|
/// below its block ("below").
|
|
Future<void> insertMarkdown(String markdown, {required bool replace}) =>
|
|
_post({
|
|
'type': 'insertMarkdown',
|
|
'markdown': markdown,
|
|
'mode': replace ? 'replace' : 'below',
|
|
});
|
|
|
|
/// The answer to an [onTranscribe] request: the API's AiTranscript as
|
|
/// JSON, or an error to show.
|
|
Future<void> answerTranscript(
|
|
int id, {
|
|
Map<String, dynamic>? result,
|
|
String? error,
|
|
}) => _post({
|
|
'type': 'transcribed',
|
|
'id': id,
|
|
'result': ?result,
|
|
'error': ?error,
|
|
});
|
|
|
|
Future<void> run(EditorCommand c) =>
|
|
_post({'type': 'command', 'command': c.name});
|
|
|
|
Future<void> setContent(Map<String, dynamic>? content) {
|
|
_content = content;
|
|
return _post({'type': 'setContent', 'content': content});
|
|
}
|
|
|
|
Future<void> setEditable(bool editable) =>
|
|
_post({'type': 'setEditable', 'editable': editable});
|
|
|
|
Future<void> setTheme({required bool dark}) =>
|
|
_post({'type': 'setTheme', 'dark': dark});
|
|
|
|
/// The page's own layout: the wider column and the body font ("", serif
|
|
/// or mono, as the API's PageFont).
|
|
Future<void> setLayout({required bool fullWidth, required String font}) =>
|
|
_post({'type': 'setLayout', 'fullWidth': fullWidth, 'font': font});
|
|
|
|
Future<void> focus() => _post({'type': 'focus'});
|
|
|
|
/// Shows the page's text or its edgeless canvas, as the API's PageMode
|
|
/// names them: "page" or "edgeless". The canvas can be edited once
|
|
/// [connect]ed and [setEditable]; on saved content it is read-only.
|
|
Future<void> setMode(String mode, {String? title}) =>
|
|
_post({'type': 'setMode', 'mode': mode, 'title': ?title});
|
|
|
|
/// Closes the topmost panel or menu over the text.
|
|
Future<void> dismiss() => _post({'type': 'dismiss'});
|
|
|
|
/// Scrolls to a block (`#b-…`) or opens a database record (`#r-…`) of the
|
|
/// page, once it shows it.
|
|
Future<void> follow(String hash) => _post({'type': 'follow', 'hash': hash});
|
|
|
|
/// Edits the live page through docwell-server instead of local content.
|
|
Future<void> connect({
|
|
required String url,
|
|
required String page,
|
|
required String token,
|
|
required String userName,
|
|
required String userColor,
|
|
}) => _post({
|
|
'type': 'connect',
|
|
'url': url,
|
|
'page': page,
|
|
'token': token,
|
|
'user': {'name': userName, 'color': userColor},
|
|
});
|
|
|
|
/// Handles one JSON message from the page.
|
|
void handleMessage(String json) {
|
|
final msg = jsonDecode(json) as Map<String, dynamic>;
|
|
switch (msg['type']) {
|
|
case 'ready':
|
|
final version = msg['version'] as int;
|
|
if (version != editorProtocolVersion) {
|
|
_error =
|
|
'Editor page speaks protocol $version, app expects '
|
|
'$editorProtocolVersion';
|
|
notifyListeners();
|
|
return;
|
|
}
|
|
// The page may say ready twice (start-up and hello); load content once.
|
|
if (_ready) return;
|
|
_ready = true;
|
|
unawaited(
|
|
setContent(_content).then((_) {
|
|
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
|
|
}),
|
|
);
|
|
notifyListeners();
|
|
case 'change':
|
|
_content = msg['content'] as Map<String, dynamic>;
|
|
_changes.add(_content!);
|
|
case 'state':
|
|
_state = EditorState.fromJson(msg['state'] as Map<String, dynamic>);
|
|
notifyListeners();
|
|
case 'collab':
|
|
_collabStatus = msg['status'] as String;
|
|
notifyListeners();
|
|
case 'navigate':
|
|
_navigations.add(msg['path'] as String);
|
|
case 'overlay':
|
|
_overlayOpen = msg['open'] as bool;
|
|
notifyListeners();
|
|
case 'selection':
|
|
final c = _selection;
|
|
_selection = null;
|
|
if (c != null && !c.isCompleted) {
|
|
c.complete((
|
|
text: msg['text'] as String? ?? '',
|
|
before: msg['before'] as String? ?? '',
|
|
));
|
|
}
|
|
case 'transcribe':
|
|
final handler = onTranscribe;
|
|
final id = msg['id'] as int;
|
|
if (handler == null) {
|
|
unawaited(answerTranscript(id, error: 'unavailable'));
|
|
} else {
|
|
handler(id, msg['src'] as String, msg['name'] as String);
|
|
}
|
|
case 'error':
|
|
_error = msg['message'] as String;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
Future<void> _post(Map<String, dynamic> msg) =>
|
|
evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})');
|
|
|
|
@override
|
|
void dispose() {
|
|
_changes.close();
|
|
_navigations.close();
|
|
super.dispose();
|
|
}
|
|
}
|