useCrawlerController.ts 24.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
import { computed, reactive, ref, shallowRef, watch } from 'vue'

import type {
  CrawlerFlowStep,
  CrawlerFormState,
  CrawlerHistoryItem,
  CrawlerOptionsResponse,
  CrawlerPlatformState,
  CrawlerPrimaryAction,
  CrawlerRecoveryHint,
  CrawlerStateResponse,
  CrawlerSummaryItem,
  OptionItem,
  ResearchTask,
} from '@/types'
import { fetchJson, postJson } from '@/utils/http'
import { bindPersistentState, loadStoredValue } from './usePersistentState'

const STORAGE_KEY = 'bettafish.crawlerState.v2'

const LOGIN_RESTORE_KEYS: Array<keyof CrawlerFormState> = [
  'platform',
  'login_type',
  'headless',
]

const CRAWL_RESTORE_KEYS: Array<keyof CrawlerFormState> = [
  'platform',
  'login_type',
  'crawler_type',
  'save_option',
  'keywords',
  'specified_ids',
  'creator_ids',
  'start_page',
  'max_notes',
  'max_comments',
  'headless',
  'enable_comments',
  'enable_sub_comments',
]

function createDefaultForm(): CrawlerFormState {
  return {
    platform: 'xhs',
    login_type: 'qrcode',
    crawler_type: 'search',
    save_option: 'postgres',
    keywords: '',
    specified_ids: '',
    creator_ids: '',
    cookies: '',
    phone: '',
    start_page: 1,
    max_notes: 20,
    max_comments: 20,
    headless: true,
    enable_comments: true,
    enable_sub_comments: false,
  }
}

interface CrawlerOptionsPayload extends CrawlerOptionsResponse {
  success: boolean
}

interface GenericCrawlerResponse {
  success: boolean
  message?: string
  platform_state?: CrawlerPlatformState
}

function splitInputItems(raw: string): string[] {
  return raw
    .replace(/\r/g, '\n')
    .split(/\n|,/)
    .map((item) => item.trim())
    .filter(Boolean)
}

function resolveOptionLabel(options: OptionItem[], value: string, fallback = value): string {
  return options.find((item) => item.value === value)?.label ?? fallback
}

function isLoginHistoryKind(kind: string): boolean {
  return kind === 'login' || kind === 'login_check'
}

function isLoginFailureStatus(status: string): boolean {
  return ['error', 'cancelled', 'logged_out'].includes(status)
}

function normalizeStoredNumber(value: unknown, fallback: number): number {
  const parsed = Number(value)
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}

function coerceStoredField<K extends keyof CrawlerFormState>(
  key: K,
  value: unknown,
  fallback: CrawlerFormState[K],
): CrawlerFormState[K] {
  if (value === undefined || value === null) {
    return fallback
  }

  if (
    key === 'start_page'
    || key === 'max_notes'
    || key === 'max_comments'
  ) {
    return normalizeStoredNumber(value, Number(fallback)) as CrawlerFormState[K]
  }

  if (
    key === 'headless'
    || key === 'enable_comments'
    || key === 'enable_sub_comments'
  ) {
    return Boolean(value) as CrawlerFormState[K]
  }

  return String(value) as CrawlerFormState[K]
}

function mergeFormField<K extends keyof CrawlerFormState>(
  form: CrawlerFormState,
  key: K,
  value: CrawlerFormState[K],
) {
  Object.assign(form, { [key]: value } as Pick<CrawlerFormState, K>)
}

