handle method

  1. @override
Future<StructuredResponse> handle(
  1. GlintSession session,
  2. CallToolRequest request
)
override

Implementation

@override
Future<StructuredResponse> handle(GlintSession session, CallToolRequest request) async {
  final args = request.arguments ?? const {};
  final durationMs = argInt(args, 'durationMs') ?? 400;
  final everyMs = argInt(args, 'everyMs') ?? 50;
  final distinctOnly = argBool(args, 'distinctOnly') ?? true;
  final maxFrames = argInt(args, 'maxFrames') ?? 12;
  final inline = argBool(args, 'inline') ?? false;
  final touches = argBool(args, 'touches') ?? false;

  if (durationMs < 0 || durationMs > 30000) {
    return _bad('durationMs must be 0-30000');
  }
  if (everyMs < 16 || everyMs > 1000) return _bad('everyMs must be 16-1000');
  if (maxFrames < 1 || maxFrames > 60) return _bad('maxFrames must be 1-60');

  final parsed = parseBatchSteps(args['steps'], maxSteps: _maxSteps, allowEmpty: true);
  if (parsed.error != null) return parsed.error!;
  final steps = parsed.steps!;
  if (observeRefusalForSteps(session, steps) case final refused?) return refused;
  if (steps.isEmpty && durationMs == 0) {
    return _bad('nothing to record: pass steps or durationMs > 0');
  }

  final app = session.active;
  if (app == null) {
    return StructuredResponse.error(
      summary: 'glint is not attached to an app',
      errorKind: GlintErrorKind.sessionNotAttached,
      nextSteps: const ['call attach first'],
    );
  }
  if (StructuredResponse.refuse(session.device, Ability.record) case final refused?) return refused;
  if (!session.backend.capabilities.record) {
    return StructuredResponse.error(
      summary: '${session.backend.label} cannot record the display',
      errorKind: GlintErrorKind.unsupportedBackendAction,
      nextSteps: const ['device op:screenshot for single frames'],
    );
  }
  if (app.activeRecording != null) {
    return _bad('a recording is already running on this device');
  }

  // Device mode: only coordinate gestures and hardware buttons can run.
  if (session.isDeviceMode) {
    for (var i = 0; i < steps.length; i++) {
      final st = steps[i];
      final ok = st.tool == 'hardware_button' ||
          (_coordSteps.contains(st.tool) && (readPoint(st.args) != null || readSegment(st.args) != null));
      if (!ok) {
        return _bad('device mode: step ${i + 1} (${st.tool}) needs a Flutter '
            'app; use tap/swipe with x,y or hardware_button, or attach to the app');
      }
    }
  } else if (steps.isNotEmpty) {
    // The steps cannot run if the isolate is not answering.
    String? lifecycle;
    try {
      lifecycle = await session.lifecycleState().timeout(const Duration(seconds: 1));
    } on Object {
      return StructuredResponse.error(
        summary: 'the app is not answering, so the steps cannot run',
        errorKind: GlintErrorKind.appUnresponsive,
        nextSteps: const [
          'if the device is locked or a native layer is up, clear it first',
          'record durationMs:<n> with no steps to see what the device shows',
        ],
      );
    }
    if (lifecycle != null && lifecycle != 'resumed') {
      return StructuredResponse.error(
        summary: 'the app is $lifecycle, so the steps cannot drive it',
        errorKind: GlintErrorKind.appUnresponsive,
        nextSteps: const [
          'clear the native layer (see get_scene), then record again',
          'record durationMs:<n> with no steps to capture the current screen',
        ],
      );
    }
  }

  final dir = _prepareDir(app.id);
  final ScreenRecording recording;
  try {
    recording = await session.backend.startRecording('${dir.path}/video.mp4');
  } on BackendToolError catch (e) {
    return StructuredResponse.error(
      summary: 'could not start recording',
      errorKind: GlintErrorKind.backendToolError,
      detail: e.stderr,
      nextSteps: const [
        'only one recording per simulator at a time',
        'try `xcrun simctl io <udid> recordVideo --codec=h264 /tmp/t.mp4` to see the error',
      ],
    );
  }
  app.activeRecording = recording;

  final t0 = recording.startedAt;
  late final DateTime stopRequestedAt;
  BatchRun? run;
  String? video;
  try {
    if (steps.isNotEmpty) {
      run = await runBatchSteps(session, steps, stopOnNoChange: false);
    }
    await Future<void>.delayed(Duration(milliseconds: durationMs));
  } finally {
    stopRequestedAt = DateTime.now();
    try {
      video = await recording.stop();
    } on BackendToolError catch (e) {
      app.activeRecording = null;
      return StructuredResponse.error(
        summary: 'recording stopped but no video was written',
        errorKind: GlintErrorKind.backendToolError,
        detail: e.stderr,
      );
    }
    app.activeRecording = null;
  }
  final wallMs = stopRequestedAt.difference(t0).inMilliseconds;

  final bridge =
      session.device is IosSimulator ? (session.device as IosSimulator).bridgePath : resolveIosBridgePath(null);
  final extraction = await FrameExtractor(bridgePath: bridge).extract(
    video: video,
    outDir: '${dir.path}/frames',
    everyMs: everyMs,
    maxFrames: maxFrames,
    distinctOnly: distinctOnly,
  );

  final frames = withHoldMs(extraction.frames, endMs: wallMs);
  final drawn = touches ? await _drawTouches(app, bridge, video, t0, stopRequestedAt, dir) : null;
  final warnings = <String>[
    ...extraction.warnings,
    if (drawn?.problem case final problem?) 'touches not drawn: $problem',
    if (extraction.error != null)
      'frames not extracted: ${extraction.error}. The video is at $video. '
          'Build the bridge: cd native/ios_sim_bridge && swift build',
    if (extraction.error == null && frames.isEmpty) await _whyNoFrames(session, video),
    if (frames.length == 1)
      'only one distinct frame in $wallMs ms: the screen did not change while '
          'recording, or changed faster than everyMs=$everyMs',
    if (extraction.capped) 'capped at maxFrames=$maxFrames; raise maxFrames or everyMs for more',
    if (session.isDeviceMode) 'device mode: steps ran as coordinate gestures',
  ];

  final stepLines = run == null ? const <String>[] : [for (final o in run.outcomes) o.line(origin: t0)];

  final attached = <String>[];
  if (inline) {
    for (final f in _spread(frames, 4)) {
      attached.add((await session.modelImage(f.path, maxSize: 512)).image.path);
    }
  }
  return StructuredResponse(
    imagePaths: attached,
    summary: [
      describeFrames(frames, wallMs, distinctOnly: distinctOnly),
      ...stepLines,
      if (frames.isNotEmpty && attached.isEmpty) 'frames are PNG files under ${dir.path}/frames; read them in order',
      if (attached.isNotEmpty) '${attached.length} of ${frames.length} frames attached in order',
      if (drawn?.video case final v?) 'video with ${drawn!.count} touch(es) drawn: $v',
    ].join('\n'),
    warnings: warnings,
    nextSteps: [
      if (frames.isNotEmpty && attached.isEmpty)
        'read ${frames.map((f) => f.path).take(4).join(", ")} to see what changed, or record again with inline:true',
      if (frames.length == 1) 'record again with everyMs:16 for finer sampling',
    ],
    data: {
      'video': video,
      if (drawn?.video case final v?) 'touchesVideo': v,
      'dir': dir.path,
      'wallMs': wallMs,
      if (extraction.durationMs != null) 'videoMs': extraction.durationMs,
      'everyMs': everyMs,
      'distinctOnly': distinctOnly,
      'capped': extraction.capped,
      if (extraction.tool != null) 'extractedWith': extraction.tool,
      'frames': [for (final f in frames) f.toJson()],
      if (run != null) 'steps': [for (final o in run.outcomes) o.toJson(origin: t0)],
      if (session.isDeviceMode) 'mode': 'device',
    },
  );
}