-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrv_request_handler.dart
More file actions
571 lines (529 loc) · 20 KB
/
Copy pathsrv_request_handler.dart
File metadata and controls
571 lines (529 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/// Listens for `srv.request` envelopes from the server and presents the
/// appropriate UI (currently: AskUserQuestion dialog). Mount once at app
/// root so any screen sees the dialog.
///
/// We render against the app's Navigator rather than our own `BuildContext`,
/// because this widget sits in `MaterialApp.builder` — above the Navigator.
library;
import 'dart:async';
// `visibleForTesting` is re-exported by Flutter material.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/router.dart';
import '../../app/theme.dart';
import '../../notifications/notification_observer.dart';
import '../../notifications/notification_request.dart';
import '../../store/connection.dart';
import '../../store/elicitation.dart';
import '../../store/store.dart';
import '../../transport/protocol.dart';
// Re-export the wizard's test entrypoint so existing importers of
// `srv_request_handler.dart` keep resolving it after the SPEC-19 split.
export 'srv_dialogs/ask_wizard.dart' show debugAskWizardFor;
class SrvRequestHandler extends ConsumerStatefulWidget {
const SrvRequestHandler({
super.key,
required this.child,
this.navigatorKey,
this.reminderDelay,
});
final Widget child;
final GlobalKey<NavigatorState>? navigatorKey;
/// Desktop mode. When set, requests ALWAYS present the in-app dialog
/// immediately (never diverted to a notification based on foreground
/// state — the desktop window is the control surface). If the request is
/// still unanswered after this delay, a system notification is fired as a
/// reminder. When null (mobile), backgrounded requests are diverted to an
/// actionable notification instead of the invisible dialog.
final Duration? reminderDelay;
@override
ConsumerState<SrvRequestHandler> createState() => _SrvRequestHandlerState();
}
class _SrvRequestHandlerState extends ConsumerState<SrvRequestHandler>
with WidgetsBindingObserver {
StreamSubscription<Envelope>? _sub;
StreamSubscription<String>? _respondedSub;
bool _foreground = true;
/// Backgrounded requests for which we fired a notification. Kept so that if
/// the user resumes the app without acting on the notification, we can still
/// present the dialog (the `srvRequests` stream has no replay). Soft-capped
/// so a long backgrounded session can't grow it without bound (mirrors the
/// SPEC-07 status-notification queue); oldest entries are evicted first.
final Map<String, Envelope> _pendingBackground = {};
static const _kMaxPendingBackground = 50;
/// Desktop reminder timers, keyed by request id. Fires a system notification
/// when a dialog has been open (unanswered) for [SrvRequestHandler.reminderDelay];
/// cancelled when the request is answered or the widget disposes.
final Map<String, Timer> _reminderTimers = {};
/// Dialog contexts keyed by request id, so an answer from a notification can
/// remove that request's exact route without disturbing another open dialog.
final Map<String, BuildContext> _activeDialogContexts = {};
final Map<String, Object> _activeDialogTokens = {};
/// Salted so request-notification ids can't collide with the status
/// notifications keyed on `sessionId.hashCode`.
int _notificationId(String requestId) =>
(requestId.hashCode ^ 0x52455148).toUnsigned(31);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) => _subscribe());
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// `inactive` (e.g. transient system overlay) still counts as foreground so
// an in-flight request isn't diverted to a notification the user can see
// the app behind. A true background→foreground transition drains any
// queued fallback dialogs.
final wasForeground = _foreground;
_foreground =
state == AppLifecycleState.resumed ||
state == AppLifecycleState.inactive;
if (!wasForeground && _foreground) _drainPendingBackground();
}
/// Present any still-pending backgrounded requests as dialogs on resume.
///
/// Approve/Deny/Reply are FOREGROUND notification actions: tapping one
/// resumes the app, and the action callback (→ `respondTo` → `responded`)
/// can land slightly AFTER `resumed`. We therefore delay the drain briefly
/// and re-check `_pendingBackground` before presenting, so a request already
/// answered from the notification is not double-prompted.
void _drainPendingBackground() {
if (_pendingBackground.isEmpty) return;
final queued = List<Envelope>.from(_pendingBackground.values);
Future.delayed(const Duration(milliseconds: 400), () async {
for (final env in queued) {
if (!mounted) return;
if (!_pendingBackground.containsKey(env.id)) continue;
_pendingBackground.remove(env.id);
await _presentDialog(env);
}
});
}
void _subscribe() {
_sub?.cancel();
final controller = ref.read(connectionControllerProvider.notifier);
_sub = controller.srvRequests.listen(_dispatch);
_respondedSub?.cancel();
_respondedSub = controller.responded.listen(_onResponded);
}
void _onResponded(String id) {
_pendingBackground.remove(id);
_reminderTimers.remove(id)?.cancel();
_activeDialogTokens.remove(id);
final dialogContext = _activeDialogContexts.remove(id);
if (dialogContext == null || !dialogContext.mounted) return;
final route = ModalRoute.of(dialogContext);
if (route != null && route.isActive) {
Navigator.of(dialogContext).removeRoute(route);
}
}
Future<T?> _showTrackedDialog<T>({
required String requestId,
required BuildContext context,
required WidgetBuilder builder,
bool barrierDismissible = true,
}) async {
final dialogToken = Object();
final result = await showDialog<T>(
context: context,
barrierDismissible: barrierDismissible,
builder: (dctx) {
_activeDialogContexts[requestId] = dctx;
_activeDialogTokens[requestId] = dialogToken;
return builder(dctx);
},
);
if (identical(_activeDialogTokens[requestId], dialogToken)) {
_activeDialogTokens.remove(requestId);
_activeDialogContexts.remove(requestId);
}
return result;
}
/// Fire a system notification once a still-unanswered request has been
/// on-screen for [SrvRequestHandler.reminderDelay] (desktop only).
void _scheduleReminder(Envelope env, String kind) {
final sessionId = env.body['sessionId'] as String? ?? '';
_reminderTimers.remove(env.id)?.cancel();
_reminderTimers[env.id] = Timer(widget.reminderDelay!, () async {
_reminderTimers.remove(env.id);
if (!mounted) return;
final notif = notificationForRequest(
kind: kind,
body: env.body,
label: _labelFor(sessionId),
);
if (notif == null) return;
await ref
.read(notificationServiceProvider)
.show(
id: _notificationId(env.id),
title: notif.title,
body: notif.body,
category: notif.category,
payload: encodeRequestPayload(
sessionId: sessionId,
requestId: env.id,
kind: kind,
),
);
});
}
Future<void> _dispatch(Envelope env) async {
final kind = env.body['kind'] as String? ?? 'unknown';
// Desktop: always present the dialog now; if it goes unanswered for
// `reminderDelay`, nudge with a system notification (the tap routes back
// through respondTo, and the in-app dialog stays answerable meanwhile).
if (widget.reminderDelay != null) {
_scheduleReminder(env, kind);
await _presentDialog(env);
return;
}
// Backgrounded: if this request kind has an actionable-notification
// affordance, fire the notification and skip the (invisible) dialog. The
// user resolves it from the lock screen; the tap routes back through
// `respondTo` (see main.dart onAction).
if (!_foreground) {
final sessionId = env.body['sessionId'] as String? ?? '';
final notif = notificationForRequest(
kind: kind,
body: env.body,
label: _labelFor(sessionId),
);
if (notif != null) {
final shown = await ref
.read(notificationServiceProvider)
.show(
id: _notificationId(env.id),
title: notif.title,
body: notif.body,
category: notif.category,
payload: encodeRequestPayload(
sessionId: sessionId,
requestId: env.id,
kind: kind,
),
);
// Shown: keep it so a resume-without-action still surfaces a dialog.
// Not shown (no permission / dismissed / platform throw): fall through
// to present the dialog now, so the request stays answerable.
if (shown) {
if (_pendingBackground.length >= _kMaxPendingBackground) {
_pendingBackground.remove(_pendingBackground.keys.first);
}
_pendingBackground[env.id] = env;
return;
}
}
}
await _presentDialog(env);
}
Future<void> _presentDialog(Envelope env) async {
final kind = env.body['kind'] as String? ?? 'unknown';
// askUserQuestion renders inline (SPEC-25) — it needs no Navigator, so
// handle it before the navigator-context guard below.
if (kind == 'askUserQuestion') {
final questions = _normaliseQuestions(env.body);
if (questions.isEmpty) {
_respond(env.id, {
'kind': 'askUserQuestion',
'indices': <int>[],
'answers': <String>[],
'error': 'no questions',
});
return;
}
// The desktop reminder timer (scheduled in _dispatch) and _onResponded
// cleanup still apply; the store answers via the connection's respondTo.
ref
.read(elicitationControllerProvider.notifier)
.add(
PendingAsk(
requestId: env.id,
sessionId: env.body['sessionId'] as String? ?? '',
questions: questions,
),
);
return;
}
// Use the app's Navigator, not this widget's context — we're above it.
final navCtx = (widget.navigatorKey ?? makitNavigatorKey).currentContext;
if (navCtx == null) return;
if (kind == 'confirmAction') {
await _showConfirmAction(navCtx, env.id, env.body);
return;
}
if (kind == 'input') {
// pi-ask-user's multi-select fallback arrives as ctx.ui.input with the
// options embedded in the prompt. Render it inline as a multi-select
// card instead of a modal; ordinary free-text input stays modal.
final ms = PendingAsk.fromMultiSelectInput(
requestId: env.id,
sessionId: env.body['sessionId'] as String? ?? '',
title: env.body['title']?.toString() ?? '',
);
if (ms != null) {
ref.read(elicitationControllerProvider.notifier).add(ms);
return;
}
await _showInput(navCtx, env.id, env.body);
return;
}
await _showGeneric(navCtx, env);
}
List<Map<String, dynamic>> _normaliseQuestions(Map<String, dynamic> body) {
final raw = body['questions'];
if (raw is List) {
return raw
.whereType<Map<dynamic, dynamic>>()
.map(Map<String, dynamic>.from)
.toList();
}
// Single-question form — wrap as one-element wizard.
if (body['question'] is String) {
return [
{
'header': body['header'],
'question': body['question'],
'options': body['options'],
'multi': body['multi'],
'recommended': body['recommended'],
},
];
}
return const [];
}
Future<void> _showConfirmAction(
BuildContext ctx,
String requestId,
Map<String, dynamic> body,
) async {
final approved = await _showTrackedDialog<bool>(
requestId: requestId,
context: ctx,
barrierDismissible: false,
builder: (dctx) => AlertDialog(
// D14 made this dialog open-ended: the caption carries a whole handoff
// reason and the message is whatever the agent wrote. Unscrollable, a
// long prompt is text the user can neither finish reading nor scroll
// past to reach Deny/Approve — which trains them to answer without
// reading, the very thing captioning them was meant to prevent.
scrollable: true,
title: Text(body['title']?.toString() ?? 'Confirm'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_PromptCaption(session: body['session']),
Text(body['message']?.toString() ?? ''),
if (body['preview'] != null) ...[
const SizedBox(height: kSpace8),
Container(
padding: const EdgeInsets.all(kSpace8),
decoration: BoxDecoration(
color: Theme.of(dctx).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(kRadius6),
),
child: SelectableText(
body['preview'].toString(),
style: Theme.of(dctx).textTheme.bodySmall?.mono,
),
),
],
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dctx, false),
child: const Text('Deny'),
),
FilledButton(
onPressed: () => Navigator.pop(dctx, true),
child: const Text('Approve'),
),
],
),
);
_respond(requestId, SrvResponse.confirmAction(approved: approved ?? false));
}
/// Free-text input (maps pi's ctx.ui.input / ctx.ui.editor via the PiAdapter
/// UI interceptor). Responds with the canonical `input` shape.
Future<void> _showInput(
BuildContext ctx,
String requestId,
Map<String, dynamic> body,
) async {
final controller = TextEditingController(
text: body['prefill']?.toString() ?? '',
);
final multiline = body['multiline'] == true;
final value = await _showTrackedDialog<String?>(
requestId: requestId,
context: ctx,
barrierDismissible: false,
builder: (dctx) => AlertDialog(
// Scrollable for the same reason as the permission prompt, and more so:
// an 8-line field sits under the caption here, with the keyboard up.
scrollable: true,
title: Text(body['title']?.toString() ?? 'Input'),
// Captioned like a permission prompt (D14): D13 routes an elicitation up
// the same ladder, so this dialog can equally reach a phone that has
// never opened the session asking the question.
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_PromptCaption(session: body['session']),
TextField(
controller: controller,
autofocus: true,
minLines: multiline ? 3 : 1,
maxLines: multiline ? 8 : 1,
decoration: InputDecoration(
hintText: body['placeholder']?.toString(),
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dctx),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(dctx, controller.text),
child: const Text('Send'),
),
],
),
);
if (value == null) {
_respond(requestId, SrvResponse.cancelled('input'));
} else {
_respond(requestId, SrvResponse.input(value));
}
}
Future<void> _showGeneric(BuildContext ctx, Envelope env) async {
final controller = TextEditingController();
final text = await _showTrackedDialog<String?>(
requestId: env.id,
context: ctx,
builder: (dctx) => AlertDialog(
title: Text(env.body['title']?.toString() ?? 'Server request'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
env.body['message']?.toString() ??
env.body['kind']?.toString() ??
'',
),
const SizedBox(height: kSpace12),
TextField(
controller: controller,
autofocus: true,
decoration: const InputDecoration(hintText: 'Your answer'),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dctx),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(dctx, controller.text),
child: const Text('Send'),
),
],
),
);
if (text == null) {
_respond(env.id, {'ok': false, 'cancelled': true});
} else {
_respond(env.id, {'ok': true, 'text': text});
}
}
void _respond(String id, Map<String, dynamic> body) {
ref.read(connectionControllerProvider.notifier).respondTo(id, body);
}
/// Human-readable label for a session (project name), mirroring
/// `NotificationController.labelFor`. Falls back to the session title.
String _labelFor(String sessionId) {
if (sessionId.isEmpty) return '';
final sessions = ref.read(sessionsProvider).sessions;
final match = sessions.where((s) => s.id == sessionId);
if (match.isEmpty) return '';
final session = match.first;
final projects = ref.read(projectsProvider).projects;
final proj = projects.where((p) => p.id == session.projectId);
return proj.isEmpty ? session.title : proj.first.name;
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_sub?.cancel();
_respondedSub?.cancel();
for (final t in _reminderTimers.values) {
t.cancel();
}
_reminderTimers.clear();
_activeDialogContexts.clear();
_activeDialogTokens.clear();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
/// SPEC-46 D14 — a self-describing header for a prompt whose session the phone
/// may never have subscribed to. Sourced entirely from the `srv.request`
/// envelope's `session` block (title, agent/harness, handoff origin), never
/// from cached store state, so a stranded prompt reached at rung 3 of the D13
/// ladder is still attributable. Renders nothing when the block is absent
/// (existing prompts are unchanged).
class _PromptCaption extends StatelessWidget {
const _PromptCaption({required this.session});
final Object? session;
@override
Widget build(BuildContext context) {
final s = session;
if (s is! Map) return const SizedBox.shrink();
final title = s['title']?.toString();
final agent = s['agent']?.toString();
final handoffReason = s['handoffReason']?.toString();
if ((title == null || title.isEmpty) &&
(agent == null || agent.isEmpty) &&
(handoffReason == null || handoffReason.isEmpty)) {
return const SizedBox.shrink();
}
final theme = Theme.of(context);
final heading = [
if (title != null && title.isNotEmpty) title,
if (agent != null && agent.isNotEmpty) agent,
].join(' · ');
return Padding(
padding: const EdgeInsets.only(bottom: kSpace12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (heading.isNotEmpty)
Text(
heading,
style: theme.textTheme.labelLarge?.copyWith(
color: theme.colorScheme.primary,
),
),
if (handoffReason != null && handoffReason.isNotEmpty)
Text(
'Handed off: $handoffReason',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
);
}
}