export function useCrawlerController() {
  const stored = loadStoredValue(STORAGE_KEY, {
    form: createDefaultForm(),
    collapsed: true,
  })

  const loading = shallowRef(false)
  const acting = shallowRef(false)
  const collapsed = shallowRef(false)
  const options = ref<CrawlerOptionsResponse>({
    platforms: [],
    login_types: [],
    crawler_types: [],
    save_options: [],
    platform_capabilities: {},
    defaults: {},
  })
  const form = reactive<CrawlerFormState>({
    ...createDefaultForm(),
    ...stored.form,
  })
  const snapshot = ref<CrawlerStateResponse>({
    crawler: {
      status: 'idle',
      message: '等待爬虫状态刷新...',
      platform: null,
      platform_label: null,
      crawler_type: null,
      started_at: null,
      logs: [],
      qr_code: '',
    },
    login: {
      active_task: {
        running: false,
        platform: null,
        login_type: null,
        started_at: null,
      },
      platforms: [],
    },
    storage: {
      last_login_configs: {},
      last_crawl_configs: {},
      history: [],
    },
  })

  const selectedPlatformState = computed(() => (
    snapshot.value.login.platforms.find((item) => item.platform === form.platform) ?? null
  ))

  const selectedCapability = computed(() => (
    options.value.platform_capabilities[form.platform] ?? null
  ))

  const availableLoginTypes = computed(() => {
    const allowed = selectedCapability.value?.login_types
    if (!allowed?.length) {
      return options.value.login_types
    }
    return options.value.login_types.filter((item) => allowed.includes(item.value))
  })

  const availableCrawlerTypes = computed(() => {
    const allowed = selectedCapability.value?.crawler_types
    if (!allowed?.length) {
      return options.value.crawler_types
    }
    return options.value.crawler_types.filter((item) => allowed.includes(item.value))
  })

  const capabilityHint = computed(() => (
    selectedCapability.value?.note || '当前平台能力信息会在加载完成后展示。'
  ))

  const selectedPlatformLabel = computed(() => (
    resolveOptionLabel(options.value.platforms, form.platform, form.platform || '未选择平台')
  ))

  const selectedLoginLabel = computed(() => (
    resolveOptionLabel(options.value.login_types, form.login_type, form.login_type || '未设置')
  ))

  const selectedCrawlerLabel = computed(() => (
    resolveOptionLabel(options.value.crawler_types, form.crawler_type, form.crawler_type || '未设置')
  ))

  const selectedSaveLabel = computed(() => (
    resolveOptionLabel(options.value.save_options, form.save_option, form.save_option || '未设置')
  ))

  const keywordCount = computed(() => splitInputItems(form.keywords).length)
  const specifiedCount = computed(() => splitInputItems(form.specified_ids).length)
  const creatorCount = computed(() => splitInputItems(form.creator_ids).length)

  const targetSummary = computed(() => {
    if (form.crawler_type === 'detail') {
      return specifiedCount.value > 0 ? `${specifiedCount.value} 条指定内容` : '等待补充内容 ID / URL'
    }
    if (form.crawler_type === 'creator') {
      return creatorCount.value > 0 ? `${creatorCount.value} 个创作者主页` : '等待补充创作者 ID / URL'
    }
    return keywordCount.value > 0 ? `${keywordCount.value} 个搜索关键词` : '等待补充搜索关键词'
  })

  const selectedQrCode = computed(() => (
    snapshot.value.crawler.qr_code
    || selectedPlatformState.value?.qr_code
    || ''
  ))

  const loginBlockedReason = computed(() => {
    if (form.login_type === 'cookie' && !form.cookies.trim()) {
      return 'Cookie 登录需要先粘贴完整 Cookie。'
    }
    if (form.login_type === 'phone' && !form.phone.trim()) {
      return '手机号登录需要先填写手机号。'
    }
    return ''
  })

  const validationIssues = computed(() => {
    const issues: string[] = []
    if (form.crawler_type === 'search' && keywordCount.value === 0) {
      issues.push('搜索模式至少填写 1 个关键词。')
    }
    if (form.crawler_type === 'detail' && specifiedCount.value === 0) {
      issues.push('详情模式至少填写 1 条内容 ID 或 URL。')
    }
    if (form.crawler_type === 'creator' && creatorCount.value === 0) {
      issues.push('创作者模式至少填写 1 个创作者 ID 或 URL。')
    }
    if (form.enable_sub_comments && !form.enable_comments) {
      issues.push('抓取二级评论前需要先启用评论抓取。')
    }
    return issues
  })

  const runningForeignTaskMessage = computed(() => {
    const activeLogin = snapshot.value.login.active_task
    if (activeLogin.running && activeLogin.platform && activeLogin.platform !== form.platform) {
      return `平台 ${activeLogin.platform} 正在进行登录,完成前无法切换执行新的动作。`
    }

    const activeCrawlerPlatform = snapshot.value.crawler.platform
    if (snapshot.value.crawler.status === 'running' && activeCrawlerPlatform && activeCrawlerPlatform !== form.platform) {
      return `平台 ${activeCrawlerPlatform} 正在执行采集,建议先停止当前任务。`
    }

    return ''
  })

  const loginTaskRunning = computed(() => (
    snapshot.value.login.active_task.running
    && snapshot.value.login.active_task.platform === form.platform
  ))

  const crawlerTaskRunning = computed(() => (
    snapshot.value.crawler.status === 'running'
    && snapshot.value.crawler.platform === form.platform
  ))

  const canStartLogin = computed(() => (
    !acting.value
    && !runningForeignTaskMessage.value
    && !loginTaskRunning.value
    && !crawlerTaskRunning.value
    && !loginBlockedReason.value
  ))

  const canStartCrawler = computed(() => (
    !acting.value
    && !runningForeignTaskMessage.value
    && !loginTaskRunning.value
    && !crawlerTaskRunning.value
    && selectedPlatformState.value?.logged_in === true
    && validationIssues.value.length === 0
  ))

  const selectedPlatformHistory = computed<CrawlerHistoryItem[]>(() => (
    snapshot.value.storage.history.filter((item) => item.platform === form.platform)
  ))

  const selectedPlatformLoginHistory = computed<CrawlerHistoryItem[]>(() => (
    selectedPlatformHistory.value.filter((item) => isLoginHistoryKind(item.kind))
  ))

  const latestLoginFailure = computed<CrawlerHistoryItem | null>(() => (
    selectedPlatformLoginHistory.value.find((item) => isLoginFailureStatus(item.status)) ?? null
  ))

  const loginFailureStreak = computed(() => {
    let streak = 0

    for (const item of selectedPlatformLoginHistory.value) {
      if (!isLoginFailureStatus(item.status)) {
        break
      }
      streak += 1
    }

    return streak
  })

  const lastLoginConfig = computed(() => (
    snapshot.value.storage.last_login_configs[form.platform] ?? null
  ))

  const lastCrawlConfig = computed(() => (
    snapshot.value.storage.last_crawl_configs[form.platform] ?? null
  ))

  const recoveryHints = computed<CrawlerRecoveryHint[]>(() => {
    const hints: CrawlerRecoveryHint[] = []
    const availableLoginValues = availableLoginTypes.value.map((item) => item.value)
    const canUseQrcode = availableLoginValues.includes('qrcode')
    const canUsePhone = availableLoginValues.includes('phone')
    const canUseCookie = availableLoginValues.includes('cookie')
    const lastLoginMatchesCurrent = Boolean(lastLoginConfig.value)
      && String(lastLoginConfig.value?.login_type || '') === form.login_type
      && Boolean(lastLoginConfig.value?.headless) === form.headless

    if (runningForeignTaskMessage.value) {
      hints.push({
        id: 'foreign-task',
        tone: 'warning',
        title: '当前有其他平台任务正在占用执行槽位',
        description: runningForeignTaskMessage.value,
        actions: [],
      })
    }

    if (loginBlockedReason.value) {
      const actions: CrawlerRecoveryHint['actions'] = []

      if (form.login_type !== 'qrcode' && canUseQrcode) {
        actions.push({ key: 'switch-to-qrcode', label: '改用二维码登录' })
      }
      if (lastLoginConfig.value && !lastLoginMatchesCurrent) {
        actions.push({ key: 'restore-last-login', label: '恢复上次方案' })
      }

      hints.push({
        id: 'login-blocked',
        tone: 'warning',
        title: '登录前置条件还没准备完整',
        description: loginBlockedReason.value,
        actions,
      })
    }

    if (loginTaskRunning.value) {
      hints.push({
        id: 'login-running',
        tone: selectedQrCode.value ? 'info' : 'warning',
        title: selectedQrCode.value ? '二维码已经生成,等待你完成扫码' : '登录任务正在准备环境',
        description: selectedQrCode.value
          ? '请直接使用对应平台 App 扫码。如果长时间没有进展,可以取消本次登录后再重新发起。'
          : '浏览器正在打开或平台正在初始化登录流程。若超过预期时间无响应,建议取消后改用可视化浏览器再试。',
        actions: selectedQrCode.value
          ? [{ key: 'cancel-login', label: '取消本次登录' }]
          : [{ key: 'switch-to-headed', label: '切到可视化浏览器' }],
      })
    } else if (selectedPlatformState.value?.logged_in) {
      hints.push({
        id: 'login-ready',
        tone: 'success',
        title: '当前平台已经登录,可以直接进入采集阶段',
        description: validationIssues.value.length > 0
          ? `不过在启动采集前,还需要先处理这条配置问题:${validationIssues.value[0]}`
          : '建议先确认关键词或目标链接,再直接启动采集。',
        actions: validationIssues.value.length > 0 ? [] : [{ key: 'check-login', label: '再检查一次登录状态' }],
      })
    } else if (latestLoginFailure.value || isLoginFailureStatus(selectedPlatformState.value?.status || '')) {
      const actions: CrawlerRecoveryHint['actions'] = []

      if (form.headless && form.login_type !== 'cookie') {
        actions.push({ key: 'switch-to-headed', label: '改用可视化浏览器' })
      }
      if (form.login_type !== 'qrcode' && canUseQrcode) {
        actions.push({ key: 'switch-to-qrcode', label: '切到二维码登录' })
      }
      if (lastLoginConfig.value && !lastLoginMatchesCurrent) {
        actions.push({ key: 'restore-last-login', label: '恢复上次方案' })
      }
      actions.push({ key: 'check-login', label: '重新检测状态' })
      actions.push({ key: 'start-login', label: '重新发起登录' })

      hints.push({
        id: 'login-failed',
        tone: 'error',
        title: loginFailureStreak.value >= 2
          ? `最近连续 ${loginFailureStreak.value} 次登录未成功`
          : '最近一次登录没有成功',
        description: latestLoginFailure.value?.message
          || selectedPlatformState.value?.message
          || '建议优先切到可视化浏览器,再重新检查登录状态。',
        actions: actions.slice(0, 3),
      })
    } else {
      hints.push({
        id: 'login-idle',
        tone: 'info',
        title: '当前平台还没有完成登录',
        description: '建议先检查登录状态,确认是否需要重新扫码或切换登录方式。',
        actions: [
          { key: 'check-login', label: '先检查状态' },
          { key: 'start-login', label: '发起登录' },
        ],
      })
    }

    if (
      latestLoginFailure.value
      && canUsePhone
      && form.login_type !== 'phone'
      && form.login_type !== 'qrcode'
    ) {
      hints.push({
        id: 'alternate-phone',
        tone: 'info',
        title: '可以尝试切换到手机号登录链路',
        description: '如果当前平台的二维码或 Cookie 链路不稳定,手机号登录有时会更容易排查验证码和风控问题。',
        actions: [{ key: 'switch-to-phone', label: '切到手机号登录' }],
      })
    } else if (latestLoginFailure.value && canUseCookie && form.login_type !== 'cookie') {
      hints.push({
        id: 'alternate-cookie',
        tone: 'info',
        title: '已有稳定凭据的话,可以考虑改用 Cookie 登录',
        description: '这更适合调试或批量重复执行场景,但请确认凭据仍然有效。',
        actions: [{ key: 'switch-to-cookie', label: '切到 Cookie 登录' }],
      })
    }

    if (validationIssues.value.length > 0 && selectedPlatformState.value?.logged_in) {
      hints.push({
        id: 'mission-warning',
        tone: 'warning',
        title: '登录已经就绪,但采集参数还不完整',
        description: validationIssues.value[0],
        actions: [],
      })
    }

    return hints.slice(0, 3)
  })

  const missionSummary = computed<CrawlerSummaryItem[]>(() => ([
    { label: '平台', value: selectedPlatformLabel.value },
    { label: '登录方式', value: selectedLoginLabel.value },
    { label: '采集模式', value: selectedCrawlerLabel.value },
    { label: '目标范围', value: targetSummary.value },
    { label: '结果存储', value: selectedSaveLabel.value },
    {
      label: '评论策略',
      value: form.enable_comments
        ? (form.enable_sub_comments ? '抓取评论 + 二级评论' : '抓取一级评论')
        : '仅抓取内容主体',
    },
  ]))

  const workflowSteps = computed<CrawlerFlowStep[]>(() => {
    const loggedIn = selectedPlatformState.value?.logged_in === true
    const hasRunOnCurrentPlatform = snapshot.value.crawler.platform === form.platform && Boolean(snapshot.value.crawler.started_at)

    return [
      {
        key: 'platform',
        label: '选择平台',
        detail: `${selectedPlatformLabel.value} 已作为当前工作平台。`,
        status: form.platform ? 'done' : 'active',
      },
      {
        key: 'login',
        label: '完成登录',
        detail: loggedIn
          ? '该平台已登录,可直接发起采集。'
          : loginTaskRunning.value
            ? '登录流程进行中,请留意二维码或风控提示。'
            : loginBlockedReason.value || '先完成登录,再开始采集。',
        status: loggedIn ? 'done' : (loginTaskRunning.value || selectedQrCode.value ? 'active' : (loginBlockedReason.value ? 'warning' : 'todo')),
      },
      {
        key: 'mission',
        label: '配置采集任务',
        detail: validationIssues.value[0] || `${selectedCrawlerLabel.value} 已准备就绪,${targetSummary.value}。`,
        status: validationIssues.value.length > 0 ? 'warning' : (loggedIn ? 'done' : 'todo'),
      },
      {
        key: 'launch',
        label: '启动与观察',
        detail: crawlerTaskRunning.value
          ? (snapshot.value.crawler.message || '采集任务正在运行。')
          : hasRunOnCurrentPlatform
            ? (snapshot.value.crawler.message || '最近一次采集已完成,可继续复用配置。')
            : '开始采集后,这里会持续反馈二维码、日志和历史记录。',
        status: crawlerTaskRunning.value ? 'active' : (hasRunOnCurrentPlatform ? 'done' : 'todo'),
      },
    ]
  })

  const primaryAction = computed<CrawlerPrimaryAction>(() => {
    if (crawlerTaskRunning.value) {
      return {
        key: 'stop-crawler',
        label: '停止当前采集',
        description: snapshot.value.crawler.message || '当前平台有采集任务正在执行,必要时可手动停止。',
        tone: 'danger',
        disabled: acting.value,
      }
    }

    if (loginTaskRunning.value) {
      return {
        key: 'cancel-login',
        label: '取消本次登录',
        description: selectedQrCode.value
          ? '二维码已生成,如果想切换账号或方式,可以先取消再重新登录。'
          : '登录流程正在进行中,可按需取消并重新发起。',
        tone: 'neutral',
        disabled: acting.value,
      }
    }

    if (runningForeignTaskMessage.value) {
      return {
        key: 'none',
        label: '等待其他任务完成',
        description: runningForeignTaskMessage.value,
        tone: 'neutral',
        disabled: true,
      }
    }

    if (selectedPlatformState.value?.logged_in !== true) {
      return {
        key: 'start-login',
        label: selectedQrCode.value ? '重新生成登录二维码' : '开始平台登录',
        description: loginBlockedReason.value || '建议先完成登录检查或直接发起扫码登录。',
        tone: 'primary',
        disabled: !canStartLogin.value,
      }
    }

    if (validationIssues.value.length > 0) {
      return {
        key: 'none',
        label: '补充采集参数',
        description: validationIssues.value[0],
        tone: 'neutral',
        disabled: true,
      }
    }

    return {
      key: 'start-crawler',
      label: '开始采集任务',
      description: `${selectedPlatformLabel.value} 已登录,${targetSummary.value},可以直接启动采集。`,
      tone: 'primary',
      disabled: !canStartCrawler.value,
    }
  })

  async function loadOptions() {
    const payload = await fetchJson<CrawlerOptionsPayload>('/api/crawler/options')
    options.value = {
      platforms: payload.platforms,
      login_types: payload.login_types,
      crawler_types: payload.crawler_types,
      save_options: payload.save_options,
      platform_capabilities: payload.platform_capabilities,
      defaults: payload.defaults,
    }

    form.save_option = String(payload.defaults.save_option || form.save_option)
  }

  async function refreshState() {
    loading.value = true
    try {
      snapshot.value = await fetchJson<CrawlerStateResponse>('/api/crawler/state')
    } finally {
      loading.value = false
    }
  }

  async function checkLogin() {
    acting.value = true
    try {
      await postJson<GenericCrawlerResponse>('/api/crawler/login/check', {
        platform: form.platform,
      })
      await refreshState()
    } finally {
      acting.value = false
    }
  }

  async function startLogin() {
    acting.value = true
    try {
      await postJson<GenericCrawlerResponse>('/api/crawler/login/start', {
        platform: form.platform,
        login_type: form.login_type,
        headless: form.headless,
        cookies: form.cookies,
        phone: form.phone,
      })
      await refreshState()
    } finally {
      acting.value = false
    }
  }

  async function cancelLogin() {
    acting.value = true
    try {
      await postJson<GenericCrawlerResponse>('/api/crawler/login/cancel')
      await refreshState()
    } finally {
      acting.value = false
    }
  }

  async function startCrawler(researchTaskId = '') {
    acting.value = true
    try {
      const payload: Record<string, unknown> = {
        ...form,
      }
      if (researchTaskId.trim()) {
        payload.research_task_id = researchTaskId.trim()
      }

      await postJson<GenericCrawlerResponse>('/api/crawler/start', {
        ...payload,
      })
      await refreshState()
    } finally {
      acting.value = false
    }
  }

  async function stopCrawler() {
    acting.value = true
    try {
      await postJson<GenericCrawlerResponse>('/api/crawler/stop')
      await refreshState()
    } finally {
      acting.value = false
    }
  }

  function syncFromResearchTask(task: ResearchTask | null) {
    if (!task) {
      return
    }

    form.keywords = task.crawler_keywords_text || task.venue_name
    form.crawler_type = task.crawler_defaults?.crawler_type || 'search'
    form.login_type = task.crawler_defaults?.login_type || 'qrcode'
    form.max_notes = Number(task.crawler_defaults?.max_notes || 20)
    form.max_comments = Number(task.crawler_defaults?.max_comments || 20)
    form.start_page = Number(task.crawler_defaults?.start_page || 1)
  }

  function applyStoredConfig(
    source: Record<string, unknown> | null,
    keys: Array<keyof CrawlerFormState>,
  ) {
    if (!source) {
      return
    }

    for (const key of keys) {
      mergeFormField(form, key, coerceStoredField(key, source[key], form[key]))
    }
  }

  function restoreLastLoginConfig() {
    applyStoredConfig(lastLoginConfig.value, LOGIN_RESTORE_KEYS)
  }

  function restoreLastCrawlConfig() {
    applyStoredConfig(lastCrawlConfig.value, CRAWL_RESTORE_KEYS)
  }

  watch(
    [availableLoginTypes, availableCrawlerTypes],
    ([loginTypes, crawlerTypes]) => {
      if (loginTypes.length > 0 && !loginTypes.some((item) => item.value === form.login_type)) {
        form.login_type = loginTypes[0].value
      }
      if (crawlerTypes.length > 0 && !crawlerTypes.some((item) => item.value === form.crawler_type)) {
        form.crawler_type = crawlerTypes[0].value
      }
    },
    { immediate: true },
  )

  watch(
    () => form.enable_comments,
    (enabled) => {
      if (!enabled && form.enable_sub_comments) {
        form.enable_sub_comments = false
      }
    },
  )

  watch(
    () => form.enable_sub_comments,
    (enabled) => {
      if (enabled && !form.enable_comments) {
        form.enable_comments = true
      }
    },
  )

  bindPersistentState(
    STORAGE_KEY,
    computed(() => ({
      form: { ...form },
      collapsed: collapsed.value,
    })),
  )

  return {
    loading,
    acting,
    collapsed,
    options,
    form,
    snapshot,
    selectedPlatformState,
    selectedCapability,
    availableLoginTypes,
    availableCrawlerTypes,
    capabilityHint,
    validationIssues,
    selectedPlatformHistory,
    missionSummary,
    recoveryHints,
    workflowSteps,
    primaryAction,
    selectedQrCode,
    lastLoginConfig,
    lastCrawlConfig,
    canStartLogin,
    canStartCrawler,
    loadOptions,
    refreshState,
    checkLogin,
    startLogin,
    cancelLogin,
    startCrawler,
    stopCrawler,
    syncFromResearchTask,
    restoreLastLoginConfig,
    restoreLastCrawlConfig,
  }
}