Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/kernel/claude_code/claude_code_kernel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import 'claude_sdk_tools.dart';
import 'turn_stats.dart';
import 'control_channel.dart';
import 'forked_runs.dart';
import 'scheduled_jobs.dart';
import 'local_time_zone.dart';
import 'tool_result_tally.dart';
import 'usage_limit.dart';
Expand Down Expand Up @@ -289,6 +290,9 @@ class ClaudeCodeKernel
/// CLI says it is idle.
bool _releaseWanted = false;

/// What the session scheduled itself, which only a running process keeps.
final _scheduled = ScheduledJobs();

String? _turn;

/// When [_turn] began, to time it if the CLI does not.
Expand Down Expand Up @@ -936,9 +940,12 @@ class ClaudeCodeKernel

/// Frees the process now if idle, else once it has started or the CLI
/// says it is idle (one that does not say keeps it until asked again).
///
/// Not with jobs scheduled (CronCreate, ScheduleWakeup): they live in the
/// process, and would not come (#994).
@override
void release() {
if (_busy) {
if (_busy || _scheduled.pending) {
_releaseWanted = true;
return;
}
Expand Down Expand Up @@ -2000,6 +2007,7 @@ class ClaudeCodeKernel
when _results.add(message) && _resultsKnown) {
_reportContext();
}
if (message['type'] case 'assistant' || 'user') _scheduled.receive(message);
switch (message['type']) {
case ClaudeExit.type:
_exited(
Expand Down Expand Up @@ -2052,6 +2060,7 @@ class ClaudeCodeKernel
// prompt of its own (a background task's notice, a scheduled one).
// It is at work all the same: shown, and stopped, as any turn.
if (message['status'] == 'requesting' && _turn == null) {
_scheduled.woke();
_beginTurn('${message['uuid'] ?? 'own:$nextSeq'}', unprompted: true);
}
_translator.translate(message);
Expand Down
68 changes: 68 additions & 0 deletions lib/kernel/claude_code/scheduled_jobs.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/// What the session has scheduled itself, as its messages say: jobs
/// (`CronCreate`, until `CronDelete`) and a loop's next round
/// (`ScheduleWakeup`, until it comes or is stopped). They live in the
/// process, which keeps them only while it runs: a conversation with any
/// is not let go of when no view shows it, or they would not come (#994).
class ScheduledJobs {
/// The jobs scheduled, by their ids (or their calls', where the result
/// gave none).
final Set<String> _jobs = {};

/// The calls made and not answered yet, by their ids: the tool, its
/// input.
final Map<String, (String, Map<String, Object?>)> _calls = {};

bool _wakeup = false;

/// Whether anything is to come.
bool get pending => _jobs.isNotEmpty || _wakeup;

/// A message of the CLI's: the agent's own calls and their results (not
/// a subagent's).
void receive(Map<String, Object?> message) {
if (message['parent_tool_use_id'] != null) return;
final body = message['message'];
if (body is! Map) return;
final content = body['content'];
if (content is! List) return;
for (final block in content) {
if (block is! Map) continue;
switch (block['type']) {
case 'tool_use'
when message['type'] == 'assistant' &&
const {
'CronCreate',
'CronDelete',
'ScheduleWakeup',
}.contains(block['name']):
final id = block['id'];
final input = block['input'];
if (id is String) {
_calls[id] = (
block['name'] as String,
input is Map ? input.cast<String, Object?>() : const {},
);
}
case 'tool_result' when message['type'] == 'user':
final call = _calls.remove(block['tool_use_id']);
if (call == null || block['is_error'] == true) continue;
final (tool, input) = call;
final result = message['tool_use_result'] ?? message['toolUseResult'];
switch (tool) {
case 'CronCreate':
_jobs.add(switch (result) {
{'id': final String id} => id,
_ => block['tool_use_id'] as String,
});
case 'CronDelete':
_jobs.remove('${input['id']}'.trim());
case 'ScheduleWakeup':
_wakeup = input['stop'] != true;
}
}
}
}

/// The CLI took up a prompt of its own: a loop's round come, if one was.
void woke() => _wakeup = false;
}
75 changes: 75 additions & 0 deletions test/kernel_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3991,6 +3991,81 @@ void main() {
kernel.dispose();
});

test('out of view, a process with jobs scheduled is kept until they are '
'deleted, a loop\'s round until it comes (#994)', () async {
final cli = FakeCli();
final (:kernel, transcript: _, events: _) = claude(cli);
const result = {
'type': 'result',
'subtype': 'success',
'is_error': false,
};
Future<void> called(
String turn,
String call,
String tool,
Map<String, Object?> input, {
Map<String, Object?>? answered,
}) async {
kernel.send(KernelTurn(id: turn, text: 'schedule it'));
await pumpEventQueue();
cli
..push({
'type': 'assistant',
'parent_tool_use_id': null,
'message': {
'id': 'msg-$call',
'role': 'assistant',
'content': [
{'type': 'tool_use', 'id': call, 'name': tool, 'input': input},
],
},
})
..push({
'type': 'user',
'parent_tool_use_id': null,
'message': {
'role': 'user',
'content': [
{'type': 'tool_result', 'tool_use_id': call, 'content': 'ok'},
],
},
'tool_use_result': ?answered,
})
..push(result);
await pumpEventQueue();
}

await called(
'u1',
'toolu_1',
'CronCreate',
{'cron': '0 23 * * *', 'prompt': 'report', 'recurring': false},
answered: {'id': 'job1'},
);
kernel.release();
expect(cli.closed, isFalse, reason: 'its job comes at 23:00');
await called('u2', 'toolu_2', 'CronDelete', {'id': 'job1'});
kernel.release();
expect(cli.closed, isTrue);

cli.closed = false;
await called('u3', 'toolu_3', 'ScheduleWakeup', {
'delaySeconds': 1200,
'prompt': '/loop check',
});
kernel.release();
expect(cli.closed, isFalse, reason: 'the next round is to come');
// The round comes: a prompt of the CLI's own.
cli
..push({'type': 'system', 'subtype': 'status', 'status': 'requesting'})
..push(result);
await pumpEventQueue();
kernel.release();
expect(cli.closed, isTrue);
kernel.dispose();
});

test(
'renamed in the CLI (/rename): told; the names sent, not (#171)',
() async {
Expand Down