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 text = args['text']! as String;
  final focus = args['focus'] as String?;
  final clear = argBool(args, 'clear') ?? false;
  final keyDelayMs = argInt(args, 'keyDelayMs');
  if (keyDelayMs != null && (keyDelayMs < 0 || keyDelayMs > 1000)) {
    return StructuredResponse.error(
      summary: 'keyDelayMs must be between 0 and 1000',
      errorKind: GlintErrorKind.invalidArgument,
      nextSteps: const ['try keyDelayMs:80 for a field that drops characters'],
    );
  }
  final t = readTargetedArgs(args, session.config);
  if (session.isDeviceMode) {
    return _typeInDeviceMode(session, text, focus, clear, keyDelayMs);
  }

  if (focus == null && session.sceneMode == SceneMode.native && session.active?.nativeReader != null) {
    await session.active?.refreshSceneMode();
    if (session.sceneMode == SceneMode.native) {
      final verdict = await _coveredTypeVerdict(session);
      if (verdict.refusal != null) return verdict.refusal!;
      if (verdict.typeNow) {
        return _typeWhileCovered(session, text, clear, keyDelayMs, t.returnScene, t.fetchScene);
      }
    }
  }

  final warnings = <String>[];
  ArmingReady? focusArming;
  String? focusedThrough;

  if (focus != null) {
    final arming = await maybeAwaitReady(
      session: session,
      glintId: focus,
      awaitReady: t.awaitReady,
      ceilingMs: t.readyTimeoutMs,
      toolLabel: 'type:focus',
    );
    if (arming is ArmingFailed) return arming.envelope;
    if (arming is ArmingReady) focusArming = arming;
  }

  final action = await openActionScene(session, snapshot: t.returnScene);
  final scene = action.scene;
  final pre = action.pre;
  try {
    if (focus != null) {
      var focusResult = await session.interactor.run(
        scene,
        Tap(SymbolicTarget(focus)),
      );
      final parent = visibleParentOf(focusResult);
      if (parent != null) {
        focusResult = await focusThroughParent(session, scene, focus, parent);
        if (focusResult.ok) focusedThrough = focusResult.summary;
      }
      if (!focusResult.ok) {
        return StructuredResponse.error(
          summary: 'failed to focus $focus before typing',
          errorKind: focusResult.errorKind ?? GlintErrorKind.internal,
          detail: focusResult.error,
          nextSteps: focusResult.nextSteps,
        );
      }
      warnings.addAll(focusResult.warnings);
      if (focusedThrough == null && !await awaitReadyToType(session)) {
        warnings.add('$focus did not report focus within 2s after the tap; '
            'typed anyway');
      }
      // Android rebinds the keyboard to a newly focused field after the inset is already steady; keys sent in that gap are lost.
      if (session.device.platform == DevicePlatform.android) {
        await Future<void>.delayed(const Duration(milliseconds: 300));
      }
    }

    _ClearOutcome? cleared;
    if (clear) {
      cleared = await _clearField(session, scene);
      warnings.addAll(cleared.warnings);
    }

    final before = await _fieldInfo(session);
    var result = await session.interactor.run(scene, TypeText(text, keyDelayMs: keyDelayMs));
    var retyped = false;
    if (result.ok) {
      final first = await _check(session, before, text);
      if (first.problem != null && first.retryable) {
        await _clearField(session, scene);
        result =
            await session.interactor.run(scene, TypeText(text, keyDelayMs: max(keyDelayMs ?? 0, _retypeDelayMs)));
        retyped = true;
        final second = await _check(session, before, text);
        warnings.add(second.problem == null
            ? '${first.problem} on the first attempt; cleared it and retyped once at '
                '${_retypeDelayMs}ms a key, and the field now holds exactly what was typed'
            : second.got == first.got
                ? 'the field rewrites what is typed (it held ${first.got} chars both times, '
                    'for ${text.length} typed): the app formats this field, nothing was lost'
                : '${second.problem} even after a slower retype; read the field and retype '
                    'the missing part, or ask the user to check the device');
      } else if (first.problem != null) {
        warnings.add('${first.problem}. Retype with clear:true and keyDelayMs:$_retypeDelayMs');
      }
    }
    var response = StructuredResponse.fromActionResult(result, detail: t.detail).addWarnings(warnings);
    if (retyped) response = response.mergeData(const {'retyped': true});
    if (cleared != null) {
      response = response.mergeData(cleared.data);
      if (cleared.summaryPrefix != null) {
        response = response.copyWith(summary: '${cleared.summaryPrefix}${response.summary}');
      }
    }
    if (focusArming != null) response = withArmedMetadata(response, focusArming);
    if (focusedThrough != null) response = response.copyWith(summary: '$focusedThrough, ${response.summary}');

    if (t.returnScene && !response.isError) {
      final post = await readPostActionState(session, pre, includeSceneText: t.fetchScene);
      if (post != null) {
        // A successful type always changes the field's value → contentChanged.
        // 'nothing' with no `focus` means the text landed nowhere — call it
        // out instead of reporting a silent success.
        final wentNowhere = post.changeCategory == 'nothing' && focus == null;
        response = response.mergeData(post.toData()).addWarnings([
          if (wentNowhere)
            'no field changed — is an input focused? pass '
                'focus:<glintId> to tap one first',
        ]);
      }
    }
    return response;
  } finally {
    await action.dispose();
  }
}