diff --git a/lib/kernel/claude_code/claude_code_kernel.dart b/lib/kernel/claude_code/claude_code_kernel.dart index ef562c8a8..586455dae 100644 --- a/lib/kernel/claude_code/claude_code_kernel.dart +++ b/lib/kernel/claude_code/claude_code_kernel.dart @@ -38,6 +38,7 @@ import 'claude_numbers.dart'; import 'claude_sdk_tools.dart'; import 'turn_stats.dart'; import 'control_channel.dart'; +import 'forked_runs.dart'; import 'local_time_zone.dart'; import 'tool_result_tally.dart'; import 'usage_limit.dart'; @@ -139,12 +140,15 @@ class ClaudeCodeKernel _usageOffBy = usageOffBy ?? _usageOn, _providers = providers ?? ModelProviders.current, _providerEnvironment = providerEnvironment ?? providerLaunchEnvironment { - _translator = ClaudeTranslator( - emit: emit, - nextSeq: () => nextSeq, - goalSaid: _syncGoal, - ownModel: _ownModel, - ); + _translator = + ClaudeTranslator( + emit: emit, + nextSeq: () => nextSeq, + goalSaid: _syncGoal, + ownModel: _ownModel, + ) + ..onForkedCommand = _followForked + ..onForkedCommandEnded = _forkedEnded; _providers.addListener(_providersChanged); ExtensionSwitches.changes?.addListener(_applySwitches); _live.add(this); @@ -327,6 +331,42 @@ class ClaudeCodeKernel /// kept when null. This machine's sessions only. static TurnStats? turnStats; + /// Where a skill run from a slash command is read as it goes (main.dart + /// sets it); not read, shown once done, when null (see [ForkedRuns]). + static ForkedRuns? forkedRuns; + + /// The runs read as they go, by their messages' parent. + final Map _followedRuns = {}; + + /// The environment the CLI last started with, besides the machine's: + /// where it keeps its sessions may be in it. + Map? _launchEnv; + + /// Reads the run [command] as it goes: this machine's sessions only. + void _followForked(String command) { + final runs = forkedRuns; + final session = _sessionId; + if (runs == null || session == null || _remoteHost != null) return; + _followedRuns.remove(command)?.cancel(); + _followedRuns[command] = runs.watch( + cwd: _cwd, + sessionId: session, + env: _launchEnv, + onLine: (line) { + if (!_disposed) _translator.forkedLine(command, line); + }, + ); + } + + void _forkedEnded(String command) => _followedRuns.remove(command)?.finish(); + + void _stopFollowing() { + for (final run in _followedRuns.values) { + run.cancel(); + } + _followedRuns.clear(); + } + /// [turnStats] for this session's history: none for a remote one's. TurnStats? get _turnStats => _remoteHost == null ? turnStats : null; @@ -625,6 +665,7 @@ class ClaudeCodeKernel _contextReported = false; _appliedSwitches = ExtensionSwitches.current(); final sdkServers = ClaudeSdkTools.serversFor(_cwd); + _launchEnv = env; final transport = await _start( _launched = ClaudeLaunch( cwd: _cwd, @@ -952,6 +993,7 @@ class ClaudeCodeKernel ExtensionSwitches.changes?.removeListener(_applySwitches); _live.remove(this); _cancelSdkCalls(); + _stopFollowing(); _teardown(); closeEvents(); } diff --git a/lib/kernel/claude_code/claude_code_translator.dart b/lib/kernel/claude_code/claude_code_translator.dart index 2f278544c..742bebb70 100644 --- a/lib/kernel/claude_code/claude_code_translator.dart +++ b/lib/kernel/claude_code/claude_code_translator.dart @@ -147,6 +147,16 @@ class ClaudeTranslator { /// own (`context: fork`), by the id its messages give as their parent /// (`forked-command-`): no call started it (see [_forkedSkill]). final Map _forkedCommands = {}; + + /// Told of a skill run from a slash command as it starts, and as it ends, + /// by its messages' parent (`forked-command-`): its messages may be + /// read as it goes ([forkedLine]), the CLI sending them only once done. + void Function(String command)? onForkedCommand; + void Function(String command)? onForkedCommandEnded; + + /// Those whose messages came as they went ([forkedLine]): the same, sent + /// all at once at the end, are not shown again. + final Set _followed = {}; final Set _denied = {}; /// Calls made and not answered yet: those of a stopped turn never are. @@ -364,6 +374,10 @@ class ClaudeTranslator { void translate(Map message) { final given = message['parent_tool_use_id'] as String?; + if (_followed.contains(given) && + (message['type'] == 'assistant' || message['type'] == 'user')) { + return; + } final parent = _forkedCommands[given] ?? given; switch (message['type']) { case 'stream_event' when parent == null: @@ -2056,7 +2070,9 @@ class ClaudeTranslator { if (call == null) { if (description == null || !description.startsWith('/')) return null; id = taskId; - _forkedCommands['forked-command-${description.substring(1)}'] = id; + final command = 'forked-command-${description.substring(1)}'; + _forkedCommands[command] = id; + if (!replaying) onForkedCommand?.call(command); } else if (skill?.name == 'Skill') { id = call; } else { @@ -2075,6 +2091,21 @@ class ClaudeTranslator { return id; } + /// A line the subagent of the skill run from a slash command [command] + /// wrote, as it went (see [onForkedCommand]): into its card. + void forkedLine(String command, Map line) { + final card = _forkedCommands[command]; + if (card == null) return; + switch (line['type']) { + case 'assistant': + _followed.add(command); + _assistant(line, card); + case 'user': + _followed.add(command); + _user(line, card); + } + } + /// The subagent [toolUseId] started, if one did, now runs on its own. void _agentToBackground(String? toolUseId) { final agent = toolUseId == null ? null : _agents[toolUseId]; @@ -2110,6 +2141,9 @@ class ClaudeTranslator { String? outputFile, Map usage = const {}, }) { + for (final MapEntry(key: command, value: card) in _forkedCommands.entries) { + if (card == taskId) onForkedCommandEnded?.call(command); + } if (_tasks[taskId] case final task?) { _tasks[taskId] = task.copyWith( status: status, diff --git a/lib/kernel/claude_code/forked_runs.dart b/lib/kernel/claude_code/forked_runs.dart new file mode 100644 index 000000000..7c9401621 --- /dev/null +++ b/lib/kernel/claude_code/forked_runs.dart @@ -0,0 +1,31 @@ +import 'forked_runs_stub.dart' + if (dart.library.io) 'forked_runs_io.dart' + as platform; + +/// A skill run from a slash command in a subagent of its own (`/code-review`, +/// `context: fork`): the CLI sends nothing of it until it is done, but +/// writes its messages as it goes, in the session's `subagents/` folder. +/// Read from there, they show in its card as it works (#1131). +abstract interface class ForkedRuns { + /// Follows the run that session [sessionId] (of a project in [cwd], its + /// CLI started with [env] besides the machine's) starts now: each line + /// its subagent writes, to [onLine], from the first. + ForkedRun watch({ + required String cwd, + required String sessionId, + Map? env, + required void Function(Map line) onLine, + }); +} + +/// A run followed ([ForkedRuns.watch]). +abstract interface class ForkedRun { + /// The run is done: what is left of its lines is read, then no more. + void finish(); + + /// No more lines, at once. + void cancel(); +} + +/// This machine's; null where there are no files (the web). +ForkedRuns? forkedRunsHere() => platform.forkedRunsHere(); diff --git a/lib/kernel/claude_code/forked_runs_io.dart b/lib/kernel/claude_code/forked_runs_io.dart new file mode 100644 index 000000000..c3b045d02 --- /dev/null +++ b/lib/kernel/claude_code/forked_runs_io.dart @@ -0,0 +1,175 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:bao_agent/bao_agent.dart' show AgentPaths; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; + +import 'claude_environment.dart'; +import 'forked_runs.dart'; + +ForkedRuns? forkedRunsHere() => ForkedRunFiles(); + +/// [ForkedRuns] in Claude Code's own files: the session's `subagents/` +/// folder beside its transcript, looked at every [interval]. +class ForkedRunFiles implements ForkedRuns { + ForkedRunFiles({ + this.interval = const Duration(milliseconds: 700), + @visibleForTesting this.folderOf, + }); + + final Duration interval; + + /// Where session [sessionId]'s subagents write; by default as the CLI + /// does, in its config folder. + final Future Function( + String cwd, + String sessionId, + Map? env, + )? + folderOf; + + static Future _folder( + String cwd, + String sessionId, + Map? env, + ) async { + final paths = AgentPaths.from({...await ClaudeEnvironment.of(), ...?env}); + final transcript = + paths.findSession(sessionId) ?? paths.sessionFile(cwd, sessionId); + return p.join(p.withoutExtension(transcript), 'subagents'); + } + + @override + ForkedRun watch({ + required String cwd, + required String sessionId, + Map? env, + required void Function(Map line) onLine, + }) => _Tail( + (folderOf ?? _folder)(cwd, sessionId, env), + interval: interval, + onLine: onLine, + )..start(); +} + +class _Tail implements ForkedRun { + _Tail(this._folder, {required this.interval, required this.onLine}); + + final Future _folder; + final Duration interval; + final void Function(Map line) onLine; + + /// When it started: a subagent of this run is one made since. + final DateTime _since = DateTime.now().subtract(const Duration(seconds: 2)); + + Timer? _timer; + bool _done = false; + bool _reading = false; + + /// The run's own transcript, once found. + File? _file; + int _offset = 0; + final List _partial = []; + + void start() { + _timer = Timer.periodic(interval, (_) => unawaited(_read())); + unawaited(_read()); + } + + @override + void finish() { + _timer?.cancel(); + _timer = null; + unawaited(_read(last: true)); + } + + @override + void cancel() { + _done = true; + _timer?.cancel(); + _timer = null; + } + + Future _read({bool last = false}) async { + if (_done || _reading) { + // The last read, after the one under way. + if (last && !_done) { + unawaited(Future.delayed(interval, () => _read(last: true))); + } + return; + } + _reading = true; + try { + final file = _file ??= await _find(); + if (file != null) await _readNew(file); + } on Object catch (error) { + debugPrint('Forked run not read: $error'); + } finally { + _reading = false; + if (last) _done = true; + } + } + + /// The run's subagent: made since it started, by no call (a slash + /// command's) and by no other subagent (those it starts itself). + Future _find() async { + final folder = Directory(await _folder); + if (!folder.existsSync()) return null; + final found = <(DateTime, File)>[]; + await for (final entry in folder.list()) { + if (entry is! File || !entry.path.endsWith('.meta.json')) continue; + final made = entry.statSync().modified; + if (made.isBefore(_since)) continue; + final Object? meta; + try { + meta = jsonDecode(await entry.readAsString()); + } on FormatException { + continue; // Being written. + } + if (meta is! Map || + meta['toolUseId'] != null || + meta['parentAgentId'] != null) { + continue; + } + final transcript = File( + '${entry.path.substring(0, entry.path.length - '.meta.json'.length)}' + '.jsonl', + ); + if (transcript.existsSync()) found.add((made, transcript)); + } + if (found.isEmpty) return null; + found.sort((a, b) => a.$1.compareTo(b.$1)); + return found.first.$2; + } + + Future _readNew(File file) async { + final length = await file.length(); + if (length <= _offset) return; + final open = await file.open(); + try { + await open.setPosition(_offset); + final bytes = await open.read(length - _offset); + _offset += bytes.length; + _partial.addAll(bytes); + } finally { + await open.close(); + } + // Whole lines only: the last may be still being written. + final end = _partial.lastIndexOf(10); + if (end < 0) return; + final text = utf8.decode(_partial.sublist(0, end), allowMalformed: true); + _partial.removeRange(0, end + 1); + for (final line in const LineSplitter().convert(text)) { + if (line.trim().isEmpty || _done) continue; + try { + if (jsonDecode(line) case final Map message) { + onLine(message); + } + } on FormatException { + // Not a line of its. + } + } + } +} diff --git a/lib/kernel/claude_code/forked_runs_stub.dart b/lib/kernel/claude_code/forked_runs_stub.dart new file mode 100644 index 000000000..44e3f61f1 --- /dev/null +++ b/lib/kernel/claude_code/forked_runs_stub.dart @@ -0,0 +1,3 @@ +import 'forked_runs.dart'; + +ForkedRuns? forkedRunsHere() => null; diff --git a/lib/main.dart b/lib/main.dart index 3a5d57e93..fa00ad452 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -58,6 +58,7 @@ import 'kernel/claude_code/claude_code_kernel.dart'; import 'kernel/claude_code/claude_core_setting.dart'; import 'kernel/claude_code/claude_onboarding.dart'; import 'kernel/claude_code/claude_path_setting.dart'; +import 'kernel/claude_code/forked_runs.dart'; import 'kernel/claude_code/process_transport.dart'; import 'kernel/claude_code/turn_stats_stub.dart' if (dart.library.io) 'kernel/claude_code/turn_stats_io.dart' @@ -590,6 +591,9 @@ void followSettingsFiles(SettingsFiles files) { ClaudeCodeKernel.turnStats = turnStatsIn( p.join(DataDirectory.current.path, 'turn-stats'), ); + // A skill run from a slash command, read as it goes from what the CLI + // writes of it (it sends nothing of it until done). + ClaudeCodeKernel.forkedRuns = forkedRunsHere(); // The calls to custom upstreams (Settings → Usage, the side panel's // Usage page): in the data folder, a file a day, kept as long as the // user says. diff --git a/test/kernel/forked_runs_test.dart b/test/kernel/forked_runs_test.dart new file mode 100644 index 000000000..2cbd35d7c --- /dev/null +++ b/test/kernel/forked_runs_test.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:baocode/kernel/claude_code/forked_runs_io.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + test('a slash command\'s run is read from its subagent\'s transcript as it ' + 'is written, the subagents it starts itself left out (#1131)', () async { + final folder = await Directory.systemTemp.createTemp('baocode-forked'); + addTearDown(() => folder.delete(recursive: true)); + final runs = ForkedRunFiles( + interval: const Duration(milliseconds: 20), + folderOf: (cwd, session, env) async => folder.path, + ); + String line(String uuid, String text) => jsonEncode({ + 'type': 'assistant', + 'uuid': uuid, + 'message': { + 'role': 'assistant', + 'content': [ + {'type': 'text', 'text': text}, + ], + }, + }); + final lines = []; + final run = runs.watch( + cwd: '/p', + sessionId: 's', + onLine: (message) => lines.add(message['uuid']! as String), + ); + addTearDown(run.cancel); + + // A subagent the run starts itself (an Agent call of its): not its own. + File(p.join(folder.path, 'agent-b.meta.json')).writeAsStringSync( + jsonEncode({'agentType': 'reviewer', 'toolUseId': 'toolu_1'}), + ); + File(p.join(folder.path, 'agent-b.jsonl')) + .writeAsStringSync('${line('b1', 'not this')}\n'); + // The run's own, written a line at a time, the last half way. + File(p.join(folder.path, 'agent-a.meta.json')).writeAsStringSync( + jsonEncode({ + 'agentType': 'general-purpose', + 'requestShape': 'foreground', + }), + ); + final transcript = File(p.join(folder.path, 'agent-a.jsonl')) + ..writeAsStringSync('${line('a1', 'Counting')}\n'); + await Future.delayed(const Duration(milliseconds: 100)); + expect(lines, ['a1']); + + final second = line('a2', '7'); + transcript.writeAsStringSync( + second.substring(0, 10), + mode: FileMode.append, + ); + await Future.delayed(const Duration(milliseconds: 100)); + expect(lines, ['a1']); + transcript.writeAsStringSync( + '${second.substring(10)}\n', + mode: FileMode.append, + ); + await Future.delayed(const Duration(milliseconds: 100)); + expect(lines, ['a1', 'a2']); + + // Done: what is left is read, then no more. + transcript.writeAsStringSync( + '${line('a3', 'done')}\n', + mode: FileMode.append, + ); + run.finish(); + await Future.delayed(const Duration(milliseconds: 100)); + transcript.writeAsStringSync( + '${line('a4', 'after')}\n', + mode: FileMode.append, + ); + await Future.delayed(const Duration(milliseconds: 100)); + expect(lines, ['a1', 'a2', 'a3']); + }); +} diff --git a/test/kernel_test.dart b/test/kernel_test.dart index 951d68625..9c76f1b8a 100644 --- a/test/kernel_test.dart +++ b/test/kernel_test.dart @@ -1109,6 +1109,55 @@ void main() { expect(card(transcript).children, hasLength(2)); }); + test('run from a slash command, read as it goes: its lines in its ' + 'card while it works, not shown again once done (#1131)', () { + final transcript = Transcript(); + var seq = 0; + final told = []; + final translator = + ClaudeTranslator(emit: transcript.apply, nextSeq: () => ++seq) + ..turnId = '11111111-1111-4111-8111-111111111111' + ..onForkedCommand = ((command) => told.add('start $command')) + ..onForkedCommandEnded = ((command) => told.add('end $command')); + translator.translate(started('a4')); + expect(told, ['start forked-command-count-lines']); + + // As the subagent's transcript has them: no parent of the CLI's. + Map line(String uuid, String text) => { + 'type': 'assistant', + 'uuid': uuid, + 'isSidechain': true, + 'message': { + 'id': 'msg-$uuid', + 'role': 'assistant', + 'content': [ + {'type': 'text', 'text': text}, + ], + }, + }; + translator.forkedLine( + 'forked-command-count-lines', + line('u1', 'Counting'), + ); + expect(card(transcript).status, CommandStatus.running); + expect(card(transcript).children, hasLength(1)); + translator.forkedLine('forked-command-count-lines', line('u2', '7')); + expect(card(transcript).children, hasLength(2)); + + translator.translate(ended('a4')); + expect(told.last, 'end forked-command-count-lines'); + translator + ..translate(said('forked-command-count-lines', 'Counting')) + ..translate(said('forked-command-count-lines', '7')) + ..translate(said(null, 'a.py has 7 lines.')); + expect(card(transcript).status, CommandStatus.succeeded); + expect(card(transcript).children, hasLength(2)); + expect(shown(transcript), [ + 'agent: /count-lines', + 'text: a.py has 7 lines.', + ]); + }); + test( 'a subagent\'s task no call or slash command started gets no card', () {