Merge branch 'worktree-agent-af57ebcee7c17abd6'

This commit is contained in:
2026-11-25 20:55:44 +00:00
24 changed files with 924 additions and 23 deletions
@@ -3,7 +3,8 @@ import 'package:flutter/material.dart';
import '../domain/chat_commands.dart';
/// The command palette above the composer: the recorded commands matching the
/// slash word, each with its own `/name` and summary.
/// slash word, each with its own `/name` and summary, then the session's
/// harness commands and skills with their argument hint and description.
///
/// Rows are standard Material `ListTile`s, so typography, colours and text
/// scaling stay the theme's. The list is content-sized and never imposes a fixed height;
@@ -52,8 +53,22 @@ class ChatCommandPalette extends StatelessWidget {
ListTile(
key: ValueKey<String>('chat-command-${commands[index].name}'),
selected: index == selectedIndex,
title: Text('/${commands[index].name}'),
subtitle: Text(commands[index].summary),
title: Text(
commands[index].fromHarness
? commands[index].usage
: '/${commands[index].name}',
),
// A skill's description can run to a paragraph; two lines
// identify it without crowding the list.
subtitle: commands[index].summary.isEmpty
? null
: Text(
commands[index].summary,
maxLines: commands[index].fromHarness ? 2 : null,
overflow: commands[index].fromHarness
? TextOverflow.ellipsis
: null,
),
onTap: () => onSelected(commands[index]),
),
],
@@ -20,6 +20,7 @@ import 'chat_command_actions.dart';
import 'chat_command_palette.dart';
import 'chat_composer_controller.dart';
import 'chat_composer_paste_focus.dart';
import 'chat_harness_command_loader.dart';
import '../ui/transcript/chat_attachment_frame.dart';
import '../../../ui/adaptive/glass_bar.dart';
import '../../../ui/adaptive/glass_pill.dart';
@@ -107,9 +108,11 @@ const String chatQueuedNotice =
/// A leading `/` opens the recorded command palette
/// above the field: rows are filtered by name prefix, Up/Down move the
/// highlight, Enter or a tap completes the highlighted command, Escape closes
/// the palette. A slash draft is never handed to the prompt path: `/new`,
/// the palette. The session's harness commands and skills follow the recorded
/// ones; a draft naming one is sent as an ordinary prompt for the harness to
/// expand. No other slash draft is handed to the prompt path: `/new`,
/// `/close` and `/rename` run through [commands], `/stop` and `/help` run
/// locally or through the existing Stop path; text naming no recorded command
/// locally or through the existing Stop path; text naming no known command
/// becomes the web client's local no-send report with its explicit "Send as
/// message" offer. Picked files are memory-only chips:
/// their names are shown with the host's own remove action and the bounded
@@ -135,8 +138,15 @@ class ChatComposerBar extends StatefulWidget {
this.images,
this.chatColor,
this.limitBanner,
this.loadHarnessCommands,
});
/// Loads the session's harness commands and skills (`chat_commands`), which
/// the palette offers after the recorded commands. Choosing one inserts
/// `/<name> ` and sending passes the draft to the harness as a prompt. Null
/// (no session) offers the recorded commands alone.
final Future<List<ChatCommand>> Function()? loadHarnessCommands;
/// Builds the usage-limit banner above the pill (see
/// ChatUsageLimitBanner); it is handed this bar's own send, so a scheduled
/// draft carries its files and clears the composer as Send does.
@@ -224,6 +234,11 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// The highlighted command row, wrapped to the filtered list on each build.
int _selectedCommand = 0;
/// The session's harness commands, loaded on the first slash draft.
late final ChatHarnessCommandLoader _harness = ChatHarnessCommandLoader(
widget.loadHarnessCommands,
);
/// The local no-send report shown under the field. Every slash draft takes
/// this path instead of the prompt, as the web client records: an unknown
/// command carries [_commandOffer] back for an explicit "Send as message".
@@ -422,15 +437,24 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// the first send; only a partial word is completed first.
bool _paletteCompletes() =>
_paletteCommands().isNotEmpty &&
chatCommandNamed(widget.composer.draft) == null;
chatCommandNamed(widget.composer.draft) == null &&
chatHarnessCommandNamed(widget.composer.draft, _harness.commands) == null;
/// The recorded commands matching the current draft while the palette is
/// open. A dismissed or completed draft keeps its palette closed until the
/// operator types something newer.
/// The recorded and harness commands matching the current draft while the
/// palette is open. A dismissed or completed draft keeps its palette closed
/// until the operator types something newer.
List<ChatCommand> _paletteCommands() {
final draft = widget.composer.draft;
if (_paletteClosedFor == draft) return const <ChatCommand>[];
return chatCommandSuggestions(draft);
return chatCommandSuggestions(draft, _harness.commands);
}
/// Asks for the harness commands once a draft opens the palette.
void _requestHarnessCommands(String draft) {
if (chatCommandQuery(draft) == null) return;
_harness.request(() {
if (mounted) setState(() {});
});
}
/// Mirrors the typed text into the composer after clearing the per-keystroke
@@ -438,7 +462,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// report, and resets the highlight when the filtered list no longer holds it
/// (the web client's `refreshComposerControls`).
void _onDraftEdited(String value) {
final suggestions = chatCommandSuggestions(value);
_requestHarnessCommands(value);
final suggestions = chatCommandSuggestions(value, _harness.commands);
setState(() {
_paletteClosedFor = null;
_dismissCommandReport();
@@ -622,6 +647,12 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
}
return;
}
// A session skill or harness command is the harness's to expand: the
// draft goes out as an ordinary prompt, argument and all.
if (chatHarnessCommandNamed(draft, _harness.commands) != null) {
unawaited(_send());
return;
}
final offer = draft.trim();
setState(() {
_commandFailed = true;
@@ -691,11 +722,11 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
await _send();
}
/// Puts the chosen recorded command in the composer and closes the palette.
/// Nothing is sent to the agent: selecting a command is completion, not an
/// execution path (this slice adds the palette, not the command actions).
/// Puts the chosen command in the composer and closes the palette. Nothing
/// is sent to the agent: selecting a command is completion, not an execution
/// path. A harness command is followed by a space, ready for its arguments.
void _completeCommand(ChatCommand command) {
final text = '/${command.name}';
final text = command.fromHarness ? '/${command.name} ' : '/${command.name}';
setState(() {
_paletteClosedFor = text;
_selectedCommand = 0;
@@ -0,0 +1,57 @@
import 'dart:async';
import '../domain/chat_commands.dart';
/// Loads the session's harness commands (skills) for the composer palette the
/// first time a slash draft asks for them, and keeps them once found.
///
/// An empty reply is not final: the server answers at once from what it knows
/// and starts the session's CLI in the background, so the commands may arrive
/// on a later ask. An empty or failed load is retried after [retryAfter] on the
/// next slash draft; meanwhile the palette offers the recorded commands alone.
class ChatHarnessCommandLoader {
ChatHarnessCommandLoader(
this._load, {
this.retryAfter = const Duration(seconds: 3),
});
final Future<List<ChatCommand>> Function()? _load;
final Duration retryAfter;
List<ChatCommand> _commands = const <ChatCommand>[];
bool _loading = false;
DateTime? _lastEmpty;
/// The commands loaded so far, empty until a load found some.
List<ChatCommand> get commands => _commands;
/// Starts a load unless commands are known, one is running, or the last one
/// came back empty too recently; [onLoaded] runs when commands arrive.
void request(void Function() onLoaded) {
final load = _load;
if (load == null || _commands.isNotEmpty || _loading) return;
final lastEmpty = _lastEmpty;
if (lastEmpty != null &&
DateTime.now().difference(lastEmpty) < retryAfter) {
return;
}
_loading = true;
unawaited(() async {
try {
final commands = await load();
if (commands.isEmpty) {
_lastEmpty = DateTime.now();
return;
}
_commands = List<ChatCommand>.unmodifiable(commands);
onLoaded();
} catch (_) {
// The palette's recorded commands still work, and a typed skill can
// still be sent through the unknown-command offer.
_lastEmpty = DateTime.now();
} finally {
_loading = false;
}
}());
}
}
@@ -13,6 +13,7 @@ import '../data/chat_attachment_images.dart';
import '../data/chat_repository.dart';
import '../domain/chat_activity_detail.dart';
import '../domain/chat_notice.dart';
import '../domain/chat_harness_commands.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_colors.dart';
import '../../../core/transport/pipelines_client.dart'
@@ -1241,6 +1242,9 @@ class _ChatThreadViewState extends State<ChatThreadView> {
composer: _composer,
running: _controller.running,
commands: _commandActions(),
loadHarnessCommands: () async => chatHarnessCommandsFromWire(
await ChatRepository(widget.gateway).commands(widget.sessionId),
),
picker: widget.attachmentPicker,
images: _images,
placeholder: chatComposerPlaceholderFor(
@@ -32,6 +32,21 @@ class ChatRepository {
return value is List ? _maps(value) : const [];
}
/// The slash commands and skills the session's harness offers
/// (`chat_commands`), in the server's order. A harness without any replies
/// with no list, which is an empty catalog.
Future<List<JsonMap>> commands(String sessionId) async {
final session = sessionId.trim();
if (session.isEmpty) {
throw ArgumentError('Select a chat session first.');
}
final reply = await gateway.call('chat_commands', {
'chat_query': {'session_id': session},
});
final value = reply['chat_commands'];
return value is List ? _maps(value) : const [];
}
Future<JsonMap> selectModel(String sessionId, String provider, String model) {
final session = sessionId.trim();
if (session.isEmpty) {
@@ -13,12 +13,24 @@ class ChatCommand {
required this.summary,
required this.usage,
this.takesArgument = false,
this.fromHarness = false,
});
/// A slash command or skill the session's harness reported (`chat_commands`).
/// The client never runs it: the draft `/<name> args` is sent as an ordinary
/// prompt and the harness expands it.
const ChatCommand.harness({
required this.name,
required this.summary,
required this.usage,
}) : takesArgument = true,
fromHarness = true;
final String name;
final String summary;
final String usage;
final bool takesArgument;
final bool fromHarness;
}
const String chatCommandNew = 'new';
@@ -79,16 +91,51 @@ String? chatCommandQuery(String draft) {
}
/// The recorded commands matching [draft], filtered case-insensitively by name
/// prefix. Empty when no palette should show.
List<ChatCommand> chatCommandSuggestions(String draft) {
/// prefix, then the session's [harness] commands (skills) matching it. A
/// harness command named like a recorded one is shadowed: the client's own
/// command runs. A namespaced harness name (`plugin:skill`) also matches on
/// the part after its colon. Empty when no palette should show.
List<ChatCommand> chatCommandSuggestions(
String draft, [
List<ChatCommand> harness = const <ChatCommand>[],
]) {
final query = chatCommandQuery(draft);
if (query == null) return const <ChatCommand>[];
return <ChatCommand>[
for (final command in chatCommands)
if (command.name.toLowerCase().startsWith(query)) command,
for (final command in harness)
if (!_isRecorded(command.name) && _harnessMatches(command.name, query))
command,
];
}
bool _isRecorded(String name) {
final lower = name.toLowerCase();
return chatCommands.any((command) => command.name == lower);
}
bool _harnessMatches(String name, String query) {
final lower = name.toLowerCase();
if (lower.startsWith(query)) return true;
final colon = lower.lastIndexOf(':');
return colon >= 0 && lower.substring(colon + 1).startsWith(query);
}
/// The session [harness] command [draft]'s slash word names exactly
/// (case-insensitive), or null. A recorded command of the same name wins, so
/// this is asked only after [chatCommandNamed] found none.
ChatCommand? chatHarnessCommandNamed(String draft, List<ChatCommand> harness) {
final word = chatCommandWord(draft);
if (word == null) return null;
final name = word.substring(1).toLowerCase();
if (_isRecorded(name)) return null;
for (final command in harness) {
if (command.name.toLowerCase() == name) return command;
}
return null;
}
/// The slash word [draft] starts with, including its `/`, or null when the
/// draft does not start with one. Only the first word counts, so an argument
/// (`/rename My chat`) still names `/rename`.
@@ -0,0 +1,27 @@
import '../../../core/api_gateway.dart';
import 'chat_commands.dart';
/// The session's harness commands from a `chat_commands` reply list: each
/// entry's `name`, `description` and `argument_hint`. Entries without a usable
/// single-word name are skipped and duplicates keep their first entry, in the
/// server's order. A harness without commands yields an empty list.
List<ChatCommand> chatHarnessCommandsFromWire(List<JsonMap> entries) {
final seen = <String>{};
final commands = <ChatCommand>[];
for (final entry in entries) {
var name = '${entry['name'] ?? ''}'.trim();
if (name.startsWith('/')) name = name.substring(1);
if (name.isEmpty || name.contains(RegExp(r'\s'))) continue;
if (!seen.add(name.toLowerCase())) continue;
final description = '${entry['description'] ?? ''}'.trim();
final hint = '${entry['argument_hint'] ?? ''}'.trim();
commands.add(
ChatCommand.harness(
name: name,
summary: description,
usage: hint.isEmpty ? '/$name' : '/$name $hint',
),
);
}
return commands;
}
+39
View File
@@ -0,0 +1,39 @@
# Chat harness commands and skills in the slash palette
User request (2026-11-25): the chat should offer every skill / slash command the
operator's Claude Code has (bundled ones like `code-review`, `~/.claude/skills`,
plugin and claude.ai-synced skills) with no import step.
## Verified live (Claude Code 2.1.332, haiku, scratch dir, no persistence)
- The `initialize` control response carries `commands: [{name, description,
argumentHint}]` (80 entries here): skills of every source, with the source in
the description (`(user)`, `(claude.ai sync)`, `(dynamic workflow)`), and the
CLI's own commands. It arrives before any turn.
- The `system`/`init` line (only after the first user message) has
`slash_commands`, `skills` (names only), `plugins` and
`terminal_slash_commands` (`doctor`, `color`, `focus`, `reload-plugins`).
- A stream-json user message `/probe-skill banana` expanded a project skill;
`/code-review low` ran the bundled skill (as a forked subagent, final answer on
the main thread); `/import-memory` resolved to `anthropic-skills:import-memory`.
So sending the slash text as an ordinary prompt is the supported path.
## Server
`chat_commands` (ChatQuery → `chat_commands: [{name, description,
argument_hint}]`). Claude parses the initialize commands (dropping `__…`
internals and duplicates), removes `terminal_slash_commands` once the init line
names them, and never waits for a CLI: without a live CLI it answers from the
latest list a CLI in the same directory reported and starts the CLI in the
background. Codex, OpenCode and Pi reply with an empty list (not implemented).
## App
The composer asks for `chat_commands` on the first slash draft (retrying an
empty reply after 3 s) and lists them after the recorded commands, filtered by
prefix (a `plugin:skill` name also matches on `skill`). A harness name equal to
a recorded command is shadowed. Choosing one inserts `/<name> `; sending a draft
whose slash word is a harness command goes out as an ordinary prompt. Unknown
slash words still get the local "Send as message" offer.
Unverified: rendered browser capture of the palette; device behaviour.
@@ -18,10 +18,15 @@ class ComposerBarGateway implements ApiGateway {
Future<JsonMap> Function()? interrupt;
Future<JsonMap> Function()? stopTasks;
/// The `chat_commands` reply list: the session's harness commands.
List<JsonMap> commands = const [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type: type, fields: fields));
switch (type) {
case 'chat_commands':
return <String, dynamic>{'chat_commands': commands};
case 'chat_subscribe':
return <String, dynamic>{};
case 'chat_messages':
@@ -0,0 +1,59 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_harness_command_loader.dart';
import 'package:pipelines_app/features/chat/domain/chat_commands.dart';
const _skill = ChatCommand.harness(
name: 'probe-skill',
summary: 'Probe',
usage: '/probe-skill',
);
void main() {
test('an empty reply is retried and found commands are kept', () async {
final replies = <List<ChatCommand>>[
const [],
const [_skill],
];
var calls = 0;
var loaded = 0;
final loader = ChatHarnessCommandLoader(() async {
calls += 1;
return replies.removeAt(0);
}, retryAfter: Duration.zero);
loader.request(() => loaded += 1);
await pumpEventQueue();
expect(loader.commands, isEmpty);
expect(loaded, 0);
loader.request(() => loaded += 1);
await pumpEventQueue();
expect(loader.commands.single.name, 'probe-skill');
expect(loaded, 1);
loader.request(() => loaded += 1);
await pumpEventQueue();
expect(calls, 2);
});
test('a recent empty or failed load is not asked again at once', () async {
var calls = 0;
final loader = ChatHarnessCommandLoader(() async {
calls += 1;
throw StateError('offline');
}, retryAfter: const Duration(hours: 1));
loader.request(() {});
await pumpEventQueue();
loader.request(() {});
await pumpEventQueue();
expect(calls, 1);
expect(loader.commands, isEmpty);
});
test('a host without a loader offers nothing', () async {
final loader = ChatHarnessCommandLoader(null);
loader.request(() => fail('no load'));
await pumpEventQueue();
expect(loader.commands, isEmpty);
});
}
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'chat_composer_bar_fixtures.dart';
/// Desktop keyboard: Enter sends.
final _desktop = TargetPlatformVariant.only(TargetPlatform.linux);
void main() {
late ComposerBarGateway gateway;
late int sequence;
setUp(() {
gateway = ComposerBarGateway()
..page = fixtureTurn()
..commands = [
{
'name': 'code-review',
'description': 'Review the current diff',
'argument_hint': '[low|high]',
},
{'name': 'probe-skill', 'description': 'Probe skill (user)'},
{'name': 'anthropic-skills:pdf', 'description': 'PDF files'},
// Shadowed by the client's own /rename.
{'name': 'rename', 'description': 'Rename the conversation'},
];
sequence = 0;
});
tearDown(() => gateway.close());
Future<void> pumpComposer(WidgetTester tester) async {
await tester.pumpWidget(
composerThread(gateway, newOperationId: () => 'op/${++sequence}'),
);
await tester.pumpAndSettle();
}
Finder field() => find.byKey(const Key('chat-composer-field'));
Finder row(String name) => find.byKey(ValueKey<String>('chat-command-$name'));
Future<void> type(WidgetTester tester, String text) async {
await tester.enterText(field(), text);
await tester.pumpAndSettle();
}
testWidgets(
'the palette offers session skills after the recorded commands',
(tester) async {
await pumpComposer(tester);
await type(tester, '/');
final commandCalls = gateway.calls.where(
(call) => call.type == 'chat_commands',
);
expect(commandCalls, hasLength(1));
expect(commandCalls.single.fields['chat_query'], {
'session_id': isNotEmpty,
});
expect(row('new'), findsOneWidget);
expect(row('code-review'), findsOneWidget);
expect(row('probe-skill'), findsOneWidget);
expect(find.text('/code-review [low|high]'), findsOneWidget);
expect(find.text('Review the current diff'), findsOneWidget);
// The client's /rename wins over the harness's.
expect(row('rename'), findsOneWidget);
expect(find.text('Rename the conversation'), findsNothing);
final help = tester.getTopLeft(row('help')).dy;
expect(tester.getTopLeft(row('code-review')).dy, greaterThan(help));
await type(tester, '/co');
expect(row('code-review'), findsOneWidget);
expect(row('close'), findsNothing);
expect(row('probe-skill'), findsNothing);
// A namespaced skill matches on its own name too.
await type(tester, '/pd');
expect(row('anthropic-skills:pdf'), findsOneWidget);
// The list is fetched once, not per keystroke.
expect(
gateway.calls.where((call) => call.type == 'chat_commands'),
hasLength(1),
);
},
variant: _desktop,
);
testWidgets(
'choosing a skill inserts it with a space and sending prompts the harness',
(tester) async {
await pumpComposer(tester);
await type(tester, '/prob');
await tester.tap(row('probe-skill'));
await tester.pumpAndSettle();
expect(fieldText(tester), '/probe-skill ');
expect(gateway.promptBodies, isEmpty);
await type(tester, '/probe-skill banana');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(gateway.promptBodies.single['text'], '/probe-skill banana');
expect(find.textContaining('is not a command'), findsNothing);
},
variant: _desktop,
);
testWidgets(
'Enter completes a partial skill name, then a whole name sends',
(tester) async {
await pumpComposer(tester);
await type(tester, '/code-r');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(fieldText(tester), '/code-review ');
expect(gateway.promptBodies, isEmpty);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(gateway.promptBodies.single['text'], '/code-review');
},
variant: _desktop,
);
testWidgets('a slash word the harness does not list still asks first', (
tester,
) async {
await pumpComposer(tester);
await type(tester, '/nope now');
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(gateway.promptBodies, isEmpty);
expect(find.textContaining('is not a command'), findsOneWidget);
}, variant: _desktop);
testWidgets('a harness without commands offers the recorded ones alone', (
tester,
) async {
gateway.commands = const [];
await pumpComposer(tester);
await type(tester, '/');
expect(row('new'), findsOneWidget);
expect(row('code-review'), findsNothing);
}, variant: _desktop);
}
@@ -0,0 +1,67 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_commands.dart';
import 'package:pipelines_app/features/chat/domain/chat_harness_commands.dart';
void main() {
final harness = chatHarnessCommandsFromWire([
{
'name': 'code-review',
'description': ' Review the diff ',
'argument_hint': '[low|high]',
},
{'name': '/probe-skill'},
{'name': 'anthropic-skills:pdf', 'description': 'PDF'},
{'name': 'Code-Review', 'description': 'duplicate'},
{'name': 'two words'},
{'name': ''},
{'name': 'help', 'description': 'shadowed'},
]);
test('wire entries become harness commands with usage and summary', () {
expect(harness.map((command) => command.name), [
'code-review',
'probe-skill',
'anthropic-skills:pdf',
'help',
]);
final review = harness.first;
expect(review.fromHarness, isTrue);
expect(review.takesArgument, isTrue);
expect(review.summary, 'Review the diff');
expect(review.usage, '/code-review [low|high]');
expect(harness[1].usage, '/probe-skill');
expect(chatHarnessCommandsFromWire(const []), isEmpty);
});
test('suggestions list recorded commands first, then matching skills', () {
final all = chatCommandSuggestions('/', harness);
expect(all.take(chatCommands.length), chatCommands);
expect(all.skip(chatCommands.length).map((command) => command.name), [
'code-review',
'probe-skill',
'anthropic-skills:pdf',
]);
expect(chatCommandSuggestions('/CODE', harness).single.name, 'code-review');
expect(
chatCommandSuggestions('/pdf', harness).single.name,
'anthropic-skills:pdf',
);
expect(chatCommandSuggestions('/code-review x', harness), isEmpty);
// Without harness commands the recorded list is unchanged.
expect(chatCommandSuggestions('/'), chatCommands);
});
test('a harness command is named only when no recorded command is', () {
expect(
chatHarnessCommandNamed('/code-review low', harness)?.name,
'code-review',
);
expect(
chatHarnessCommandNamed('/Probe-Skill', harness)?.name,
'probe-skill',
);
expect(chatHarnessCommandNamed('/help', harness), isNull);
expect(chatHarnessCommandNamed('/code', harness), isNull);
expect(chatHarnessCommandNamed('plain', harness), isNull);
});
}
+7
View File
@@ -121,6 +121,9 @@ type Chat struct {
// so a listed row names its levels without starting a CLI.
catalogMu sync.Mutex
catalog []protocol.ChatModel
// commandCatalog is the latest slash-command list per directory
// (commands.go), guarded by catalogMu.
commandCatalog map[string][]protocol.ChatCommand
}
func New(ctx context.Context) *Chat {
@@ -369,6 +372,10 @@ type session struct {
account accountIdentity
prompts []promptRecord
models []protocol.ChatModel
// commands are the slash commands the live CLI's initialize listed;
// terminalCommands are those its init line marks terminal-only (commands.go).
commands []protocol.ChatCommand
terminalCommands map[string]bool
// model is the requested selection; modelActual is the model the CLI last
// reported for a message. appliedModel is what the live process was told.
+120
View File
@@ -0,0 +1,120 @@
package claude
import (
"context"
"encoding/json"
"errors"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// parseInitializeCommands reads the slash commands Claude Code's initialize
// response lists: bundled skills (code-review), ~/.claude and project skills,
// plugin and claude.ai-synced skills, and the CLI's own commands, each with its
// description and argument hint. The operator sends "/<name> args" as an
// ordinary prompt and the CLI expands it. Internal entries ("__…") and
// duplicates are dropped; a response without commands yields none.
func parseInitializeCommands(raw json.RawMessage) []protocol.ChatCommand {
var reply struct {
Commands []struct {
Name string `json:"name"`
Description string `json:"description"`
ArgumentHint string `json:"argumentHint"`
} `json:"commands"`
}
if len(raw) == 0 || json.Unmarshal(raw, &reply) != nil {
return nil
}
seen := map[string]bool{}
commands := make([]protocol.ChatCommand, 0, len(reply.Commands))
for _, c := range reply.Commands {
name := strings.TrimPrefix(strings.TrimSpace(c.Name), "/")
if name == "" || strings.HasPrefix(name, "_") || strings.ContainsAny(name, " \t\r\n") || seen[name] {
continue
}
seen[name] = true
commands = append(commands, protocol.ChatCommand{
Name: name,
Description: strings.TrimSpace(c.Description),
ArgumentHint: strings.TrimSpace(c.ArgumentHint),
})
}
return commands
}
// noteTerminalCommands records the commands the CLI's init line reports as
// terminal-only (terminal_slash_commands): they do nothing in a stream-json
// session, so the chat does not offer them.
func (s *session) noteTerminalCommands(names []string) {
if len(names) == 0 {
return
}
s.mu.Lock()
s.terminalCommands = map[string]bool{}
for _, name := range names {
s.terminalCommands[strings.TrimPrefix(name, "/")] = true
}
directory, commands := s.directory, s.commandsLocked()
s.mu.Unlock()
s.chat.rememberCommands(directory, commands)
}
// rememberCommands keeps the newest command list a CLI in directory reported,
// so a chat there lists commands before its own CLI has started.
func (c *Chat) rememberCommands(directory string, commands []protocol.ChatCommand) {
if commands == nil {
return
}
c.catalogMu.Lock()
defer c.catalogMu.Unlock()
if c.commandCatalog == nil {
c.commandCatalog = map[string][]protocol.ChatCommand{}
}
c.commandCatalog[directory] = append([]protocol.ChatCommand(nil), commands...)
}
func (c *Chat) cachedCommands(directory string) []protocol.ChatCommand {
c.catalogMu.Lock()
defer c.catalogMu.Unlock()
return append([]protocol.ChatCommand(nil), c.commandCatalog[directory]...)
}
// commandsLocked is the session's offered commands. Callers hold s.mu.
func (s *session) commandsLocked() []protocol.ChatCommand {
commands := make([]protocol.ChatCommand, 0, len(s.commands))
for _, c := range s.commands {
if !s.terminalCommands[c.Name] {
commands = append(commands, c)
}
}
return commands
}
// Commands lists the slash commands and skills the session's CLI loaded at the
// initialize handshake. It never waits for a CLI to start: requests on a
// connection are answered in order, and a cold start would stall them. With no
// live CLI it starts one in the background (the next prompt needs it anyway)
// and answers from the list a CLI in the same directory last reported, empty
// when none has; the client asks again later.
func (c *Chat) Commands(_ context.Context, id string) ([]protocol.ChatCommand, error) {
s := c.session(id)
if s == nil {
return nil, errors.New("unknown Claude session " + id)
}
s.mu.Lock()
live := s.proc != nil
commands := s.commandsLocked()
directory := s.directory
s.mu.Unlock()
if live {
return commands, nil
}
go func() {
ctx, cancel := context.WithTimeout(c.ctx, initializeTimeout+5*time.Second)
defer cancel()
_, _ = s.ensureProcess(ctx)
}()
return c.cachedCommands(directory), nil
}
+110
View File
@@ -0,0 +1,110 @@
package claude
import (
"context"
"encoding/json"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestInitializeCommandsKeepNamesDescriptionsAndHints(t *testing.T) {
commands := parseInitializeCommands(json.RawMessage(`{"commands":[
{"name":"code-review","description":"Review the current diff","argumentHint":"[low|high]"},
{"name":" /docs ","description":" Docs (claude.ai sync) ","argumentHint":""},
{"name":"","description":"nameless"},
{"name":"two words","description":"bad"},
{"name":"__remote-workflow","description":"internal"},
{"name":"code-review","description":"duplicate"}]}`))
want := []protocol.ChatCommand{
{Name: "code-review", Description: "Review the current diff", ArgumentHint: "[low|high]"},
{Name: "docs", Description: "Docs (claude.ai sync)"},
}
if len(commands) != len(want) {
t.Fatalf("commands = %+v", commands)
}
for i := range want {
if commands[i] != want[i] {
t.Fatalf("command %d = %+v, want %+v", i, commands[i], want[i])
}
}
if got := parseInitializeCommands(json.RawMessage(`{"models":[]}`)); len(got) != 0 {
t.Fatalf("no commands field = %+v", got)
}
if got := parseInitializeCommands(nil); got != nil {
t.Fatalf("empty init = %+v", got)
}
}
// The chat lists the CLI's initialize commands and, once the init line names
// terminal-only commands, stops offering them. A slash prompt reaches the CLI
// verbatim, so the CLI expands the skill.
func TestClaudeCommandsComeFromInitializeAndSkipTerminalOnly(t *testing.T) {
chat := testChat(t)
session := newCreatedChat(t, chat)
ctx := context.Background()
names := func(commands []protocol.ChatCommand) []string {
out := []string{}
for _, c := range commands {
out = append(out, c.Name)
}
return out
}
// No CLI runs yet: the list is empty at once and the CLI starts in the
// background, so a later ask has its commands.
commands, err := chat.Commands(ctx, session.ID)
if err != nil || len(commands) != 0 {
t.Fatalf("commands before any CLI = %v, %v", names(commands), err)
}
eventually(t, "commands after the background start", func() bool {
commands, err = chat.Commands(ctx, session.ID)
return err == nil && len(commands) > 0
})
if got := names(commands); len(got) != 3 || got[0] != "code-review" || got[1] != "probe-skill" || got[2] != "color" {
t.Fatalf("commands before init = %v", got)
}
if commands[0].ArgumentHint != "[low|high] [<pr#>]" || commands[0].Description != "Review the current diff" {
t.Fatalf("code-review = %+v", commands[0])
}
frames := subscribe(t, chat, session.ID)
if err := chat.Prompt(ctx, session.ID, "/probe-skill banana"); err != nil {
t.Fatal(err)
}
waitStepEnded(t, frames)
commands, err = chat.Commands(ctx, session.ID)
if err != nil {
t.Fatal(err)
}
if got := names(commands); len(got) != 2 || got[0] != "code-review" || got[1] != "probe-skill" {
t.Fatalf("commands after init = %v", got)
}
// Another chat in the same directory lists them before its CLI starts.
other, err := chat.Create(ctx, "other", session.Directory)
if err != nil {
t.Fatal(err)
}
if got, _ := chat.Commands(ctx, other.ID); len(got) != 2 {
t.Fatalf("same-directory cached commands = %v", names(got))
}
eventually(t, "other chat's CLI", func() bool {
s := chat.session(other.ID)
s.mu.Lock()
defer s.mu.Unlock()
return s.proc != nil
})
eventually(t, "transcript", func() bool { return sessionTranscriptPath(session.ID) != "" })
page, err := chat.Messages(ctx, session.ID, 50, "")
if err != nil {
t.Fatal(err)
}
if len(page.Messages) == 0 || len(page.Messages[0].Parts) != 1 || page.Messages[0].Parts[0].Text != "/probe-skill banana" {
t.Fatalf("slash prompt did not reach the CLI verbatim: %+v", page.Messages)
}
}
func TestClaudeCommandsRejectUnknownSession(t *testing.T) {
chat := testChat(t)
if _, err := chat.Commands(context.Background(), "missing"); err == nil {
t.Fatal("unknown session listed commands")
}
}
+3
View File
@@ -249,6 +249,7 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
p.link.tasksIncomplete.Store(status.Tasks == nil && status.Base > 0)
p.stderr.WriteString(status.Stderr)
p.models, p.account, p.appliedModel = models, account, status.Model
p.commands = parseInitializeCommands(status.Init)
p.automations = status.Automations
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true, tasks: status.Tasks}
for _, pending := range status.Pending {
@@ -267,6 +268,8 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
// Callers hold s.mu.
func (s *session) adoptLocked(p *process) {
s.models, s.account = p.models, p.account
s.commands = p.commands
s.chat.rememberCommands(s.directory, s.commandsLocked())
s.chat.rememberCatalog(p.models)
s.appliedModel = p.appliedModel
if p.automations != nil {
+8 -4
View File
@@ -63,6 +63,7 @@ type process struct {
// models, account and appliedModel carry an attached host's
// initialize state until the session adopts it.
models []protocol.ChatModel
commands []protocol.ChatCommand
account accountIdentity
appliedModel string
automations *claudehost.AutomationSnapshot
@@ -167,13 +168,15 @@ func (s *session) spawnOnce(ctx context.Context) (*process, error) {
// before any user turn so an approval is never silently denied.
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
defer cancel()
models, account, err := p.initialize(initCtx)
models, account, commands, err := p.initialize(initCtx)
if err != nil {
p.close()
return nil, err
}
s.mu.Lock()
s.models = models
s.commands = commands
s.chat.rememberCommands(s.directory, s.commandsLocked())
s.account = account
s.chat.rememberCatalog(models)
s.lastErr = ""
@@ -211,7 +214,7 @@ func (s *session) startDirect(args []string, mode string, env []string) (*proces
return p, nil
}
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, []protocol.ChatCommand, error) {
raw, err := p.request(ctx, "initialize", map[string]any{
"hooks": map[string]any{"Stop": []any{map[string]any{
"hookCallbackIds": []string{claudehost.NativeAutomationCallbackID},
@@ -219,9 +222,10 @@ func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, account
}}},
})
if err != nil {
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
return nil, accountIdentity{}, nil, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
}
return parseInitialize(raw)
models, account, err := parseInitialize(raw)
return models, account, parseInitializeCommands(raw), err
}
// parseInitialize reads the CLI's initialize response: its model catalog and
+9 -2
View File
@@ -70,7 +70,8 @@ def user_message(text):
append({"type": "user", "uuid": "user-%d" % state["turn"], "timestamp": stamp(),
"message": {"role": "user", "content": [{"type": "text", "text": text}]}})
send({"type": "system", "subtype": "init", "session_id": state["session"],
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd()})
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd(),
"terminal_slash_commands": ["color"]})
message_id = "msg_fake_%d" % state["turn"]
if "gate" in text:
gated(message_id)
@@ -218,7 +219,13 @@ def handle(line):
"supportsEffort": True, "supportedEffortLevels": ["low", "medium", "high", "max"]},
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
],
"commands": [], "agents": [],
"commands": [
{"name": "code-review", "description": "Review the current diff", "argumentHint": "[low|high] [<pr#>]"},
{"name": "probe-skill", "description": "Probe skill (user)", "argumentHint": ""},
{"name": "color", "description": "Set the prompt bar color", "argumentHint": "[red|blue]"},
{"name": "__remote-workflow", "description": "internal", "argumentHint": ""},
{"name": "code-review", "description": "duplicate", "argumentHint": ""},
], "agents": [],
"account": {"email": "fixture@example.invalid", "organization": "Fixture Org",
"subscriptionType": "max", "apiProvider": "firstParty"},
})
+4
View File
@@ -42,6 +42,9 @@ type lineEnvelope struct {
IsMeta bool `json:"isMeta"`
// RateLimitInfo is the payload of a rate_limit_event line (see quota.go).
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
// TerminalSlashCommands, on a system init line, names the commands that
// only work in the interactive terminal (see commands.go).
TerminalSlashCommands []string `json:"terminal_slash_commands"`
}
type contentBlock struct {
@@ -648,6 +651,7 @@ func (s *session) handleSystem(envelope lineEnvelope) {
case "init":
// The CLI re-emits init at each turn; keep only the authoritative identity.
s.adoptFollowUpTurn()
s.noteTerminalCommands(envelope.TerminalSlashCommands)
if envelope.SessionID != "" && envelope.SessionID != s.id {
s.mu.Lock()
s.lastErr = "Claude Code opened unexpected session " + envelope.SessionID
+14
View File
@@ -67,6 +67,10 @@ const (
// ChatModels lists the models the chat's harness can switch to; its request
// body is ChatQuery (the session id).
ChatModels = "chat_models"
// ChatCommands lists the slash commands and skills the chat's harness
// session offers; its request body is ChatQuery (the session id). A harness
// that reports none replies with an empty list.
ChatCommands = "chat_commands"
// ChatModelSelect switches one session's model for subsequent turns.
ChatModelSelect = "chat_model"
// ChatModes lists the permission modes the chat's harness offers (Claude
@@ -267,6 +271,16 @@ const (
ChatMessageKindNotice = "notice"
)
// ChatCommand is one slash command or skill the chat's harness session offers.
// Name is the word after the slash; the operator sends "/<Name> <args>" as an
// ordinary prompt and the harness expands it. ArgumentHint is the harness's
// usage hint for the arguments, if any.
type ChatCommand struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
ArgumentHint string `json:"argument_hint,omitempty"`
}
// ChatModel is one model the current chat harness can switch to. ID is the
// provider's model id, Provider its provider id, Name the harness's display name.
type ChatModel struct {
+2
View File
@@ -248,6 +248,8 @@ type Message struct {
ChatBackends []string `json:"chat_backends,omitempty"`
// ChatModels is the chat_models reply: models the session's harness offers.
ChatModels []ChatModel `json:"chat_models,omitempty"`
// ChatCommands is the chat_commands reply: the session's slash commands.
ChatCommands []ChatCommand `json:"chat_commands,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
+3
View File
@@ -250,6 +250,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatModels:
handleChatModels(ctx, request, broker, write)
return true
case protocol.ChatCommands:
handleChatCommands(ctx, request, broker, write)
return true
case protocol.ChatModelSelect:
handleChatModelSwitch(ctx, request, broker, write)
return true
+46
View File
@@ -0,0 +1,46 @@
package server
import (
"context"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// chatCommander is the optional slash-command surface of a chat harness:
// the skills and commands its session loaded, which the operator invokes by
// sending "/<name> args" as an ordinary prompt. Claude Code implements it; a
// harness without one offers an empty list rather than an error.
type chatCommander interface {
Commands(ctx context.Context, sessionID string) ([]protocol.ChatCommand, error)
}
// Commands lists the slash commands the session's harness offers.
func (m *chatManager) Commands(ctx context.Context, sessionID string) ([]protocol.ChatCommand, error) {
adapter, err := m.brokerFor(ctx, sessionID)
if err != nil {
return nil, err
}
commander, ok := adapter.(chatCommander)
if !ok {
return nil, nil
}
return commander.Commands(ctx, sessionID)
}
// handleChatCommands answers chat_commands with the session's slash commands.
func handleChatCommands(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
}
var commands []protocol.ChatCommand
if commander, ok := broker.(chatCommander); ok {
var err error
if commands, err = commander.Commands(ctx, query.SessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
}
_ = write(protocol.Message{Type: protocol.ChatCommands, ID: request.ID, ChatCommands: commands})
}
@@ -0,0 +1,68 @@
package server
import (
"context"
"encoding/json"
"path/filepath"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// commandChat is a harness that reports its session's slash commands.
type commandChat struct {
*fakeChat
asked []string
}
func (c *commandChat) Commands(_ context.Context, id string) ([]protocol.ChatCommand, error) {
c.asked = append(c.asked, id)
return []protocol.ChatCommand{{Name: "code-review", Description: "Review the diff", ArgumentHint: "[low|high]"}, {Name: "probe-skill"}}, nil
}
func TestChatCommandsRouteToTheSessionHarness(t *testing.T) {
ctx := context.Background()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
claudeID := "01900000-0000-7000-8000-000000000011"
codexID := "01900000-0000-7000-8000-000000000012"
for id, backend := range map[string]string{claudeID: "claude", codexID: "codex"} {
if err := store.RecordOperatorSession(ctx, id, "/fixture", "chat", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.SetOperatorSessionBackend(ctx, id, backend); err != nil {
t.Fatal(err)
}
}
claude := &commandChat{fakeChat: scriptedChat()}
manager := &chatManager{claude: claude, codex: scriptedChat(), registry: store, cache: map[string]string{}}
var reply protocol.Message
capture := func(msg protocol.Message) error { reply = msg; return nil }
handleChatCommands(ctx, protocol.Message{ID: "c1", ChatQuery: &protocol.ChatQuery{SessionID: claudeID}}, manager, capture)
if reply.Type != protocol.ChatCommands || reply.ID != "c1" || len(reply.ChatCommands) != 2 || len(claude.asked) != 1 || claude.asked[0] != claudeID {
t.Fatalf("claude reply = %+v, asked %v", reply, claude.asked)
}
wire, err := json.Marshal(reply)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(wire), `"chat_commands":[{"name":"code-review","description":"Review the diff","argument_hint":"[low|high]"},{"name":"probe-skill"}]`) {
t.Fatalf("wire = %s", wire)
}
// A harness without commands answers with an empty list, not an error.
handleChatCommands(ctx, protocol.Message{ID: "c2", ChatQuery: &protocol.ChatQuery{SessionID: codexID}}, manager, capture)
if reply.Type != protocol.ChatCommands || reply.ID != "c2" || len(reply.ChatCommands) != 0 {
t.Fatalf("codex reply = %+v", reply)
}
handleChatCommands(ctx, protocol.Message{ID: "c3", ChatQuery: &protocol.ChatQuery{SessionID: "not a session"}}, manager, capture)
if reply.Type != protocol.Error {
t.Fatalf("invalid id reply = %+v", reply)
}
}