feat(chat): fold answered permissions into a turn chip like tool calls

This commit is contained in:
2026-10-24 16:05:47 +01:00
parent c7852d27d1
commit 2740bb0673
10 changed files with 536 additions and 105 deletions
@@ -81,6 +81,7 @@ String chatPermissionResourceText(JsonMap permission) {
class ChatPermissionCardData {
const ChatPermissionCardData({
required this.requestId,
required this.action,
required this.resources,
required this.resourceText,
required this.risk,
@@ -93,6 +94,9 @@ class ChatPermissionCardData {
});
final String requestId;
/// The recorded action (the tool's name), blank when the request names none.
final String action;
final List<String> resources;
final String resourceText;
final String risk;
@@ -151,6 +155,7 @@ ChatPermissionCardData? chatPermissionCard(
};
return ChatPermissionCardData(
requestId: requestId,
action: action,
resources: chatPermissionResources(permission),
resourceText: chatPermissionResourceText(permission),
risk: chatPermissionRiskText(permission),
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/text/monospace.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart';
import '../ui/transcript/native_disclosure.dart';
import 'chat_permission_card_model.dart';
/// The settled approval requests of [row], a permission card row; null while it
/// still needs the operator or its last answer was refused.
ChatPermissionCardData? _settled(JsonMap row) {
if (row['kind'] != 'permission' || row['error'] != null) return null;
final frame = row['frame'];
if (frame is! Map) return null;
final card = chatPermissionCard(
Map<String, dynamic>.from(frame),
'${row['answer'] ?? ''}',
);
return card == null || card.actionable ? null : card;
}
/// Folds answered permission cards out of the card list, the way a turn's tool
/// calls fold into one chip.
///
/// A settled request joins the agent turn that raised it, matched by the tool
/// call id (Claude) or the message id (OpenCode) its frame recorded, as that
/// row's `permissions`. Requests naming no turn in view (a Codex request, or a
/// turn paged out) share one `permissions` row where the first of them stood.
/// Open requests stay full cards with their decision controls.
List<JsonMap> groupSettledPermissions(List<JsonMap> rows) {
final result = <JsonMap>[];
final attached = <int, List<ChatPermissionCardData>>{};
final loose = <ChatPermissionCardData>[];
int? looseAt;
for (final row in rows) {
final card = _settled(row);
if (card == null) {
result.add(row);
continue;
}
final turn = _turnOf(
result,
Map<String, dynamic>.from(row['frame'] as Map),
);
if (turn != null) {
attached.putIfAbsent(turn, () => []).add(card);
} else {
looseAt ??= result.length;
loose.add(card);
}
}
for (final entry in attached.entries) {
result[entry.key] = {...result[entry.key], 'permissions': entry.value};
}
if (looseAt != null) {
result.insert(looseAt, {
'kind': 'permissions',
'key': 'chat-permissions-${loose.first.requestId}',
'permissions': loose,
});
}
return result;
}
/// The index of the assistant row in [rows] that raised [frame], if any.
int? _turnOf(List<JsonMap> rows, JsonMap frame) {
final source = frame['source'];
if (source is! Map) return null;
final call = '${source['id'] ?? ''}'.trim();
final message = '${source['message_id'] ?? ''}'.trim();
for (var index = rows.length - 1; index >= 0; index--) {
final row = rows[index];
if (row['kind'] != 'assistant') continue;
final ids = row['messageIds'];
if (message.isNotEmpty && ids is List && ids.contains(message)) {
return index;
}
final parts = row['parts'];
if (call.isEmpty || parts is! List) continue;
for (final part in parts) {
if (part is Map && part['type'] == 'tool' && '${part['id']}' == call) {
return index;
}
}
}
return null;
}
/// `1 permission` / `N permissions`.
String chatPermissionsLabel(int count) =>
count == 1 ? '1 permission' : '$count permissions';
/// A turn's answered approval requests as one chip beside its tools chip,
/// tinted when one was rejected. It opens a sheet with one row per request.
class ChatPermissionsChip extends StatelessWidget {
const ChatPermissionsChip({super.key, required this.permissions});
final List<ChatPermissionCardData> permissions;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final rejected = permissions.any((p) => p.decision == chatDecisionReject);
final color = rejected
? (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant);
final label = chatPermissionsLabel(permissions.length);
return ChatTurnChip(
chipKey: const Key('chat-permission-chip'),
leading: Icon(
cupertino ? CupertinoIcons.checkmark_shield : Icons.shield_outlined,
size: 14,
color: color,
),
label: label,
color: color,
semanticsLabel: permissions.length == 1
? '1 permission request, expand for details'
: '${permissions.length} permission requests, expand for details',
sheet: _PermissionsSheet(permissions: permissions),
);
}
}
class _PermissionsSheet extends StatelessWidget {
const _PermissionsSheet({required this.permissions});
final List<ChatPermissionCardData> permissions;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return DefaultTextStyle.merge(
style: style,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: ListView(
key: const Key('chat-permission-sheet'),
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: [
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
chatPermissionsLabel(permissions.length),
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
for (final permission in permissions)
_PermissionRow(permission: permission),
],
),
),
);
}
}
/// One request: its action and outcome; it opens to the request's summary,
/// its full resources and the server's note.
class _PermissionRow extends StatelessWidget {
const _PermissionRow({required this.permission});
final ChatPermissionCardData permission;
@override
Widget build(BuildContext context) {
final action = permission.action.isEmpty
? chatApprovalBlankAction
: permission.action;
return NativeDisclosure(
label: '$action · ${permission.headline}',
childBuilder: (context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// A resolution's note can be the same text as the summary.
if (permission.risk != permission.statusLine)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(permission.risk),
),
if (permission.resources.isNotEmpty)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: SelectableText(
permission.resources.join('\n'),
style: const TextStyle(
fontFamily: appMonospaceFamily,
fontSize: 12,
),
),
),
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(permission.statusLine),
),
],
),
);
}
}
@@ -25,6 +25,8 @@ import 'chat_models.dart';
import 'chat_row_keys.dart';
import 'chat_scroll.dart';
import 'chat_thread_controller.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_transcript_card.dart';
/// One read-only conversation: the controller's transcript in the order the
@@ -587,11 +589,14 @@ class _ChatThreadViewState extends State<ChatThreadView> {
permissionErrorFor: _controller.permissionErrorFor,
formErrorFor: _controller.questionErrorFor,
);
final allRows = transcriptRows(
messages,
trailing: cards,
running: _controller.running && !_reconnecting && !_staleTranscript,
liveMessageId: _controller.liveAssistantMessageId,
// Answered approvals fold into their turn's chips, like tool calls.
final allRows = groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running: _controller.running && !_reconnecting && !_staleTranscript,
liveMessageId: _controller.liveAssistantMessageId,
),
);
// A transcript held from before a socket gap may still say a compaction is
// running even when the repair's read is refused. That running state is
@@ -922,7 +927,22 @@ class _ChatThreadViewState extends State<ChatThreadView> {
onQuestionAnswer: _controller.answerQuestion,
);
}
return ChatMessageView(row: row, textBuilder: chatMarkdownText);
final permissions = row['permissions'];
final chips = [
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
ChatPermissionsChip(permissions: permissions),
];
if (kind == 'permissions') {
return Align(
alignment: AlignmentDirectional.centerStart,
child: chips.firstOrNull ?? const SizedBox.shrink(),
);
}
return ChatMessageView(
row: row,
textBuilder: chatMarkdownText,
footer: chips,
);
}
/// The header's compact Back control, matching the web's icon-only control.
@@ -16,11 +16,20 @@ typedef ChatMessageTextBuilder = Widget Function(BuildContext, String);
/// One `transcriptRows` row: a user message or one folded agent turn. Parts keep
/// order for agent turns; native disclosures retain unknown parts as raw JSON.
class ChatMessageView extends StatelessWidget {
const ChatMessageView({super.key, required this.row, this.textBuilder});
const ChatMessageView({
super.key,
required this.row,
this.textBuilder,
this.footer = const [],
});
final JsonMap row;
final ChatMessageTextBuilder? textBuilder;
/// More of an agent turn's summary chips, after its tools chip (the turn's
/// settled permission requests).
final List<Widget> footer;
@override
Widget build(BuildContext context) {
final user = row['kind'] == 'user';
@@ -205,6 +214,7 @@ class ChatMessageView extends StatelessWidget {
final model = '${row['model'] ?? ''}'.trim();
final footer = <Widget>[
if (tools.isNotEmpty) ChatToolCallsChip(calls: tools),
...this.footer,
if (model.isNotEmpty)
Text(
model,
@@ -5,6 +5,7 @@ import '../../../../core/api_gateway.dart';
import '../../../../ui/text/monospace.dart';
import '../../domain/chat_tool_calls.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_turn_chip.dart';
import 'native_disclosure.dart';
/// A turn's one tool summary below its answer, as the web's chip: `N tools`,
@@ -41,7 +42,7 @@ class ChatToolCallsChip extends StatelessWidget {
size: 14,
color: color,
);
return _TurnChip(
return ChatTurnChip(
chipKey: const Key('chat-tool-chip'),
leading: leading,
label: label,
@@ -54,91 +55,6 @@ class ChatToolCallsChip extends StatelessWidget {
}
}
/// The quiet tool chip shell and its native sheet.
class _TurnChip extends StatelessWidget {
const _TurnChip({
required this.chipKey,
required this.leading,
required this.label,
required this.color,
required this.semanticsLabel,
required this.sheet,
});
final Key chipKey;
final Widget leading;
final String label;
final Color color;
final String semanticsLabel;
final Widget sheet;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final content = Row(
mainAxisSize: MainAxisSize.min,
children: [
leading,
const SizedBox(width: 6),
Text(label, style: TextStyle(color: color, fontSize: 13)),
Icon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
size: 14,
color: color,
),
],
);
return Semantics(
button: true,
// The child's own action is excluded with its label, so the node
// carries the activation for assistive technology.
onTap: () => _open(context, cupertino),
label: semanticsLabel,
excludeSemantics: true,
child: Padding(
padding: const EdgeInsets.only(top: 2),
child: cupertino
? CupertinoButton(
key: chipKey,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
minimumSize: Size.zero,
onPressed: () => _open(context, cupertino),
child: content,
)
: InkWell(
key: chipKey,
borderRadius: BorderRadius.circular(8),
onTap: () => _open(context, cupertino),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 6,
),
child: content,
),
),
),
);
}
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
context: context,
builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)),
);
}
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
builder: (_) => sheet,
);
}
}
class _ToolCallsSheet extends StatelessWidget {
const _ToolCallsSheet({required this.calls});
@@ -0,0 +1,91 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../sessions/chat_adaptive.dart';
/// The quiet chip under an agent turn (its tools, its permissions) and the
/// native sheet it opens.
class ChatTurnChip extends StatelessWidget {
const ChatTurnChip({
super.key,
required this.chipKey,
required this.leading,
required this.label,
required this.color,
required this.semanticsLabel,
required this.sheet,
});
final Key chipKey;
final Widget leading;
final String label;
final Color color;
final String semanticsLabel;
final Widget sheet;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final content = Row(
mainAxisSize: MainAxisSize.min,
children: [
leading,
const SizedBox(width: 6),
Text(label, style: TextStyle(color: color, fontSize: 13)),
Icon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
size: 14,
color: color,
),
],
);
return Semantics(
button: true,
// The child's own action is excluded with its label, so the node
// carries the activation for assistive technology.
onTap: () => _open(context, cupertino),
label: semanticsLabel,
excludeSemantics: true,
child: Padding(
padding: const EdgeInsets.only(top: 2),
child: cupertino
? CupertinoButton(
key: chipKey,
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
minimumSize: Size.zero,
onPressed: () => _open(context, cupertino),
child: content,
)
: InkWell(
key: chipKey,
borderRadius: BorderRadius.circular(8),
onTap: () => _open(context, cupertino),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 4,
vertical: 6,
),
child: content,
),
),
),
);
}
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
context: context,
builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)),
);
}
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
builder: (_) => sheet,
);
}
}
+31
View File
@@ -0,0 +1,31 @@
# Answered permissions fold into a chip like tool calls
User request: once a permission is allowed or rejected it should be grouped and
shown the way tool calls are, not left as a full card.
## Behavior
- An open request (or one whose reply was refused) stays the full card with its
Allow once / Always allow / Reject controls.
- Once answered locally or resolved by the server, it leaves the card list and
joins its turn's footer as `N permissions` beside `N tools`
(`groupSettledPermissions` in `lib/features/chat/conversation/chat_permission_group.dart`).
The turn is matched by the frame's `source.id` (Claude tool-use id = tool part
id) or `source.message_id` (OpenCode). Codex frames name no source, so those
(and requests whose turn is paged out) share one chip where the first stood.
- The chip is tinted when a request was rejected; it opens a native sheet with
one disclosure per request (`action · outcome`) holding the summary, full
resources and the server's note. The tool chip's frame is now the shared
`ChatTurnChip` (`lib/features/chat/ui/transcript/chat_turn_chip.dart`).
- Permission frames are not part of stored history, so as before they only exist
for the current visit (bounded to 20 settled requests).
## Evidence
- Tests: new `chat_permission_group_test.dart` (turn matching for Claude and
OpenCode, loose Codex group, pending/refused stay cards, chip beside tools,
sheet contents); two `chat_permission_card_test.dart` cases now expect the chip.
`flutter analyze` clean; full suite **1,865 tests pass**.
- Browser: `tool/chat_approvals_probe.mjs` (updated) passes in Material and
Cupertino; captures in `build/chat-permission-group-probe/`.
- Not deployed, no APK, no device verification.
@@ -275,7 +275,13 @@ void main() {
'client': 'Web',
},
});
expect(find.text('Allowed once'), findsOneWidget);
// The answered request folds into one chip, the way tool calls do.
expect(find.text('Approve bash'), findsNothing);
expect(find.text('1 permission'), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-permission-chip')));
await tester.pumpAndSettle();
await tester.tap(find.text('bash · Allowed once'));
await tester.pumpAndSettle();
expect(find.text('Waiting for the agent to continue…'), findsOneWidget);
held.complete(const {});
await tester.pumpAndSettle();
@@ -337,9 +343,12 @@ void main() {
),
});
await tester.pumpAndSettle();
expect(find.text('Allowed once'), findsOneWidget);
expect(find.text('Another device allowed once.'), findsOneWidget);
expect(find.text('Allow once'), findsNothing);
await tester.tap(find.byKey(const Key('chat-permission-chip')));
await tester.pumpAndSettle();
await tester.tap(find.text('bash · Allowed once'));
await tester.pumpAndSettle();
expect(find.text('Another device allowed once.'), findsOneWidget);
});
testWidgets('a turn waiting on a pending card hides the running indicator '
@@ -0,0 +1,128 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_permission_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_permission_group.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
JsonMap _turn(String id, {List<String> tools = const []}) => {
'kind': 'assistant',
'key': id,
'messageIds': [id],
'parts': [
for (final tool in tools) {'type': 'tool', 'id': tool, 'name': 'Bash'},
],
};
JsonMap _card(
String id, {
Map<String, String>? source,
String answer = '',
bool resolved = false,
String? error,
}) => {
'kind': 'permission',
'key': 'chat-permission-$id',
'frame': {
'request_id': id,
'action': 'Bash',
'source': ?source,
'resolved': resolved,
if (resolved) 'decision': 'reject',
},
'answer': answer,
'error': error,
};
List<String> _ids(Object? permissions) => [
for (final p in permissions as List<ChatPermissionCardData>) p.requestId,
];
void main() {
test('answered requests join the turn that raised them', () {
final rows = groupSettledPermissions([
_turn('m1', tools: ['call-1']),
_turn('m2'),
_card('claude', source: {'type': 'tool', 'id': 'call-1'}, answer: 'once'),
_card('opencode', source: {'message_id': 'm2'}, resolved: true),
]);
expect(rows.map((r) => r['kind']), ['assistant', 'assistant']);
expect(_ids(rows[0]['permissions']), ['claude']);
expect(_ids(rows[1]['permissions']), ['opencode']);
});
test('requests naming no turn share one row; open ones stay cards', () {
final rows = groupSettledPermissions([
_turn('m1'),
_card('codex-1', answer: 'once'),
_card('pending'),
_card('refused', answer: 'reject', error: 'request expired'),
_card('codex-2', resolved: true),
]);
expect(rows.map((r) => r['kind']), [
'assistant',
'permissions',
'permission',
'permission',
]);
expect(rows[0].containsKey('permissions'), isFalse);
expect(_ids(rows[1]['permissions']), ['codex-1', 'codex-2']);
expect(rows[2]['key'], 'chat-permission-pending');
expect(rows[3]['key'], 'chat-permission-refused');
});
testWidgets('a turn shows its answered permissions beside its tools', (
tester,
) async {
final gateway = FakeChatGateway()
..history = (_) async => chatPage([
chatMessage(
'm1',
'assistant',
parts: [
{'type': 'text', 'text': 'Done.'},
{
'type': 'tool',
'id': 'call-1',
'name': 'Bash',
'state': {'status': 'completed'},
},
],
),
]);
addTearDown(gateway.close);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': {
'session_id': 's',
'request_id': 'req-1',
'action': 'Bash',
'resources': ['rm -rf build'],
'source': {'type': 'tool', 'id': 'call-1'},
'resolved': true,
'decision': 'reject',
},
});
await tester.pumpAndSettle();
expect(find.text('1 tool'), findsOneWidget);
expect(find.text('1 permission'), findsOneWidget);
expect(find.text('Rejected'), findsNothing);
await tester.tap(find.byKey(const Key('chat-permission-chip')));
await tester.pumpAndSettle();
await tester.tap(find.text('Bash · Rejected'));
await tester.pumpAndSettle();
expect(find.text('rm -rf build'), findsOneWidget);
});
}
+17 -9
View File
@@ -305,15 +305,11 @@ try {
});
await click('Allow once');
const approvedRead = await waitForOCR('Allowed once');
for (const text of ['Recorded by the probe fixture']) {
if (!approvedRead.toLowerCase().includes(text.toLowerCase())) {
throw new Error(`Answered approval lacks ${JSON.stringify(text)}`);
}
}
// The answered request folds into its turn chips, like tool calls.
await waitForOCR('1 permission');
await capture('approval-answered');
evidence.checks.push({
check: 'the approval reply was sent and the recorded resolution cleared controls',
check: 'the approval reply was sent and the request folded into a permissions chip',
style,
allowOnceStillVisible: await hasText('Allow once'),
});
@@ -331,10 +327,22 @@ try {
sendAnswerStillVisible: await hasText('Send answer'),
});
if (evidence.checks.at(-1).sendAnswerStillVisible) {
await click('1 permission request');
await click('bash · Allowed once');
const sheetRead = await waitForOCR('Recorded by the probe fixture');
if (!flat(sheetRead).includes(flat('rm -rf build'))) {
throw new Error('The permissions sheet lost the recorded request');
}
await capture('permissions-sheet');
evidence.checks.push({
check: 'the permissions chip opens the recorded request and its outcome',
style,
});
if (evidence.checks.at(-2).sendAnswerStillVisible) {
throw new Error('Send answer stayed visible after the question resolved');
}
if (evidence.checks.at(-2).allowOnceStillVisible) {
if (evidence.checks.at(-3).allowOnceStillVisible) {
throw new Error('Allow once stayed visible after the approval resolved');
}