preserveIncompleteProgress static method
Preserves in-flight worker events when a process fails before writing its complete report. The terminal stream intentionally shows only completed case outcomes, so these events are the only durable pointer to a stuck case after its worker is terminated.
Implementation
static List<File> preserveIncompleteProgress(
List<String> progressFiles,
Directory diagnosticsDirectory, {
Set<int> timedOutWorkerIndexes = const {},
DateTime? capturedAt,
}) {
final preserved = <File>[];
final capturedAtEpochMs =
(capturedAt ?? DateTime.now()).millisecondsSinceEpoch;
for (var i = 0; i < progressFiles.length; i++) {
final source = File(progressFiles[i]);
if (!source.existsSync() || source.lengthSync() == 0) continue;
diagnosticsDirectory.createSync(recursive: true);
final target = File(
'${diagnosticsDirectory.path}/worker_${i + 1}_progress.jsonl',
);
final copy = source.copySync(target.path);
final latest = <String, Map<String, dynamic>>{};
for (final line in copy.readAsLinesSync()) {
final event = _decodeEvent(line);
final testId = event?['testId']?.toString();
if (event != null && testId != null) latest[testId] = event;
}
final active =
latest.values.where((event) => event['status'] == 'running');
if (active.isNotEmpty) {
final status =
timedOutWorkerIndexes.contains(i) ? 'timed_out' : 'interrupted';
final additions = active.map((event) {
final startedAt = event['startedAtEpochMs'];
final elapsedMs = startedAt is int
? (capturedAtEpochMs - startedAt).clamp(0, 0x7fffffff)
: null;
return json.encode({
'testId': event['testId'],
'assetPath': event['assetPath'],
'status': status,
if (elapsedMs != null) 'durationMs': elapsedMs,
'capturedAtEpochMs': capturedAtEpochMs,
});
}).join('\n');
copy.writeAsStringSync('$additions\n', mode: FileMode.append);
}
preserved.add(copy);
}
return preserved;
}