feat(chat): per-chat permission modes for Claude, Codex and OpenCode
This commit is contained in:
@@ -0,0 +1,318 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../../../core/error_reason.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
|
||||
/// The conversation bar's permission-mode control.
|
||||
///
|
||||
/// It shows the mode the session row names (`mode_name`, the harness default
|
||||
/// when none was chosen) without a request of its own, since requests are
|
||||
/// serialized and must not delay the transcript. Tapping reads the harness's
|
||||
/// modes (`chat_modes`) into a native picker; choosing one sends `chat_mode`. A
|
||||
/// refusal keeps the picker open with the server's reason. A row without a
|
||||
/// mode (an older server or a harness without modes) shows no control.
|
||||
class ChatModeControl extends StatefulWidget {
|
||||
const ChatModeControl({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
required this.mode,
|
||||
required this.modeName,
|
||||
this.onChanged,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
|
||||
/// The row's `mode` id and its display name.
|
||||
final String mode;
|
||||
final String modeName;
|
||||
|
||||
/// The accepted mode's id and name, so the opened row keeps up.
|
||||
final void Function(String mode, String name)? onChanged;
|
||||
|
||||
@override
|
||||
State<ChatModeControl> createState() => _ChatModeControlState();
|
||||
}
|
||||
|
||||
class _ChatModeControlState extends State<ChatModeControl> {
|
||||
late String _mode = widget.mode;
|
||||
late String _name = widget.modeName;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatModeControl oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.mode != widget.mode ||
|
||||
oldWidget.modeName != widget.modeName) {
|
||||
_mode = widget.mode;
|
||||
_name = widget.modeName;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final repository = ChatRepository(widget.gateway);
|
||||
final picker = _ChatModePicker(
|
||||
load: () => repository.modes(widget.sessionId),
|
||||
current: _mode,
|
||||
cupertino: cupertino,
|
||||
choose: (mode) async {
|
||||
final applied = await repository.selectMode(widget.sessionId, mode.id);
|
||||
final name = applied == mode.id ? mode.name : applied;
|
||||
widget.onChanged?.call(applied, name);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_mode = applied;
|
||||
_name = name;
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
if (cupertino) {
|
||||
await showCupertinoModalPopup<void>(
|
||||
context: context,
|
||||
builder: (_) => picker,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
showDragHandle: true,
|
||||
isScrollControlled: true,
|
||||
useSafeArea: true,
|
||||
builder: (_) => picker,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (_mode.isEmpty || _name.isEmpty) return const SizedBox.shrink();
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final label = _name;
|
||||
final content = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.shield_lefthalf_fill
|
||||
: Icons.shield_outlined,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
|
||||
],
|
||||
);
|
||||
const key = Key('chat-mode');
|
||||
if (cupertino) {
|
||||
return Semantics(
|
||||
container: true,
|
||||
button: true,
|
||||
label: 'Change mode, currently $label',
|
||||
onTap: _open,
|
||||
child: ExcludeSemantics(
|
||||
child: CupertinoButton(
|
||||
key: key,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: _open,
|
||||
child: content,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Tooltip(
|
||||
message: 'Change mode (currently $label)',
|
||||
child: TextButton(key: key, onPressed: _open, child: content),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One mode the harness offers.
|
||||
typedef _Mode = ({String id, String name, String description});
|
||||
|
||||
/// The native mode list: each mode's name and description, the current one
|
||||
/// checked. It reads the list when opened and closes once the server accepts
|
||||
/// a choice.
|
||||
class _ChatModePicker extends StatefulWidget {
|
||||
const _ChatModePicker({
|
||||
required this.load,
|
||||
required this.current,
|
||||
required this.cupertino,
|
||||
required this.choose,
|
||||
});
|
||||
|
||||
final Future<({List<JsonMap> modes, String current})> Function() load;
|
||||
final String current;
|
||||
final bool cupertino;
|
||||
final Future<void> Function(_Mode mode) choose;
|
||||
|
||||
@override
|
||||
State<_ChatModePicker> createState() => _ChatModePickerState();
|
||||
}
|
||||
|
||||
class _ChatModePickerState extends State<_ChatModePicker> {
|
||||
List<_Mode>? _modes;
|
||||
late String _current = widget.current;
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_read();
|
||||
}
|
||||
|
||||
Future<void> _read() async {
|
||||
try {
|
||||
final reply = await widget.load();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_modes = [
|
||||
for (final mode in reply.modes)
|
||||
if ('${mode['id'] ?? ''}'.trim().isNotEmpty)
|
||||
(
|
||||
id: '${mode['id']}'.trim(),
|
||||
name: '${mode['name'] ?? mode['id']}'.trim(),
|
||||
description: '${mode['description'] ?? ''}'.trim(),
|
||||
),
|
||||
];
|
||||
if (reply.current.isNotEmpty) _current = reply.current;
|
||||
});
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_modes = const [];
|
||||
_error = describeErrorReason(
|
||||
error,
|
||||
fallback: 'The modes could not be loaded.',
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _choose(_Mode mode) async {
|
||||
if (_busy) return;
|
||||
if (mode.id == _current) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
await widget.choose(mode);
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
} catch (error) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_busy = false;
|
||||
_error = describeErrorReason(
|
||||
error,
|
||||
fallback: 'The mode was not changed.',
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
widget.cupertino ? _cupertinoSheet(context) : _materialSheet(context);
|
||||
|
||||
Widget _materialSheet(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final modes = _modes;
|
||||
return SafeArea(
|
||||
child: ListView(
|
||||
key: const Key('chat-mode-sheet'),
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||
child: Text('Mode', style: theme.textTheme.titleMedium),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||
child: Text(
|
||||
_error!,
|
||||
style: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
),
|
||||
if (modes == null)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else
|
||||
for (final mode in modes)
|
||||
ListTile(
|
||||
key: ValueKey<String>('chat-mode-option-${mode.id}'),
|
||||
enabled: !_busy,
|
||||
title: Text(mode.name),
|
||||
subtitle: mode.description.isEmpty
|
||||
? null
|
||||
: Text(mode.description),
|
||||
trailing: mode.id == _current
|
||||
? Icon(Icons.check, color: theme.colorScheme.primary)
|
||||
: null,
|
||||
onTap: () => _choose(mode),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertinoSheet(BuildContext context) {
|
||||
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
|
||||
final modes = _modes;
|
||||
return CupertinoActionSheet(
|
||||
key: const Key('chat-mode-sheet'),
|
||||
title: const Text('Mode'),
|
||||
message: _error != null
|
||||
? Text(
|
||||
_error!,
|
||||
style: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
)
|
||||
: modes == null
|
||||
? const CupertinoActivityIndicator()
|
||||
: null,
|
||||
actions: [
|
||||
for (final mode in modes ?? const <_Mode>[])
|
||||
CupertinoActionSheetAction(
|
||||
key: ValueKey<String>('chat-mode-option-${mode.id}'),
|
||||
onPressed: () => _choose(mode),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(child: Text(mode.name)),
|
||||
if (mode.id == _current) ...[
|
||||
const SizedBox(width: 6),
|
||||
const Icon(CupertinoIcons.checkmark_alt),
|
||||
],
|
||||
],
|
||||
),
|
||||
if (mode.description.isNotEmpty)
|
||||
Text(
|
||||
mode.description,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(fontSize: 13, color: secondary),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
cancelButton: CupertinoActionSheetAction(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import 'chat_command_actions.dart';
|
||||
import 'chat_composer_bar.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_mode_control.dart';
|
||||
import 'chat_model_control.dart';
|
||||
import 'chat_models.dart';
|
||||
import 'chat_row_keys.dart';
|
||||
@@ -48,6 +49,7 @@ class ChatThreadView extends StatefulWidget {
|
||||
this.title = '',
|
||||
this.session,
|
||||
this.onModelChanged,
|
||||
this.onModeChanged,
|
||||
this.syncToken = 0,
|
||||
this.drafts,
|
||||
this.newOperationId,
|
||||
@@ -90,6 +92,9 @@ class ChatThreadView extends StatefulWidget {
|
||||
/// keep the row it opened current for the next visit.
|
||||
final ValueChanged<ChatModelSelection>? onModelChanged;
|
||||
|
||||
/// The accepted permission mode's id and name.
|
||||
final void Function(String mode, String name)? onModeChanged;
|
||||
|
||||
/// Advances when the shared socket is replaced, keeping this selection.
|
||||
final int syncToken;
|
||||
|
||||
@@ -701,6 +706,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
answeredBy: latestReplyModel(_controller.messages),
|
||||
),
|
||||
),
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: constraints.maxWidth * 0.3,
|
||||
),
|
||||
child: _modeControl(),
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-info'),
|
||||
label: 'Chat information',
|
||||
@@ -864,6 +875,10 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
answeredBy: latestReplyModel(_controller.messages),
|
||||
),
|
||||
),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 160),
|
||||
child: _modeControl(),
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-info'),
|
||||
label: 'Chat information',
|
||||
@@ -877,6 +892,17 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
},
|
||||
);
|
||||
|
||||
/// The session's permission mode, keyed per session so another chat
|
||||
/// re-reads its own modes.
|
||||
Widget _modeControl() => ChatModeControl(
|
||||
key: ValueKey<String>('chat-mode-${widget.sessionId}'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
mode: '${widget.session?['mode'] ?? ''}'.trim(),
|
||||
modeName: '${widget.session?['mode_name'] ?? ''}'.trim(),
|
||||
onChanged: widget.onModeChanged,
|
||||
);
|
||||
|
||||
ChatNotice? _noticeOf(List<ChatNotice> notices, ChatNoticeKind kind) {
|
||||
for (final notice in notices) {
|
||||
if (notice.kind == kind) return notice;
|
||||
|
||||
@@ -49,6 +49,40 @@ class ChatRepository {
|
||||
});
|
||||
}
|
||||
|
||||
/// The permission modes the session's harness offers, in the server's
|
||||
/// order, and the session's stored mode (empty for the harness default).
|
||||
Future<({List<JsonMap> modes, String current})> modes(
|
||||
String sessionId,
|
||||
) async {
|
||||
final session = sessionId.trim();
|
||||
if (session.isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
final reply = await gateway.call('chat_modes', {
|
||||
'chat_query': {'session_id': session},
|
||||
});
|
||||
final value = reply['chat_modes'];
|
||||
final current = reply['chat_mode'];
|
||||
return (
|
||||
modes: value is List ? _maps(value) : const <JsonMap>[],
|
||||
current: current is Map ? '${current['mode'] ?? ''}'.trim() : '',
|
||||
);
|
||||
}
|
||||
|
||||
/// Switches the session's mode; the reply echoes the stored mode.
|
||||
Future<String> selectMode(String sessionId, String mode) async {
|
||||
final session = sessionId.trim();
|
||||
if (session.isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
if (mode.trim().isEmpty) throw ArgumentError('Choose a mode first.');
|
||||
final reply = await gateway.call('chat_mode', {
|
||||
'chat_mode': {'session_id': session, 'mode': mode.trim()},
|
||||
});
|
||||
final echoed = reply['chat_mode'];
|
||||
return echoed is Map ? '${echoed['mode'] ?? ''}'.trim() : mode.trim();
|
||||
}
|
||||
|
||||
Future<List<JsonMap>> shells(String sessionId) async => _maps(
|
||||
(await gateway.call('chat_shells', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
|
||||
@@ -145,6 +145,16 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
setState(() => _acceptedModels[id] = applied);
|
||||
}
|
||||
|
||||
/// An accepted mode switch updates the opened row, so reopening the chat in
|
||||
/// this visit shows it before the list re-reads.
|
||||
void _modeChanged(String id, String mode, String name) {
|
||||
final row = _openedSessions[id];
|
||||
if (!mounted || row == null) return;
|
||||
setState(
|
||||
() => _openedSessions[id] = {...row, 'mode': mode, 'mode_name': name},
|
||||
);
|
||||
}
|
||||
|
||||
/// The row to open for [id], with an accepted model folded in.
|
||||
JsonMap? _rowFor(String id) {
|
||||
final row = _openedSessions[id];
|
||||
@@ -194,6 +204,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
: null,
|
||||
onBack: onBack,
|
||||
onModelChanged: (applied) => _modelChanged(selected, applied),
|
||||
onModeChanged: (mode, name) => _modeChanged(selected, mode, name),
|
||||
onCreatedSession: _openCreated,
|
||||
onSessionRenamed: (title) => _renamed(selected, title),
|
||||
onSessionClosed: _closed,
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Chat permission modes
|
||||
|
||||
User request (2026-10-24): change a chat to auto mode instead of plan/ask, for
|
||||
Claude, Codex and OpenCode. Server and app change (user authorized the server).
|
||||
|
||||
## Server
|
||||
|
||||
- Protocol: `chat_modes` (ChatQuery → `chat_modes` list + current `chat_mode`)
|
||||
and `chat_mode` ({session_id, mode} → echoed stored mode). `ChatSession` rows
|
||||
carry `mode` and `mode_name` (the harness default, listed first, when none was
|
||||
chosen).
|
||||
- Stored in `operator_sessions.chat_mode` (additive migration); re-applied to the
|
||||
harness before every turn, so a server restart keeps the choice.
|
||||
- Claude: default (ask), acceptEdits, plan, auto, bypassPermissions. A new CLI
|
||||
starts with `--permission-mode`; a running one switches in place with the
|
||||
`set_permission_mode` control request (verified present in CLI 2.1.310).
|
||||
`dontAsk` is omitted on purpose.
|
||||
- Codex: ask (on-request + workspaceWrite), auto (never + workspaceWrite), full
|
||||
(never + dangerFullAccess), sent as turn/start `approvalPolicy`/`sandboxPolicy`
|
||||
(checked against codex 0.163.0's app-server schema).
|
||||
- OpenCode: build / plan agents, sent as the prompt's `agent` (v2 body and the v1
|
||||
native translation).
|
||||
|
||||
## App
|
||||
|
||||
`ChatModeControl` in the chat bar shows the row's `mode_name` without a request
|
||||
(client requests are serialized, so an eager read would delay history), and reads
|
||||
`chat_modes` only when tapped. Native sheet / action sheet with descriptions; a
|
||||
refusal stays in the picker. Accepted switches update the opened row.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Go: new tests for storage, Claude (spawn flag, live switch, default omits the
|
||||
flag), Codex turn overrides, OpenCode agent on v1/v2 prompts, server
|
||||
store/apply/restart. Full `go test ./...` passes except two tests that already fail
|
||||
on main in this environment (umask 077 file-permission checks, and
|
||||
`TestHumanRunAttentionNotification` picking up the host's real web URL).
|
||||
- App: `chat_mode_control_test.dart`; analyze clean; full suite 1,867 pass.
|
||||
- Browser: `tool/chat_mode_probe.mjs` (fixture gained chat_modes/chat_mode),
|
||||
Material and Cupertino at 1280: `build/chat-mode-probe/`.
|
||||
- Not verified against live Claude/Codex/OpenCode processes. The server isn't
|
||||
deployed yet and no device was used.
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/core/transport/pipelines_client.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_mode_control.dart';
|
||||
|
||||
class _ModeGateway implements ApiGateway {
|
||||
_ModeGateway({this.current = '', this.refuse, this.supported = true});
|
||||
|
||||
String current;
|
||||
final String? refuse;
|
||||
final bool supported;
|
||||
final requests = <JsonMap>[];
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
requests.add({'type': type, ...fields});
|
||||
if (!supported) throw ProtocolError('unknown request type');
|
||||
if (type == 'chat_modes') {
|
||||
return {
|
||||
'chat_modes': [
|
||||
{
|
||||
'id': 'default',
|
||||
'name': 'Ask for permission',
|
||||
'description': 'Ask first.',
|
||||
},
|
||||
{'id': 'plan', 'name': 'Plan', 'description': 'Plan only.'},
|
||||
{'id': 'auto', 'name': 'Auto', 'description': 'Act without asking.'},
|
||||
],
|
||||
'chat_mode': {'session_id': 's', 'mode': current},
|
||||
};
|
||||
}
|
||||
if (type == 'chat_mode') {
|
||||
final refused = refuse;
|
||||
if (refused != null) throw ProtocolError(refused);
|
||||
current = '${(fields['chat_mode'] as Map)['mode']}';
|
||||
return {
|
||||
'chat_mode': {'session_id': 's', 'mode': current},
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
Widget _material(
|
||||
ApiGateway gateway, {
|
||||
String mode = 'default',
|
||||
String name = 'Ask for permission',
|
||||
void Function(String, String)? onChanged,
|
||||
}) => MaterialApp(
|
||||
home: Scaffold(
|
||||
appBar: AppBar(
|
||||
actions: [
|
||||
ChatModeControl(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
mode: mode,
|
||||
modeName: name,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
void main() {
|
||||
testWidgets("shows the row's mode without a request and switches to Auto", (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModeGateway();
|
||||
final changes = <String>[];
|
||||
await tester.pumpWidget(
|
||||
_material(gateway, onChanged: (mode, name) => changes.add('$mode/$name')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
// The row names the mode; nothing is requested until the picker opens,
|
||||
// so the serialized transport never delays the transcript.
|
||||
expect(find.text('Ask for permission'), findsOneWidget);
|
||||
expect(gateway.requests, isEmpty);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-mode')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Act without asking.'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('chat-mode-option-auto')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byKey(const Key('chat-mode-sheet')), findsNothing);
|
||||
expect(gateway.requests.last, {
|
||||
'type': 'chat_mode',
|
||||
'chat_mode': {'session_id': 's', 'mode': 'auto'},
|
||||
});
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-mode')),
|
||||
matching: find.text('Auto'),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(changes, ['auto/Auto']);
|
||||
});
|
||||
|
||||
testWidgets('the stored mode is shown and checked', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
_material(
|
||||
_ModeGateway(current: 'plan'),
|
||||
mode: 'plan',
|
||||
name: 'Plan',
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Plan'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('chat-mode')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const ValueKey('chat-mode-option-plan')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a refusal keeps the picker open with the reason', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModeGateway(refuse: 'mode switch refused');
|
||||
await tester.pumpWidget(_material(gateway));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-mode')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('chat-mode-option-auto')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-mode-sheet')), findsOneWidget);
|
||||
expect(find.textContaining('mode switch refused'), findsOneWidget);
|
||||
expect(gateway.current, '');
|
||||
});
|
||||
|
||||
testWidgets('a row without a mode shows no control', (tester) async {
|
||||
await tester.pumpWidget(_material(_ModeGateway(), mode: '', name: ''));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-mode')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a failed mode list is reported in the picker', (tester) async {
|
||||
await tester.pumpWidget(_material(_ModeGateway(supported: false)));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-mode')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.textContaining('unknown request type'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('Cupertino uses a native action sheet', (tester) async {
|
||||
final gateway = _ModeGateway();
|
||||
await tester.pumpWidget(
|
||||
CupertinoApp(
|
||||
home: CupertinoPageScaffold(
|
||||
navigationBar: CupertinoNavigationBar(
|
||||
trailing: ChatModeControl(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
mode: 'default',
|
||||
modeName: 'Ask for permission',
|
||||
),
|
||||
),
|
||||
child: const SizedBox.shrink(),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('chat-mode')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CupertinoActionSheet), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('chat-mode-option-auto')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(CupertinoActionSheet), findsNothing);
|
||||
expect(gateway.current, 'auto');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Switches an open chat's permission mode in a real browser against a loopback
|
||||
// fixture, never operator data.
|
||||
// PROBE_WIDTH=1280 PROBE_HOST=material|cupertino node tool/chat_mode_probe.mjs <web-build> <out>
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
|
||||
import { once } from 'node:events';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { startFixture } from './runs_probe_server.mjs';
|
||||
import { launchChrome, waitForPort, waitForPage, connect, sleep } from './pipelines_probe_cdp_lib.mjs';
|
||||
import { axNodes, enableSemantics, waitFor, capture } from './pipelines_probe_cdp_input.mjs';
|
||||
|
||||
const width = Number(process.env.PROBE_WIDTH ?? 1280);
|
||||
const host = process.env.PROBE_HOST ?? 'material';
|
||||
const output = resolve(process.argv[3] ?? 'build/chat-mode-probe');
|
||||
await mkdir(output, { recursive: true });
|
||||
const messages = [
|
||||
{ id: 'u0', role: 'user', parts: [{ id: 'p0', type: 'text', text: 'Switch this chat to auto mode.' }] },
|
||||
{ id: 'a0', role: 'assistant', parts: [{ id: 'p1', type: 'text', text: 'Recorded fixture reply.' }] },
|
||||
];
|
||||
const fixture = await startFixture({ root: resolve(process.argv[2]), chatMessages: messages });
|
||||
const profile = await mkdtemp(join(tmpdir(), 'chat-mode-'));
|
||||
const chrome = launchChrome('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', profile, 'about:blank');
|
||||
const log = { width, host, checks: [], captures: [] };
|
||||
let c;
|
||||
const named = async (pattern) => (await axNodes(c)).filter((n) => pattern.test(n.name?.value ?? ''));
|
||||
const press = async (node) => {
|
||||
const { model } = await c.send('DOM.getBoxModel', { backendNodeId: node.backendDOMNodeId });
|
||||
const [x1, y1, , , x3, y3] = model.content;
|
||||
for (const type of ['mousePressed', 'mouseReleased']) {
|
||||
await c.send('Input.dispatchMouseEvent', { type, x: (x1 + x3) / 2, y: (y1 + y3) / 2, button: 'left', clickCount: 1 });
|
||||
}
|
||||
};
|
||||
const first = async (pattern, what) => {
|
||||
let found;
|
||||
assert.ok(await waitFor(async () => (found = (await named(pattern)).find((n) => n.backendDOMNodeId)), 30000), what);
|
||||
return found;
|
||||
};
|
||||
try {
|
||||
c = await connect((await waitForPage(await waitForPort(join(profile, 'DevToolsActivePort')))).webSocketDebuggerUrl);
|
||||
await c.send('Page.enable');
|
||||
if (host === 'cupertino') {
|
||||
await c.send('Emulation.setUserAgentOverride', {
|
||||
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15', platform: 'MacIntel',
|
||||
});
|
||||
} else {
|
||||
await c.send('Emulation.setUserAgentOverride', {
|
||||
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36', platform: 'Win32',
|
||||
});
|
||||
}
|
||||
await c.send('Emulation.setDeviceMetricsOverride', { width, height: 800, deviceScaleFactor: 1, mobile: false });
|
||||
await c.send('Page.navigate', { url: fixture.url + '/chat/ses_probechat' });
|
||||
assert.ok(await waitFor(() => c.evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 30000));
|
||||
await enableSemantics(c);
|
||||
await first(/Change mode\b.*Ask for permission/, 'mode control shows the row mode');
|
||||
await sleep(800);
|
||||
await capture(c, output, log, `${host}-mode-default`);
|
||||
log.checks.push('bar shows the stored/default mode before any chat_modes request');
|
||||
|
||||
await press(await first(/Change mode\b/, 'mode control'));
|
||||
await first(/^Auto/, 'Auto option');
|
||||
await sleep(600);
|
||||
await capture(c, output, log, `${host}-mode-picker`);
|
||||
await press(await first(/^Auto/, 'Auto option'));
|
||||
await first(/Change mode\b.*Auto/, 'bar shows Auto');
|
||||
await sleep(600);
|
||||
await capture(c, output, log, `${host}-mode-auto`);
|
||||
const state = await (await fetch(fixture.url + '/fixture/state')).json();
|
||||
assert.deepEqual(state.chatModeRequests, [{ session_id: 'ses_probechat', mode: 'auto' }]);
|
||||
log.checks.push('choosing Auto sent chat_mode and the bar shows Auto');
|
||||
console.log(JSON.stringify(log, null, 2));
|
||||
} catch (error) {
|
||||
if (c) {
|
||||
await capture(c, output, log, 'failure');
|
||||
await writeFile(join(output, 'failure-ax.json'), JSON.stringify(await axNodes(c), null, 2));
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await writeFile(join(output, `${host}-result.json`), JSON.stringify(log, null, 2));
|
||||
c?.close(); const exited = once(chrome, 'exit'); chrome.kill(); await exited;
|
||||
await fixture.close();
|
||||
}
|
||||
@@ -337,7 +337,18 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
kind: 'operator',
|
||||
directory: '/srv/probe',
|
||||
updated_at: '2026-10-21T12:00:00Z',
|
||||
backend: 'claude',
|
||||
mode: 'default',
|
||||
mode_name: 'Ask for permission',
|
||||
};
|
||||
const CHAT_MODES = [
|
||||
{ id: 'default', name: 'Ask for permission', description: 'Ask before edits and commands.' },
|
||||
{ id: 'acceptEdits', name: 'Accept edits', description: 'Make file edits without asking; ask for other actions.' },
|
||||
{ id: 'plan', name: 'Plan', description: 'Explore and plan without changing anything.' },
|
||||
{ id: 'auto', name: 'Auto', description: "Act without asking, with Claude Code's safety checks." },
|
||||
{ id: 'bypassPermissions', name: 'Bypass permissions', description: 'Never ask. Everything runs without checks.' },
|
||||
];
|
||||
const chatModeRequests = [];
|
||||
|
||||
const dropConnections = () => {
|
||||
for (const connection of connections) connection.close();
|
||||
@@ -394,6 +405,7 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
.writeHead(200, { 'content-type': 'application/json' })
|
||||
.end(JSON.stringify({
|
||||
subscribed,
|
||||
chatModeRequests,
|
||||
live,
|
||||
connections: connections.size,
|
||||
refuse,
|
||||
@@ -550,6 +562,23 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c
|
||||
setTimeout(() => client.send({ id: request.id, type: 'chat_prompt', chat_queued: chatRunning }), 300);
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_modes') {
|
||||
client.send({ id: request.id, type: 'chat_modes', chat_modes: CHAT_MODES,
|
||||
chat_mode: { session_id: CHAT_SESSION.id, mode: CHAT_SESSION.mode } });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_mode') {
|
||||
const mode = CHAT_MODES.find((entry) => entry.id === request.chat_mode?.mode);
|
||||
chatModeRequests.push(request.chat_mode);
|
||||
if (!mode) {
|
||||
client.send({ id: request.id, type: 'error', error: 'unknown Claude permission mode' });
|
||||
return;
|
||||
}
|
||||
CHAT_SESSION.mode = mode.id;
|
||||
CHAT_SESSION.mode_name = mode.name;
|
||||
client.send({ id: request.id, type: 'chat_mode', chat_mode: { session_id: CHAT_SESSION.id, mode: mode.id } });
|
||||
return;
|
||||
}
|
||||
if (request.type === 'chat_shells') {
|
||||
client.send({ id: request.id, type: 'chat_shells', chat_shells: [] });
|
||||
return;
|
||||
|
||||
@@ -171,6 +171,9 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
s.appliedModel = requested
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if err := s.applyMode(ctx, proc); err != nil {
|
||||
return err
|
||||
}
|
||||
content, err := promptContent(text, files)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -234,6 +234,7 @@ type session struct {
|
||||
directory string
|
||||
title string
|
||||
model string // CLI model selection (alias or full id); "" uses the CLI default
|
||||
mode string // permission mode id; "" uses the CLI's own default
|
||||
createdAt int64
|
||||
|
||||
proc *process
|
||||
|
||||
@@ -456,3 +456,58 @@ func TestSignedOutCLIReturnsAnActionableError(t *testing.T) {
|
||||
t.Fatalf("error is not actionable: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionModeStartsTheCLIAndSwitchesALiveOne(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
modeLog := filepath.Join(t.TempDir(), "modes.log")
|
||||
t.Setenv("FAKE_CLAUDE_MODE_LOG", modeLog)
|
||||
session := newCreatedChat(t, chat)
|
||||
ctx := context.Background()
|
||||
if err := chat.SetMode(ctx, session.ID, "dontAsk"); err == nil {
|
||||
t.Fatal("an unlisted mode was accepted")
|
||||
}
|
||||
modes, err := chat.Modes(ctx, session.ID)
|
||||
if err != nil || len(modes) != 5 || modes[0].ID != defaultMode || modes[3].ID != "auto" {
|
||||
t.Fatalf("modes: %+v %v", modes, err)
|
||||
}
|
||||
if err := chat.SetMode(ctx, session.ID, "auto"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(ctx, session.ID, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
entries := readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
|
||||
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "auto" {
|
||||
t.Fatalf("spawn did not start in the chosen mode: %+v", entries)
|
||||
}
|
||||
if _, err := os.Stat(modeLog); err == nil {
|
||||
t.Fatal("a process started in its mode was switched again")
|
||||
}
|
||||
|
||||
// A running CLI switches in place, without a restart.
|
||||
if err := chat.SetMode(ctx, session.ID, "plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if data, _ := os.ReadFile(modeLog); strings.TrimSpace(string(data)) != "plan" {
|
||||
t.Fatalf("live switch sent %q", data)
|
||||
}
|
||||
if count := len(readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))); count != len(entries) {
|
||||
t.Fatalf("the live switch restarted the CLI: %d spawns", count)
|
||||
}
|
||||
|
||||
// Back to the default: the flag is omitted on a fresh process.
|
||||
if err := chat.SetMode(ctx, session.ID, defaultMode); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat.session(session.ID).closeProcess()
|
||||
if err := chat.Prompt(ctx, session.ID, "again"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
entries = readArgs(t, os.Getenv("FAKE_CLAUDE_LOG"))
|
||||
if argValue(entries[len(entries)-1].Args, "--permission-mode") != "" {
|
||||
t.Fatalf("the default mode passed a flag: %+v", entries[len(entries)-1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// defaultMode is Claude Code's own ask-for-permission mode. The CLI flag has no
|
||||
// spelling for it, so a process in this mode is started without the flag; the
|
||||
// control request accepts it by name.
|
||||
const defaultMode = "default"
|
||||
|
||||
// chatModes are the Claude Code permission modes a chat can run in, in the
|
||||
// order the CLI cycles them. dontAsk is left out: it silently denies anything
|
||||
// not pre-approved, which a chat on a phone cannot recover from.
|
||||
var chatModes = []protocol.ChatMode{
|
||||
{ID: defaultMode, Name: "Ask for permission", Description: "Ask before edits and commands."},
|
||||
{ID: "acceptEdits", Name: "Accept edits", Description: "Make file edits without asking; ask for other actions."},
|
||||
{ID: "plan", Name: "Plan", Description: "Explore and plan without changing anything."},
|
||||
{ID: "auto", Name: "Auto", Description: "Act without asking, with Claude Code's safety checks."},
|
||||
{ID: "bypassPermissions", Name: "Bypass permissions", Description: "Never ask. Everything runs without checks."},
|
||||
}
|
||||
|
||||
// Modes lists the permission modes a Claude chat can switch to.
|
||||
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
|
||||
return append([]protocol.ChatMode(nil), chatModes...), nil
|
||||
}
|
||||
|
||||
func knownMode(mode string) bool {
|
||||
for _, known := range chatModes {
|
||||
if known.ID == mode {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetMode records the session's permission mode and applies it to a running
|
||||
// CLI at once; a later process starts in it.
|
||||
func (c *Chat) SetMode(ctx context.Context, id, mode string) error {
|
||||
if !knownMode(mode) {
|
||||
return fmt.Errorf("unknown Claude permission mode %q", mode)
|
||||
}
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
meta, ok := transcriptSession(id)
|
||||
if !ok {
|
||||
return errors.New("unknown Claude session " + id)
|
||||
}
|
||||
s = c.sessionFor(id, meta.Directory)
|
||||
}
|
||||
s.mu.Lock()
|
||||
previous := s.mode
|
||||
s.mode = mode
|
||||
proc := s.proc
|
||||
s.mu.Unlock()
|
||||
if proc == nil {
|
||||
return nil
|
||||
}
|
||||
if err := s.applyMode(ctx, proc); err != nil {
|
||||
s.mu.Lock()
|
||||
s.mode = previous
|
||||
s.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyMode tells a running CLI the session's mode when it runs in another.
|
||||
func (s *session) applyMode(ctx context.Context, proc *process) error {
|
||||
s.mu.Lock()
|
||||
requested, current := s.mode, proc.mode
|
||||
s.mu.Unlock()
|
||||
if requested == "" || requested == current || (current == "" && requested == defaultMode) {
|
||||
return nil
|
||||
}
|
||||
setCtx, cancel := context.WithTimeout(ctx, controlRequestTimeout)
|
||||
defer cancel()
|
||||
if _, err := proc.request(setCtx, "set_permission_mode", map[string]any{"mode": requested}); err != nil {
|
||||
return fmt.Errorf("switch Claude permission mode: %w", err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
proc.mode = requested
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
@@ -44,6 +44,10 @@ type process struct {
|
||||
exitErr error
|
||||
done chan struct{}
|
||||
stderrDone chan struct{}
|
||||
|
||||
// mode is the permission mode this process runs in, guarded by the
|
||||
// session's mu: set at spawn and after a confirmed set_permission_mode.
|
||||
mode string
|
||||
}
|
||||
|
||||
type controlReply struct {
|
||||
@@ -80,6 +84,12 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
if s.model != "" {
|
||||
args = append(args, "--model", s.model)
|
||||
}
|
||||
s.mu.Lock()
|
||||
mode := s.mode
|
||||
s.mu.Unlock()
|
||||
if mode != "" && mode != defaultMode {
|
||||
args = append(args, "--permission-mode", mode)
|
||||
}
|
||||
cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...)
|
||||
cmd.Dir = s.directory
|
||||
cmd.Env = s.chat.auth.resolve(s.chat.ctx, s.chat.binary, withServiceToken(os.Environ()))
|
||||
@@ -99,7 +109,7 @@ func (s *session) spawn(ctx context.Context) (*process, error) {
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, fmt.Errorf("start Claude Code: %w", err)
|
||||
}
|
||||
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{})}
|
||||
p := &process{session: s, cmd: cmd, stdin: stdin, pending: map[string]chan controlReply{}, done: make(chan struct{}), stderrDone: make(chan struct{}), mode: mode}
|
||||
go p.readStderr(stderr)
|
||||
go p.readStdout(stdout)
|
||||
go p.wait()
|
||||
|
||||
+8
-1
@@ -2,7 +2,8 @@
|
||||
"""Deterministic stand-in for the Claude Code CLI's SDK stdio protocol.
|
||||
|
||||
It implements only what Pipelines' adapter uses: initialize, stream-json turns,
|
||||
can_use_tool approvals, AskUserQuestion, set_model, interrupt, usage queries and
|
||||
can_use_tool approvals, AskUserQuestion, set_model, set_permission_mode,
|
||||
interrupt, usage queries and
|
||||
a session transcript. It never contacts a provider.
|
||||
"""
|
||||
import json
|
||||
@@ -157,6 +158,12 @@ def handle(line):
|
||||
elif subtype == "set_model":
|
||||
state["model"] = request.get("model")
|
||||
respond(value.get("request_id"), {"model": request.get("model")})
|
||||
elif subtype == "set_permission_mode":
|
||||
mode_log = os.environ.get("FAKE_CLAUDE_MODE_LOG")
|
||||
if mode_log:
|
||||
with open(mode_log, "a", encoding="utf-8") as log:
|
||||
log.write(request.get("mode", "") + "\n")
|
||||
respond(value.get("request_id"), {"mode": request.get("mode")})
|
||||
elif subtype == "interrupt":
|
||||
respond(value.get("request_id"), {"still_queued": [], "cancelled": []})
|
||||
if state["pending"]:
|
||||
|
||||
@@ -67,6 +67,7 @@ type Chat struct {
|
||||
endedTurns map[string]string
|
||||
usage map[string]usageSnapshot
|
||||
usageOrder uint64
|
||||
modes map[string]string
|
||||
}
|
||||
|
||||
type pendingForm struct {
|
||||
@@ -407,6 +408,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
|
||||
if model != "" {
|
||||
params["model"] = model
|
||||
}
|
||||
c.applyMode(id, params)
|
||||
c.mu.Lock()
|
||||
if c.starting == nil {
|
||||
c.starting = map[string]bool{}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// codexMode is one approval/sandbox preset, applied as turn/start overrides
|
||||
// that Codex keeps for the thread's later turns too.
|
||||
type codexMode struct {
|
||||
protocol.ChatMode
|
||||
approval string
|
||||
sandbox string
|
||||
}
|
||||
|
||||
// The presets mirror Codex's own: ask in the workspace sandbox (the thread
|
||||
// default chats start with), act without asking inside it, or full access.
|
||||
var codexModes = []codexMode{
|
||||
{protocol.ChatMode{ID: "ask", Name: "Ask for approval", Description: "Work in the project sandbox and ask when an action needs more."}, "on-request", "workspaceWrite"},
|
||||
{protocol.ChatMode{ID: "auto", Name: "Auto", Description: "Work in the project sandbox without asking."}, "never", "workspaceWrite"},
|
||||
{protocol.ChatMode{ID: "full", Name: "Full access", Description: "No sandbox and no approvals. Everything runs."}, "never", "dangerFullAccess"},
|
||||
}
|
||||
|
||||
// Modes lists the approval/sandbox presets a Codex chat can switch to.
|
||||
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
|
||||
modes := make([]protocol.ChatMode, len(codexModes))
|
||||
for index, mode := range codexModes {
|
||||
modes[index] = mode.ChatMode
|
||||
}
|
||||
return modes, nil
|
||||
}
|
||||
|
||||
// SetMode records the thread's preset; it is sent with the next turn/start.
|
||||
func (c *Chat) SetMode(_ context.Context, id, mode string) error {
|
||||
if _, ok := codexModeFor(mode); !ok {
|
||||
return fmt.Errorf("unknown Codex mode %q", mode)
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.modes == nil {
|
||||
c.modes = map[string]string{}
|
||||
}
|
||||
c.modes[id] = mode
|
||||
return nil
|
||||
}
|
||||
|
||||
func codexModeFor(id string) (codexMode, bool) {
|
||||
for _, mode := range codexModes {
|
||||
if mode.ID == id {
|
||||
return mode, true
|
||||
}
|
||||
}
|
||||
return codexMode{}, false
|
||||
}
|
||||
|
||||
// applyMode adds the thread's preset to turn/start params, if one was chosen.
|
||||
func (c *Chat) applyMode(id string, params map[string]any) {
|
||||
c.mu.Lock()
|
||||
chosen := c.modes[id]
|
||||
c.mu.Unlock()
|
||||
mode, ok := codexModeFor(chosen)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
params["approvalPolicy"] = mode.approval
|
||||
params["sandboxPolicy"] = map[string]any{"type": mode.sandbox}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestModePresetRidesOnTheNextTurn(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var turns []map[string]any
|
||||
chat := modelTestChat(t, func(method string, raw json.RawMessage) any {
|
||||
if method != "turn/start" {
|
||||
t.Errorf("unexpected operation: %s", method)
|
||||
return map[string]any{}
|
||||
}
|
||||
var params map[string]any
|
||||
_ = json.Unmarshal(raw, ¶ms)
|
||||
mu.Lock()
|
||||
turns = append(turns, params)
|
||||
mu.Unlock()
|
||||
return json.RawMessage(`{"turn":{"id":"turn-fixture","status":"inProgress","items":[]}}`)
|
||||
})
|
||||
ctx := context.Background()
|
||||
if err := chat.SetMode(ctx, fixtureThread, "yolo"); err == nil {
|
||||
t.Fatal("an unlisted mode was accepted")
|
||||
}
|
||||
if err := chat.Prompt(ctx, fixtureThread, "plain"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.SetMode(ctx, fixtureThread, "auto"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.Prompt(ctx, fixtureThread, "auto"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.SetMode(ctx, fixtureThread, "full"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.Prompt(ctx, fixtureThread, "full"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(turns) != 3 {
|
||||
t.Fatalf("turns = %d", len(turns))
|
||||
}
|
||||
if turns[0]["approvalPolicy"] != nil || turns[0]["sandboxPolicy"] != nil {
|
||||
t.Fatalf("no mode chosen, yet overrides were sent: %v", turns[0])
|
||||
}
|
||||
sandbox := func(turn map[string]any) any { return turn["sandboxPolicy"].(map[string]any)["type"] }
|
||||
if turns[1]["approvalPolicy"] != "never" || sandbox(turns[1]) != "workspaceWrite" {
|
||||
t.Fatalf("auto turn = %v", turns[1])
|
||||
}
|
||||
if turns[2]["approvalPolicy"] != "never" || sandbox(turns[2]) != "dangerFullAccess" {
|
||||
t.Fatalf("full turn = %v", turns[2])
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,8 @@ type Chat struct {
|
||||
mu sync.Mutex
|
||||
usageMu sync.Mutex
|
||||
usageModels map[string]usageModelCache
|
||||
modeMu sync.Mutex
|
||||
agents map[string]string
|
||||
}
|
||||
|
||||
// NewChat brokers chat for one owned OpenCode endpoint. The connection must be
|
||||
@@ -131,6 +133,9 @@ func (c *Chat) PromptWithMessageIDFiles(ctx context.Context, id, text, messageID
|
||||
if messageID != "" {
|
||||
body["id"] = messageID
|
||||
}
|
||||
if agent := c.agentFor(id); agent != "" {
|
||||
body["agent"] = agent
|
||||
}
|
||||
if len(files) > 0 {
|
||||
attachments := make([]map[string]string, 0, len(files))
|
||||
for _, file := range files {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatModes are OpenCode's two primary agents. What each may do without asking
|
||||
// is the agent's own permission configuration; Pipelines only picks the agent.
|
||||
var chatModes = []protocol.ChatMode{
|
||||
{ID: "build", Name: "Build", Description: "OpenCode's default agent: edits and runs commands under its permission settings."},
|
||||
{ID: "plan", Name: "Plan", Description: "Analyse and plan; edits and commands are restricted."},
|
||||
}
|
||||
|
||||
// Modes lists the agents an OpenCode chat can switch to.
|
||||
func (c *Chat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
|
||||
return append([]protocol.ChatMode(nil), chatModes...), nil
|
||||
}
|
||||
|
||||
// SetMode records the session's agent; every later prompt names it.
|
||||
func (c *Chat) SetMode(_ context.Context, id, mode string) error {
|
||||
known := false
|
||||
for _, candidate := range chatModes {
|
||||
known = known || candidate.ID == mode
|
||||
}
|
||||
if !known {
|
||||
return fmt.Errorf("unknown OpenCode agent %q", mode)
|
||||
}
|
||||
c.modeMu.Lock()
|
||||
defer c.modeMu.Unlock()
|
||||
if c.agents == nil {
|
||||
c.agents = map[string]string{}
|
||||
}
|
||||
c.agents[id] = mode
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Chat) agentFor(id string) string {
|
||||
c.modeMu.Lock()
|
||||
defer c.modeMu.Unlock()
|
||||
return c.agents[id]
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package opencode
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChosenAgentRidesOnEveryPrompt(t *testing.T) {
|
||||
for _, backend := range []string{"v2", "v1"} {
|
||||
t.Run(backend, func(t *testing.T) {
|
||||
var bodies []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
bodies = append(bodies, body)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
conn := &Connection{Backend: backend, URL: srv.URL, Directory: "/repo", models: map[string]map[string]string{}, responses: map[string][]byte{}}
|
||||
chat := NewChat(conn)
|
||||
ctx := context.Background()
|
||||
if err := chat.SetMode(ctx, "ses_1", "auto"); err == nil {
|
||||
t.Fatal("an unknown agent was accepted")
|
||||
}
|
||||
if err := chat.Prompt(ctx, "ses_1", "before"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.SetMode(ctx, "ses_1", "plan"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := chat.Prompt(ctx, "ses_1", "after"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(bodies) != 2 || bodies[0]["agent"] != nil || bodies[1]["agent"] != "plan" {
|
||||
t.Fatalf("prompt bodies = %v", bodies)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -199,6 +199,7 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
Prompt string `json:"prompt"`
|
||||
Text string `json:"text"`
|
||||
ID string `json:"id"`
|
||||
Agent string `json:"agent"`
|
||||
Format json.RawMessage `json:"format"`
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
@@ -226,6 +227,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([
|
||||
if request.ID != "" {
|
||||
payload["id"] = request.ID
|
||||
}
|
||||
if request.Agent != "" {
|
||||
payload["agent"] = request.Agent
|
||||
}
|
||||
if len(request.Format) > 0 {
|
||||
supported, err := c.supportsFormat(ctx, request.Format)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOperatorChatModeMigratesAndPersists(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "old.db")
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = db.Exec(`CREATE TABLE operator_sessions (session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL)`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.Close()
|
||||
store, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.RecordOperatorSession(ctx, "chat", "/fixture", "title", "operator"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode, err := store.ChatMode(ctx, "chat"); err != nil || mode != "" {
|
||||
t.Fatalf("fresh mode %q: %v", mode, err)
|
||||
}
|
||||
if err := store.SetChatMode(ctx, "missing", "auto"); err == nil {
|
||||
t.Fatal("unregistered chat accepted a mode")
|
||||
}
|
||||
before, _, err := store.OperatorSession(ctx, "chat")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetChatMode(ctx, "chat", "auto"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store.Close()
|
||||
store, err = Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if mode, err := store.ChatMode(ctx, "chat"); err != nil || mode != "auto" {
|
||||
t.Fatalf("restored mode %q: %v", mode, err)
|
||||
}
|
||||
if mode, err := store.ChatMode(ctx, "missing"); err != nil || mode != "" {
|
||||
t.Fatalf("missing chat mode %q: %v", mode, err)
|
||||
}
|
||||
after, _, err := store.OperatorSession(ctx, "chat")
|
||||
if err != nil || before.UpdatedAt != after.UpdatedAt {
|
||||
t.Fatal("mode changed recency", err)
|
||||
}
|
||||
}
|
||||
@@ -139,7 +139,7 @@ func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to strin
|
||||
// row valid and open (0), so an upgrade is idempotent across repeated Open calls
|
||||
// and no session is silently reported as closed.
|
||||
func (s *Store) migrateOperatorSessions() error {
|
||||
for _, column := range []string{"chat_model", "chat_model_provider"} {
|
||||
for _, column := range []string{"chat_model", "chat_model_provider", "chat_mode"} {
|
||||
if err := s.addColumnIfMissing("operator_sessions", column, "TEXT NOT NULL DEFAULT ''"); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -183,6 +183,34 @@ func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model s
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetChatMode stores one operator chat's permission mode. The harness validates
|
||||
// the mode id; this only records it for later turns and restarts.
|
||||
func (s *Store) SetChatMode(ctx context.Context, id, mode string) error {
|
||||
result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_mode=? WHERE session_id=? AND tag<>''`, mode, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count != 1 {
|
||||
return errors.New("a mode can only be set on a registered operator chat")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChatMode reads one operator chat's stored mode without touching recency; ""
|
||||
// when none was chosen or the session is not an operator chat.
|
||||
func (s *Store) ChatMode(ctx context.Context, id string) (string, error) {
|
||||
var mode string
|
||||
err := s.db.QueryRowContext(ctx, `SELECT chat_mode FROM operator_sessions WHERE session_id=? AND tag<>''`, id).Scan(&mode)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", nil
|
||||
}
|
||||
return mode, err
|
||||
}
|
||||
|
||||
// ChatModelSelection reads a durable next-turn choice without touching recency.
|
||||
func (s *Store) ChatModelSelection(ctx context.Context, id string) (provider, model string, err error) {
|
||||
err = s.db.QueryRowContext(ctx, `SELECT chat_model_provider,chat_model FROM operator_sessions WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, id).Scan(&provider, &model)
|
||||
|
||||
@@ -51,6 +51,13 @@ const (
|
||||
ChatModels = "chat_models"
|
||||
// ChatModelSelect switches one session's model for subsequent turns.
|
||||
ChatModelSelect = "chat_model"
|
||||
// ChatModes lists the permission modes the chat's harness offers (Claude
|
||||
// Code's permission modes, Codex approval/sandbox presets, OpenCode agents);
|
||||
// its request body is ChatQuery and the reply also carries the current mode.
|
||||
ChatModes = "chat_modes"
|
||||
// ChatModeSelect switches one session's mode. The choice is stored with the
|
||||
// operator session and applied now and before every later turn.
|
||||
ChatModeSelect = "chat_mode"
|
||||
// ChatStar records the operator's star on the server, so every browser and
|
||||
// device shows the same starred group. It takes a ChatQuery with SessionID
|
||||
// and Starred, and echoes the updated session like close/reopen.
|
||||
@@ -169,6 +176,19 @@ type ChatModel struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// ChatMode is one permission mode a chat harness offers.
|
||||
type ChatMode struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
// ChatModeRequest switches one session's mode; the reply echoes the stored mode.
|
||||
type ChatModeRequest struct {
|
||||
SessionID string `json:"session_id"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
// ChatModelRequest switches the model for one session's subsequent turns.
|
||||
type ChatModelRequest struct {
|
||||
// Selection is reply-only: next_turn means a durable local override was saved.
|
||||
@@ -186,6 +206,12 @@ type ChatSession struct {
|
||||
// ModelSelection == next_turn denotes a durable Pipelines override, not an
|
||||
// acknowledgement that a remote thread's current configuration changed.
|
||||
ModelSelection string `json:"model_selection,omitempty"`
|
||||
// Mode is the stored permission mode (a ChatMode id); empty is the
|
||||
// harness's own default.
|
||||
Mode string `json:"mode,omitempty"`
|
||||
// ModeName is Mode's display name. With no stored mode both name the
|
||||
// harness default, so a client can show the mode without a chat_modes read.
|
||||
ModeName string `json:"mode_name,omitempty"`
|
||||
// InstructionStatus is the observed create-time preload outcome: applied,
|
||||
// unsupported, failed, or not_requested. Ordinary list rows omit it.
|
||||
InstructionStatus string `json:"instruction_status,omitempty"`
|
||||
|
||||
@@ -210,6 +210,11 @@ type Message struct {
|
||||
ChatModels []ChatModel `json:"chat_models,omitempty"`
|
||||
// ModelRequest is the chat_model body and echoed selection.
|
||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||
// harness offers, with the session's current mode in ModeRequest.
|
||||
ChatModes []ChatMode `json:"chat_modes,omitempty"`
|
||||
// ModeRequest is the chat_mode body and echoed selection.
|
||||
ModeRequest *ChatModeRequest `json:"chat_mode,omitempty"`
|
||||
// ChatSubscribe attaches this connection to one session's shared stream; the
|
||||
// body names the session like ChatQuery. A chat_prompt response sets
|
||||
// ChatQueued when the prompt had to wait for an in-flight turn and was
|
||||
|
||||
@@ -203,6 +203,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatModelSelect:
|
||||
handleChatModelSwitch(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatModes:
|
||||
handleChatModes(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatModeSelect:
|
||||
handleChatModeSwitch(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatShells:
|
||||
handleChatShells(ctx, request, broker, registry, write)
|
||||
return true
|
||||
|
||||
@@ -179,6 +179,9 @@ func (m *chatManager) PromptWithMessageID(ctx context.Context, sessionID, text,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.applyStoredMode(ctx, adapter, sessionID); err != nil {
|
||||
return err
|
||||
}
|
||||
if isModelBackend(m.backendFor(ctx, sessionID)) {
|
||||
model, err := m.promptModel(ctx, adapter, sessionID)
|
||||
if err != nil {
|
||||
@@ -231,6 +234,9 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.applyStoredMode(ctx, adapter, sessionID); err != nil {
|
||||
return err
|
||||
}
|
||||
if isModelBackend(m.backendFor(ctx, sessionID)) {
|
||||
model, err := m.promptModel(ctx, adapter, sessionID)
|
||||
if err != nil {
|
||||
@@ -349,6 +355,7 @@ func (m *chatManager) chatModelSelection(ctx context.Context, id string) (string
|
||||
}
|
||||
|
||||
func (m *chatManager) withModelSelection(ctx context.Context, session protocol.ChatSession) (protocol.ChatSession, error) {
|
||||
session = m.withMode(ctx, session)
|
||||
if !isModelBackend(session.Backend) {
|
||||
return session, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatModer is the optional permission-mode surface of a chat harness.
|
||||
type chatModer interface {
|
||||
Modes(ctx context.Context, sessionID string) ([]protocol.ChatMode, error)
|
||||
SetMode(ctx context.Context, sessionID, mode string) error
|
||||
}
|
||||
|
||||
// chatModeRegistry stores each operator chat's chosen mode.
|
||||
type chatModeRegistry interface {
|
||||
SetChatMode(ctx context.Context, id, mode string) error
|
||||
ChatMode(ctx context.Context, id string) (string, error)
|
||||
}
|
||||
|
||||
var errChatModesUnsupported = errors.New("this chat harness does not support changing modes")
|
||||
|
||||
// Modes lists the modes the session's harness offers.
|
||||
func (m *chatManager) Modes(ctx context.Context, sessionID string) ([]protocol.ChatMode, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
moder, ok := adapter.(chatModer)
|
||||
if !ok {
|
||||
return nil, errChatModesUnsupported
|
||||
}
|
||||
return moder.Modes(ctx, sessionID)
|
||||
}
|
||||
|
||||
// SetMode applies a mode to the harness now and stores it, so it survives a
|
||||
// restart and is re-applied before every later turn.
|
||||
func (m *chatManager) SetMode(ctx context.Context, sessionID, mode string) error {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
moder, ok := adapter.(chatModer)
|
||||
if !ok {
|
||||
return errChatModesUnsupported
|
||||
}
|
||||
registry, ok := m.registry.(chatModeRegistry)
|
||||
if !ok {
|
||||
return errors.New("durable chat modes are not configured")
|
||||
}
|
||||
if err := moder.SetMode(ctx, sessionID, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.SetChatMode(ctx, sessionID, mode)
|
||||
}
|
||||
|
||||
// CurrentMode is the session's stored mode, "" for the harness default.
|
||||
func (m *chatManager) CurrentMode(ctx context.Context, sessionID string) string {
|
||||
registry, ok := m.registry.(chatModeRegistry)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
mode, err := registry.ChatMode(ctx, sessionID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return mode
|
||||
}
|
||||
|
||||
// withMode names the session's mode on a listed row: the stored mode, else the
|
||||
// harness default (listed first). A harness without modes leaves both empty.
|
||||
func (m *chatManager) withMode(ctx context.Context, session protocol.ChatSession) protocol.ChatSession {
|
||||
moder, ok := m.adapter(session.Backend).(chatModer)
|
||||
if !ok {
|
||||
return session
|
||||
}
|
||||
modes, err := moder.Modes(ctx, session.ID)
|
||||
if err != nil || len(modes) == 0 {
|
||||
return session
|
||||
}
|
||||
stored := m.CurrentMode(ctx, session.ID)
|
||||
chosen := modes[0]
|
||||
for _, mode := range modes {
|
||||
if mode.ID == stored {
|
||||
chosen = mode
|
||||
}
|
||||
}
|
||||
session.Mode, session.ModeName = chosen.ID, chosen.Name
|
||||
return session
|
||||
}
|
||||
|
||||
// applyStoredMode hands the stored mode to the harness before a turn. Adapters
|
||||
// treat a repeat as a no-op, and this covers a server restart that lost the
|
||||
// adapter's in-memory choice.
|
||||
func (m *chatManager) applyStoredMode(ctx context.Context, adapter chatBroker, sessionID string) error {
|
||||
moder, ok := adapter.(chatModer)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
mode := m.CurrentMode(ctx, sessionID)
|
||||
if mode == "" {
|
||||
return nil
|
||||
}
|
||||
return moder.SetMode(ctx, sessionID, mode)
|
||||
}
|
||||
|
||||
// handleChatModes lists a session's modes and reports the current one.
|
||||
func handleChatModes(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
moder, ok := broker.(chatModer)
|
||||
if !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errChatModesUnsupported.Error()})
|
||||
return
|
||||
}
|
||||
modes, err := moder.Modes(ctx, query.SessionID)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
current := protocol.ChatModeRequest{SessionID: query.SessionID}
|
||||
if reporter, ok := broker.(interface {
|
||||
CurrentMode(context.Context, string) string
|
||||
}); ok {
|
||||
current.Mode = reporter.CurrentMode(ctx, query.SessionID)
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatModes, ID: request.ID, ChatModes: modes, ModeRequest: ¤t})
|
||||
}
|
||||
|
||||
// handleChatModeSwitch changes one session's mode and echoes the stored mode.
|
||||
func handleChatModeSwitch(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
body := request.ModeRequest
|
||||
if body == nil || !validChatSessionID(body.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
mode := strings.TrimSpace(body.Mode)
|
||||
if mode == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a mode is required"})
|
||||
return
|
||||
}
|
||||
moder, ok := broker.(chatModer)
|
||||
if !ok {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: errChatModesUnsupported.Error()})
|
||||
return
|
||||
}
|
||||
if err := moder.SetMode(ctx, body.SessionID, mode); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
reply := protocol.ChatModeRequest{SessionID: body.SessionID, Mode: mode}
|
||||
_ = write(protocol.Message{Type: protocol.ChatModeSelect, ID: request.ID, ModeRequest: &reply})
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// modedChat records the modes the manager hands to the harness.
|
||||
type modedChat struct {
|
||||
*fakeChat
|
||||
applied []string
|
||||
}
|
||||
|
||||
func (c *modedChat) Modes(context.Context, string) ([]protocol.ChatMode, error) {
|
||||
return []protocol.ChatMode{{ID: "default", Name: "Ask"}, {ID: "auto", Name: "Auto"}}, nil
|
||||
}
|
||||
|
||||
func (c *modedChat) SetMode(_ context.Context, _, mode string) error {
|
||||
if mode != "default" && mode != "auto" {
|
||||
return errors.New("unknown mode " + mode)
|
||||
}
|
||||
c.applied = append(c.applied, mode)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestChatModeIsStoredAppliedAndSurvivesRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "chat.db")
|
||||
store, err := pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := "01900000-0000-7000-8000-000000000002"
|
||||
if err := store.RecordOperatorSession(ctx, id, "/fixture", "chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, id, "claude"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fake := &modedChat{fakeChat: scriptedChat()}
|
||||
fake.sessionRecord = protocol.ChatSession{ID: id, Backend: "claude"}
|
||||
fake.sessionFound = true
|
||||
fake.sessions = []protocol.ChatSession{fake.sessionRecord}
|
||||
manager := &chatManager{claude: fake, registry: store, cache: map[string]string{}}
|
||||
var reply protocol.Message
|
||||
capture := func(msg protocol.Message) error { reply = msg; return nil }
|
||||
|
||||
if session, _, err := manager.Session(ctx, id); err != nil || session.Mode != "default" || session.ModeName != "Ask" {
|
||||
t.Fatalf("fresh session names %q/%q, want the harness default: %v", session.Mode, session.ModeName, err)
|
||||
}
|
||||
handleChatModes(ctx, protocol.Message{ID: "list", ChatQuery: &protocol.ChatQuery{SessionID: id}}, manager, capture)
|
||||
if reply.Type != protocol.ChatModes || len(reply.ChatModes) != 2 || reply.ModeRequest == nil || reply.ModeRequest.Mode != "" {
|
||||
t.Fatalf("modes reply = %+v", reply)
|
||||
}
|
||||
handleChatModeSwitch(ctx, protocol.Message{ID: "bad", ModeRequest: &protocol.ChatModeRequest{SessionID: id, Mode: "yolo"}}, manager, capture)
|
||||
if reply.Type != protocol.Error {
|
||||
t.Fatalf("unknown mode accepted: %+v", reply)
|
||||
}
|
||||
handleChatModeSwitch(ctx, protocol.Message{ID: "auto", ModeRequest: &protocol.ChatModeRequest{SessionID: id, Mode: "auto"}}, manager, capture)
|
||||
if reply.Type != protocol.ChatModeSelect || reply.ModeRequest.Mode != "auto" || len(fake.applied) != 1 {
|
||||
t.Fatalf("switch reply = %+v, applied %v", reply, fake.applied)
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = pipeline.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
|
||||
// A restarted server forgot the harness state; the stored mode is listed and
|
||||
// re-applied before the next turn.
|
||||
fake.applied = nil
|
||||
manager = &chatManager{claude: fake, registry: store, cache: map[string]string{}}
|
||||
session, found, err := manager.Session(ctx, id)
|
||||
if err != nil || !found || session.Mode != "auto" || session.ModeName != "Auto" {
|
||||
t.Fatalf("restarted session = %+v, %v", session, err)
|
||||
}
|
||||
list, err := manager.Sessions(ctx)
|
||||
if err != nil || len(list) != 1 || list[0].Mode != "auto" {
|
||||
t.Fatalf("restarted list = %+v, %v", list, err)
|
||||
}
|
||||
handleChatModes(ctx, protocol.Message{ID: "again", ChatQuery: &protocol.ChatQuery{SessionID: id}}, manager, capture)
|
||||
if reply.ModeRequest == nil || reply.ModeRequest.Mode != "auto" {
|
||||
t.Fatalf("current mode after restart = %+v", reply)
|
||||
}
|
||||
if err := manager.Prompt(ctx, id, "hello"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := manager.PromptWithMessageIDFiles(ctx, id, "again", "msg", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(fake.applied) != 2 || fake.applied[0] != "auto" || fake.applied[1] != "auto" {
|
||||
t.Fatalf("stored mode not re-applied before turns: %v", fake.applied)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user