diff --git a/frontend-vue/src/pages/jd/JdCollectTab.vue b/frontend-vue/src/pages/jd/JdCollectTab.vue index 2576c1546..a421197c9 100644 --- a/frontend-vue/src/pages/jd/JdCollectTab.vue +++ b/frontend-vue/src/pages/jd/JdCollectTab.vue @@ -17,6 +17,7 @@ import { } from '@/shared/api/types/modules/jd-collect' import { retryClientTask } from '@/shared/api/task-retry' import { getPywebviewApi } from '@/shared/bridges/pywebview' +import { ensureJdLogin, markJdLoginExpired } from '@/shared/stores/jd-login-autoflow' import { loadCategoryCache, saveCategoryCache } from './jd-category-cache' import { resolvePageHref } from '@/shared/page-prefix' import { userNotice } from '@/shared/utils/user-notice' @@ -51,6 +52,11 @@ import BrandApiSecretSettingsButton from '@/pages/brand/components/BrandApiSecre * DEFAULT_TABS 改为页面勾选(默认两项都勾=与旧行为一致),选中值成为建单 listTabs 与 * 推送载荷的同一真源;空选不建单(服务端 JdCollectTaskService 同样要求至少一个 Tab)。 * DEFAULT_TABS 只保留给历史行缺 listTabs 时的重试/继续兜底。 + * + * 2026-11-23 客户口径「登录能不能自动化的识别,也就是登录按钮不要了」:「登录京麦」按钮 + * 退役,登录态走懒触发自动链路(shared/stores/jd-login-autoflow.ts)——会话内任何一路 + * 发现京麦未登录(同步分类 jd_login / 任务致命公告)就置旗自动开登录窗;此后建单/重试前 + * 预检放行,登录成功才放行任务。旗未置位=零探测,页面不闪浏览器窗口。 */ /** 页面不再让用户填店铺名:店铺名称由客户端从京麦后台读,建单先按此占位记录。 */ @@ -106,9 +112,6 @@ const selectedShopCategoryValues = ref([]) /** 同步中/可用态:可用性按桥上有没有 get_jd_shop_categories 方法判(老客户端置灰)。 */ const syncingCategories = ref(false) const canSyncCategories = ref(false) -/** 「登录京麦」(2026-11-20):起采集专用浏览器等人工登录;可用态同口径按桥判。 */ -const loggingIn = ref(false) -const canLoginJd = ref(false) /** 最近一次同步到的店铺名(空=尚未同步或京麦页面没返回店铺名)。 */ const syncedShopName = ref('') /** 本页选项集来自上次缓存的时间(空=本次没回填缓存;只作提示,不参与建单)。 */ @@ -137,14 +140,10 @@ function restoreCategoryCache() { /** 无桥(浏览器打开)或老客户端(桥没有该方法)时点同步的提示。 */ const SYNC_UNAVAILABLE_NOTE = '当前在浏览器中打开或客户端版本较旧,无法同步店内分类。请在本机客户端中打开本页;仍不可用请把客户端升级到最新版' -/** 同上口径的「登录京麦」不可用提示(2026-11-20)。 */ -const LOGIN_UNAVAILABLE_NOTE = - '当前在浏览器中打开或客户端版本较旧,无法打开京麦登录窗口。请在本机客户端中打开本页;仍不可用请把客户端升级到最新版' function refreshSyncAvailability() { const api = getPywebviewApi() canSyncCategories.value = typeof api?.get_jd_shop_categories === 'function' - canLoginJd.value = typeof api?.open_jd_login === 'function' } /** 分类块底部说明:同步状态 + 选中口径 + 「先挂分类才有命中」的边界,一行讲完。 */ @@ -167,9 +166,15 @@ const categoryHint = computed(() => { /** 点「同步分类」:桥 → 客户端现拉 getShopCategoryList。成功刷新选项集并清理 * 不属于当前店铺的已选 id(id 是店铺自有,跨店必错);失败按 code 分档—— - * jd_busy(京东任务在跑)走 amber notice,jd_login/jd_page/未知走红色 error。 */ -async function syncShopCategories() { - if (syncingCategories.value) return + * jd_busy(京东任务在跑)走 amber notice,jd_login 触发自动登录链路(见下), + * jd_page/未知走红色 error。 + * + * 2026-11-23「登录京麦」按钮退役:jd_login 不再引导手动点按钮,改为置会话旗 + + * ensure 自动开登录窗(busy 档 8 秒后自动重试一次),登录成功后自动重拉一次分类。 + * fromAutoLogin 防递归:自动重拉这次再遇 jd_login 只报错不再开窗——刚验证过登录, + * 多半是抖动,让用户手动再点。 */ +async function syncShopCategories(options?: { fromAutoLogin?: boolean }) { + if (syncingCategories.value && !options?.fromAutoLogin) return errorMessage.value = '' noticeMessage.value = '' const api = getPywebviewApi() @@ -203,9 +208,21 @@ async function syncShopCategories() { } else if (result?.code === 'jd_busy') { noticeMessage.value = result.error || '京东任务正在运行,请等任务结束后再同步分类' } else if (result?.code === 'jd_login') { - errorMessage.value = result.error || '京麦未登录(登录态失效)' - if (canLoginJd.value) { - noticeMessage.value = '点上方「登录京麦」按钮打开登录窗口,登录完成后重新点「同步分类」' + if (options?.fromAutoLogin) { + errorMessage.value = result.error || '京麦未登录(登录态失效)' + return + } + markJdLoginExpired() + noticeMessage.value = '检测到京麦未登录,已自动打开京麦登录窗口,请在弹出的浏览器里完成登录' + const gate = await ensureJdLogin(api) + if (gate.status === 'ok') { + noticeMessage.value = '' + await syncShopCategories({ fromAutoLogin: true }) + } else if (gate.severity === 'error') { + noticeMessage.value = '' + errorMessage.value = gate.hint || result.error || '打开京麦登录窗口失败,请稍后重试' + } else if (gate.status === 'busy' || gate.status === 'unresolved') { + noticeMessage.value = gate.hint || noticeMessage.value } } else { errorMessage.value = result?.error || '同步分类未返回结果,请稍后重试' @@ -221,37 +238,20 @@ function clearShopCategories() { selectedShopCategoryValues.value = [] } -/** 点「登录京麦」(2026-11-20 装机实录后的独立登录入口):桥 → 客户端起采集专用 - * 浏览器停在京麦登录页等人工登录,登录成功即关窗、登录态常驻本机 profile。 - * 分档口径:busy/重入/超时/用户关窗都是「设计内等待或可恢复」走 amber notice - * (超时档客户端**不关窗口**,用户可继续登),只有 jd_page/未知才是红色 error。 */ -async function openJdLogin() { - if (loggingIn.value) return - errorMessage.value = '' - noticeMessage.value = '' - successMessage.value = '' - const api = getPywebviewApi() - const bridge = api?.open_jd_login - if (typeof bridge !== 'function') { - errorMessage.value = LOGIN_UNAVAILABLE_NOTE - return - } - loggingIn.value = true - try { - const result = await bridge() - if (result?.success) { - successMessage.value = result.message || '京麦登录完成,可重跑采集或点「同步分类」' - } else if (result?.code === 'jd_busy' || result?.code === 'jd_login_running' - || result?.code === 'timeout' || result?.code === 'window_closed') { - noticeMessage.value = result.error || '京麦登录未完成,请按提示重试' - } else { - errorMessage.value = result?.error || '打开登录窗口失败,请稍后重试' - } - } catch (error) { - errorMessage.value = error instanceof Error ? `登录京麦失败:${error.message}` : '登录京麦失败,请稍后重试' - } finally { - loggingIn.value = false +/** 登录预检放行闸(2026-11-23「登录京麦」按钮退役):会话内见过京麦未登录(旗置位)时, + * 建单/重试前自动开登录窗,登录成功才放行——不让注定失败的任务白跑一单。 + * 旗未置位(正常路径)零探测直接放行;busy(已自动重试一次)/超时/关窗按档展示并拦下 + * 本次动作,用户完成登录后重新点即可。返回 false=已提示、本次不放行。 */ +async function passJdLoginGate(): Promise { + const gate = await ensureJdLogin(getPywebviewApi()) + if (gate.status === 'ok') { + if (gate.hint) successMessage.value = gate.hint + return true } + if (gate.status === 'skipped') return true + if (gate.severity === 'error') errorMessage.value = gate.hint || '打开京麦登录窗口失败,请稍后重试' + else noticeMessage.value = gate.hint || '京麦登录未完成,请按提示重试' + return false } /** 选中项按选项集原序反查回对象(下拉里点选的先后不进请求体——双键顺序恒等于同步序)。 */ @@ -354,7 +354,16 @@ function toJdTaskView(item: JdCollectHistoryItemVo): TaskItemView { : []), ...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []), ], - progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null, + progress: showProgress + ? { + percent: progressPercent(item), + countLabel: progressCountLabel(item), + // 分母未知(列表页店内分类筛选没生效、走行级兜底翻页 → 游标 total 记 0): + // 在跑的任务改走不确定态流动条纹,别让 0% 空轨道看着像坏了。 + indeterminate: normalizeTaskStatus(item) === 'RUNNING' + && !(typeof item.total === 'number' && item.total > 0), + } + : null, source: item, } } @@ -419,7 +428,7 @@ function progressCountLabel(item: JdCollectHistoryItemVo) { if (!received && normalizeTaskStatus(item) !== 'SUCCESS') { return total ? `已采 0/${total} 个商品(正在采集中…)` : '正在采集,首批数据确认后开始计数…' } - if (!total) return `已采集 ${received} 个商品` + if (!total) return `已采集 ${received} 个商品(总量未知,按页累计)` return `已采集 ${received}/${total} 个商品(${progressPercent(item)}%)` } @@ -468,6 +477,8 @@ async function retryTaskRecord(item: JdCollectHistoryItemVo | null | undefined) const taskId = item?.taskId if (!taskId) return const isResume = normalizeTaskStatus(item) === 'CANCELLED' + // 登录预检放在复位**之前**:复位成功即 PENDING,预检拦下却没人领=任务挂死在 PENDING。 + if (!(await passJdLoginGate())) return try { await retryClientTask(taskId) ElMessage.success(isResume @@ -588,6 +599,8 @@ async function startCollect() { const shopNames = [...selectedShopCategoryNames.value] const shopIds = [...selectedShopCategoryIds.value] try { + // 登录预检(2026-11-23 旗置位时自动开登录窗):登录没完成就不建单——白跑一单不如先登录。 + if (!(await passJdLoginGate())) return const vo = await createJdCollectTask(shop, tabs, 0, [], shopNames, shopIds) board.addPollingTask(vo.taskId) const activateError = await activateTask(vo.taskId) @@ -697,13 +710,8 @@ onUnmounted(() => {
采集分类(可选,多选)
-
@@ -942,8 +950,8 @@ onUnmounted(() => { margin-bottom: 8px; } -/* 两个操作按钮收进右侧一组:原来三个子项直接 space-between,中等的那个被推到 - 中间悬空,「登录京麦」和「同步分类」之间隔了一大段(2026-11-22 用户点名)。 */ +/* 操作按钮收进右侧一组:原来三个子项直接 space-between,中等的那个被推到 + 中间悬空(2026-11-22 用户点名);2026-11-23 起「登录京麦」按钮退役,只剩「同步分类」。 */ .category-head-actions { display: flex; align-items: center; diff --git a/frontend-vue/src/shared/components/CredentialFatalAlert.vue b/frontend-vue/src/shared/components/CredentialFatalAlert.vue index 4bb9b19f4..0f7cdd621 100644 --- a/frontend-vue/src/shared/components/CredentialFatalAlert.vue +++ b/frontend-vue/src/shared/components/CredentialFatalAlert.vue @@ -16,11 +16,26 @@ import { subscribeCredentialFatal, takeCredentialFatal, } from '@/shared/stores/credential-fatal-alert' +import { ensureJdLogin, markJdLoginExpired } from '@/shared/stores/jd-login-autoflow' +import { getPywebviewApi } from '@/shared/bridges/pywebview' let disposed = false let showing = false let unsubscribe: (() => void) | null = null +/** 京麦未登录公告=登录窗口自动弹出(2026-11-23「登录京麦」按钮退役):置会话旗后 + * ensure(busy 档 8 秒后自动重试一次),采集/发布任一特性因京麦未登录判死时, + * 错误弹窗与登录浏览器窗口同时出现,用户登完回任务面板点「重试」即可(重试前 + * 预检会确认登录态)。浏览器模式(无桥)静默跳过;fire-and-forget,失败不打断 + * 公告循环——旗已置位,下一步同步分类/获取/重试还会自动再试。 */ +function autoOpenJdLoginWindow(): void { + markJdLoginExpired() + void ensureJdLogin(getPywebviewApi()).catch((error) => { + console.warn('[jd-login] 自动打开登录窗口失败:%s', + error instanceof Error ? error.message : String(error)) + }) +} + async function drain(): Promise { if (disposed || showing) return showing = true @@ -28,6 +43,7 @@ async function drain(): Promise { for (;;) { const queued = takeCredentialFatal() if (!queued || disposed) return + if (queued.notice.kind === 'jd_login') autoOpenJdLoginWindow() // 关闭/ESC 也是正常路径(用户已经看到了):用 .catch 收掉这个「正常取消」, // 不写成空 catch 块——那正是静默 catch 棘轮点名要减的形状 await ElMessageBox.alert(queued.notice.body, queued.notice.title, { diff --git a/frontend-vue/src/shared/components/tasks/TaskItemCard.vue b/frontend-vue/src/shared/components/tasks/TaskItemCard.vue index 1849d7db8..11f6be0ac 100644 --- a/frontend-vue/src/shared/components/tasks/TaskItemCard.vue +++ b/frontend-vue/src/shared/components/tasks/TaskItemCard.vue @@ -14,7 +14,13 @@ 总进度 {{ item.progress.percent }}%
-
+ +
@@ -134,4 +140,21 @@ defineProps<{ background: linear-gradient(90deg, #4aa3ff, #f0c75e); transition: width .25s ease; } + +/* 不确定态:分母未知时用流动条纹铺满轨道表示"在跑",不显示假的 0% 空条。 */ +.file-progress-bar.indeterminate { + width: 100%; + background: repeating-linear-gradient( + 135deg, + rgba(74, 163, 255, .55) 0 10px, + rgba(240, 199, 94, .55) 10px 20px + ); + background-size: 28px 28px; + animation: file-progress-flow 1s linear infinite; +} + +@keyframes file-progress-flow { + from { background-position: 0 0; } + to { background-position: 28px 0; } +} diff --git a/frontend-vue/src/shared/components/tasks/types.ts b/frontend-vue/src/shared/components/tasks/types.ts index 37ad4caf8..7b21325e1 100644 --- a/frontend-vue/src/shared/components/tasks/types.ts +++ b/frontend-vue/src/shared/components/tasks/types.ts @@ -21,6 +21,9 @@ export interface TaskProgressView { stage?: string /** 计数文案,如:12/50 */ countLabel?: string + /** 分母未知(任务在跑但总量读不到,如京东列表页筛选未生效走兜底翻页): + * 进度条走不确定态动效,percent 不参与宽度。默认 false=按 percent 摆宽度。 */ + indeterminate?: boolean } export interface TaskItemView { diff --git a/frontend-vue/src/shared/composables/useLiveTaskBoard.ts b/frontend-vue/src/shared/composables/useLiveTaskBoard.ts index 41b2dd485..25b78dc94 100644 --- a/frontend-vue/src/shared/composables/useLiveTaskBoard.ts +++ b/frontend-vue/src/shared/composables/useLiveTaskBoard.ts @@ -148,9 +148,9 @@ export interface UseLiveTaskBoardReturn { historyItems: Ref /** 统计卡片数据 */ dashboard: Ref - /** 当前任务区条目(在跑/待跑/已中断/失败 + live 兜底 + 解析占位;失败态是待办不是历史) */ + /** 当前任务区条目(在跑/待跑/已中断 + live 兜底 + 解析占位;失败态归历史任务,2026-11-23 拍板) */ currentItems: ComputedRef - /** 纯历史条目(只留完成态;排除 CURRENT_AREA_STATUSES) */ + /** 纯历史条目(完成态与失败态;排除 CURRENT_AREA_STATUSES) */ historyOnlyItems: ComputedRef /** 从 localStorage 恢复轮询 ID */ @@ -221,16 +221,17 @@ export function defaultCanDownload(item: LiveTaskHistoryItem) { } /** - * 「当前任务区」状态词表(2026-11-22 用户拍板:历史任务只留完成态)。 + * 「当前任务区」状态词表(2026-11-23 用户拍板:失败的任务进历史任务)。 * - * 在跑/待跑之外,「已中断」「失败」也是待办——服务端留着断点游标与原任务重试出口 - * (铁律 26:失败在原任务上复位;B184-01:重试后直推载荷带回本机队列),埋进历史抽屉 - * 用户就找不到了:中断 toast 说「之后可点继续接着跑」,继续按钮却藏在抽屉里。 + * 在跑/待跑/已中断仍是待办留在当前区——中断 toast 说「之后可点继续接着跑」, + * 继续按钮不能埋进抽屉。失败(FAILED)按 2026-11-23 口径归历史:历史行的 + * `history-item-actions` 槽与当前区同形带「重试/删除」(铁律 26 的原任务重试出口 + * 不丢),失败单留在当前区反而把用户盯着的界面堆满旧账。 * 取消态两种拼写并存(Java 侧 CANCELLED 与 CANCELED 都发得出,见 task-status-text.ts 的 * CANCELLED_STATUS_WORDS),词表漏一个老行就掉回历史区。未知/空状态不在表内 ⇒ 仍归历史, * 别把认不出的行装进当前区冒充在跑。 */ -const CURRENT_AREA_STATUSES: readonly string[] = ['RUNNING', 'PENDING', 'SCHEDULED', 'FAILED', 'CANCELLED', 'CANCELED'] +const CURRENT_AREA_STATUSES: readonly string[] = ['RUNNING', 'PENDING', 'SCHEDULED', 'CANCELLED', 'CANCELED'] const HISTORY_CACHE_TTL_MS = 3000 diff --git a/frontend-vue/src/shared/stores/jd-login-autoflow.ts b/frontend-vue/src/shared/stores/jd-login-autoflow.ts new file mode 100644 index 000000000..f1ba2e2c7 --- /dev/null +++ b/frontend-vue/src/shared/stores/jd-login-autoflow.ts @@ -0,0 +1,143 @@ +/** + * 京麦登录自动流转——「登录京麦」按钮退役后的自动识别链路(2026-11-23 用户口径: + * 「登录能不能自动化的识别,不需要手动点击按钮触发,也就是这个按钮不要了」)。 + * + * 形态由探测成本决定:京麦列表接口带 h5st 签名,登录态探测只能起有头浏览器 + * (chrome_data_jd profile 开商品列表页看是否 302 落登录页)⇒ 常态化探测会让每次进页/ + * 建单都闪一个浏览器窗口。所以是**懒触发**:会话内任何一路发现「京麦未登录」(同步分类 + * jd_login、任务致命公告 kind=jd_login)就置会话旗;此后「获取/重试」前的 ensure 放行闸 + * 自动开登录窗,登录成功清旗回到零探测常态。客户端桥 open_jd_login 与执行体 + * amazon/jd/login_window.py 原样复用(app_client 零改动)。 + * + * 零框架依赖(node --test 直测):只产状态与中文动作句,展示通道(页面 refs / + * ElMessage / 静默)由调用方选。 + */ + +/** 会话旗:本会话见过京麦登录失效(进程内单例,跨页面共享;刷新页面即重置)。 */ +let expiredSeen = false + +export function markJdLoginExpired(): void { + expiredSeen = true +} + +export function isJdLoginExpired(): boolean { + return expiredSeen +} + +export function clearJdLoginExpired(): void { + expiredSeen = false +} + +/** 测试隔离用:清会话旗。生产代码不得调用。 */ +export function resetJdLoginAutoflowForTest(): void { + expiredSeen = false +} + +/** 客户端桥 open_jd_login 的返回形状(pywebview.ts 同形;这里窄化成结构类型以便零依赖直测)。 */ +export interface JdLoginBridgeResult { + success: boolean + code?: string + message?: string + error?: string +} + +export interface JdLoginBridgeApi { + open_jd_login?: () => Promise +} + +export interface JdLoginGateOutcome { + /** skipped=不动作(旗未置=流程照旧 / no_bridge=给升级指引);ok=登录就绪; + * busy=任务收尾挡住(已自动重试一次);unresolved=这一轮登录没成(超时/关窗/真失败)。 */ + status: 'skipped' | 'ok' | 'busy' | 'unresolved' + reason?: 'flag_not_set' | 'no_bridge' + /** busy/unresolved 档给界面的中文动作句(skipped/ok 一般无话可说,ok 可带客户端回执)。 */ + hint?: string + /** 展示通道:notice=amber(设计内等待或可恢复),error=红色(真失败/升级指引)。 */ + severity?: 'notice' | 'error' +} + +/** busy 档自动重试的间隔:任务判死/删除后 worker 还在收尾(关浏览器、注销心跳), + * 8 秒后 worker_control.busy 基本已放行;只重试一次,仍 busy 就如实交给用户择机再点。 */ +export const JD_BUSY_RETRY_DELAY_MS = 8000 + +const sleepDefault = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** 调桥开登录窗;成功档(logged_in/already_logged_in)清会话旗。 + * 桥缺失(老客户端 <5.0.1 / 纯浏览器)返回 null=调用方给升级指引。 */ +export async function openJdLoginViaBridge( + api: JdLoginBridgeApi | null | undefined, +): Promise { + const bridge = api?.open_jd_login + if (typeof bridge !== 'function') return null + let result: JdLoginBridgeResult | undefined + try { + result = await bridge() + } catch (error) { + return { + success: false, + code: 'jd_page', + error: `打开京麦登录窗口失败:${error instanceof Error ? error.message : String(error)}`, + } + } + if (!result) { + return { success: false, code: 'jd_page', error: '登录桥未返回结果,请稍后重试' } + } + if (result.success) clearJdLoginExpired() + return result +} + +const NO_BRIDGE_HINT = + '当前在浏览器中打开或客户端版本较旧,无法自动打开京麦登录窗口。请在本机客户端中打开本页;' + + '仍不可用请把客户端升级到最新版' + +function isBusyCode(code?: string): boolean { + return code === 'jd_busy' || code === 'jd_login_running' +} + +function outcomeFor(result: JdLoginBridgeResult): JdLoginGateOutcome { + if (result.success) return { status: 'ok', hint: result.message } + if (isBusyCode(result.code)) { + return { + status: 'busy', + severity: 'notice', + hint: '京东采集/发布任务正在收尾,登录窗口暂时打不开;稍后重新点「同步分类」「获取」或任务「重试」,会自动再弹出登录窗口', + } + } + if (result.code === 'timeout') { + return { + status: 'unresolved', + severity: 'notice', + hint: '等待京麦登录超时,浏览器窗口仍开着;请继续完成登录,之后重新点「同步分类」「获取」或任务「重试」', + } + } + if (result.code === 'window_closed') { + return { + status: 'unresolved', + severity: 'notice', + hint: '登录窗口已被关闭;重新点「同步分类」「获取」或任务「重试」,会再次自动弹出登录窗口', + } + } + return { status: 'unresolved', severity: 'error', hint: result.error || '打开京麦登录窗口失败,请稍后重试' } +} + +/** 登录预检放行闸:会话旗未置 → skipped(零探测常态,调用方直接走原流程);置了 → 开登录窗 + * (busy 档自动重试一次),成功=ok,没登成=unresolved/busy 带中文动作句。 + * @param opts.sleep 注入测试时钟;busyRetry=false 关掉 busy 自动重试。 */ +export async function ensureJdLogin( + api: JdLoginBridgeApi | null | undefined, + opts?: { sleep?: (ms: number) => Promise; busyRetry?: boolean }, +): Promise { + if (!isJdLoginExpired()) return { status: 'skipped', reason: 'flag_not_set' } + const sleep = opts?.sleep ?? sleepDefault + const doRetry = opts?.busyRetry ?? true + let outcome = await openJdLoginViaBridge(api) + if (outcome === null) { + return { status: 'unresolved', reason: 'no_bridge', severity: 'error', hint: NO_BRIDGE_HINT } + } + if (isBusyCode(outcome.code) && doRetry) { + await sleep(JD_BUSY_RETRY_DELAY_MS) + const second = await openJdLoginViaBridge(api) + if (second) outcome = second + } + return outcomeFor(outcome) +} diff --git a/frontend-vue/tests/jd-collect-tab.test.ts b/frontend-vue/tests/jd-collect-tab.test.ts index 2b39b1793..324de0dbd 100644 --- a/frontend-vue/tests/jd-collect-tab.test.ts +++ b/frontend-vue/tests/jd-collect-tab.test.ts @@ -219,42 +219,49 @@ test('建单后先激活再推客户端队列', () => { * 横幅(兜底拉取 2 分钟后照常认领,任务没坏)。推送失败是设计内慢路径不是错误——文案 * 改中性动作句、展示走 amber notice 通道,红色 error 只留给真失败(建单/激活失败)。 * 把提示改回塞进 errorMessage 即红。 */ -/** 2026-11-20 装机实录:京麦登录态失效后,登录窗口只在任务失败那十几秒"顺带"出现、 - * 还会被任务 finally 关掉 ⇒ 独立登录入口「登录京麦」(桥 open_jd_login → 客户端 - * amazon/jd/login_window.py)。把按钮下线、分档改回全红 error、或 jd_login 不再引导 - * 去「登录京麦」(用户就会去登自己的浏览器——登录态不共享,白登),即红。 */ -test('登录京麦独立入口:按钮 + 桥类型 + 分档引导', () => { +/** 2026-11-23 用户口径「登录能不能自动化的识别,也就是登录按钮不要了」:「登录京麦」 + * 按钮退役(2026-11-20 的独立入口使命完成),登录态走懒触发自动链路 + * (shared/stores/jd-login-autoflow.ts):同步分类遇 jd_login 置旗自动开登录窗、 + * 登录成功自动重拉分类;建单/重试前过预检放行闸(旗置位时登录成功才放行)。 + * 把手动登录按钮/状态机加回来、jd_login 改回引导手动点按钮、或预检/自动重拉链路 + * 断线,即红。桥类型登记与 ensure 分档/重试判据在 tests/jd-login-autoflow.test.ts。 */ +test('登录京麦按钮退役:jd_login 自动开登录窗 + 建单/重试预检放行', () => { const page = readIfExists( join(process.cwd(), 'src', 'pages', 'jd', 'JdCollectTab.vue'), 'JdCollectTab.vue', ) - assert.ok(page.includes('open_jd_login'), 'JdCollectTab.vue 必须经桥 open_jd_login') - assert.ok(page.includes('登录京麦'), '必须有「登录京麦」按钮(登录态失效后唯一稳定登录入口)') - assert.ok(page.includes('canLoginJd'), '老客户端(桥无该方法)置灰提示升级(与「同步分类」同口径)') + // 按钮退役反钉:手动登录入口(按钮/状态机/直调桥)不得复活,登录窗只能由闸自动触发 + assert.ok(!page.includes('canLoginJd'), '「登录京麦」按钮已退役(2026-11-23),canLoginJd 复活即红') + assert.ok(!page.includes('loggingIn') && !page.includes('@click="openJdLogin"') + && !page.includes('async function openJdLogin'), + '手动登录入口(openJdLogin/状态机)复活即红;登录窗只能由 jd-login-autoflow 自动触发') const bridge = readIfExists( join(process.cwd(), 'src', 'shared', 'bridges', 'pywebview.ts'), 'pywebview.ts', ) - assert.ok(bridge.includes('open_jd_login'), 'pywebview.ts 必须登记 open_jd_login 桥类型') - - const startAt = page.indexOf('async function openJdLogin') - assert.ok(startAt > 0, 'JdCollectTab.vue 缺 openJdLogin') - const endAt = page.indexOf('selectedShopCategories = computed', startAt) - assert.ok(endAt > startAt, 'openJdLogin 之后的锚点形状变了,请同步本判据') - const body = page.slice(startAt, endAt) - assert.ok(body.includes("code === 'jd_busy'") && body.includes("code === 'jd_login_running'") - && body.includes("code === 'timeout'") && body.includes("code === 'window_closed'") - && body.includes('noticeMessage.value'), - 'busy/重入/超时/关窗都是设计内等待或可恢复,必须走 amber notice(超时档窗口还开着,不是失败)') - assert.ok(body.includes('successMessage.value'), '登录成功必须走绿色 success 展示') - assert.ok(body.includes('errorMessage.value = result?.error'), '仅 jd_page/未知失败走红色 error') - assert.ok(body.includes('LOGIN_UNAVAILABLE_NOTE'), '无桥必须给升级指引(与 SYNC_UNAVAILABLE_NOTE 同口径)') + assert.ok(bridge.includes('open_jd_login'), 'pywebview.ts 必须登记 open_jd_login 桥类型(自动链路的执行体)') + // 同步分类遇 jd_login:置旗 + 自动开登录窗 + 登录成功自动重拉(fromAutoLogin 防递归) const syncStart = page.indexOf('async function syncShopCategories') const syncBody = page.slice(syncStart, page.indexOf('function clearShopCategories')) - assert.ok(syncBody.includes("code === 'jd_login'") && syncBody.includes('登录京麦'), - '「同步分类」遇 jd_login 必须引导点「登录京麦」(否则用户去登自己的浏览器=白登)') + assert.ok(syncBody.includes("code === 'jd_login'") && syncBody.includes('markJdLoginExpired()') + && syncBody.includes('await ensureJdLogin(api)'), + '「同步分类」遇 jd_login 必须自动开登录窗(引导手动点按钮=按钮已退役无处可点;' + + '让用户去登自己的浏览器=登录态不共享,白登)') + assert.ok(syncBody.includes('syncShopCategories({ fromAutoLogin: true })'), + '登录成功后必须自动重拉分类闭环;fromAutoLogin 防递归(重拉再遇 jd_login 不再开窗)') + + // 建单/重试预检:旗置位时登录成功才放行 + assert.ok(page.includes('async function passJdLoginGate'), '缺登录预检放行闸 passJdLoginGate') + const collectStart = page.indexOf('async function startCollect') + const collectBody = page.slice(collectStart, page.indexOf('onMounted(', collectStart)) + assert.ok(collectBody.includes('await passJdLoginGate()'), + '建单前必须过登录预检闸(旗置位时登录成功才建单,不让注定失败的任务白跑一单)') + const retryStart = page.indexOf('async function retryTaskRecord') + const retryBody = page.slice(retryStart, page.indexOf('/** 手动刷新', retryStart)) + assert.ok(retryBody.includes('await passJdLoginGate()'), + '重试/继续前必须过登录预检闸,且在复位之前(复位成功即 PENDING,预检拦下却没人领=任务挂死)') }) test('推送失败的兜底提示走 notice 通道,不占红色 error', () => { diff --git a/frontend-vue/tests/jd-login-autoflow.test.ts b/frontend-vue/tests/jd-login-autoflow.test.ts new file mode 100644 index 000000000..0043d67c4 --- /dev/null +++ b/frontend-vue/tests/jd-login-autoflow.test.ts @@ -0,0 +1,169 @@ +/** + * 京麦登录自动流转(2026-11-23「登录京麦」按钮退役)回归判据。 + * + * 背景:按钮退役后登录态走懒触发自动链路——会话内任何一路发现「京麦未登录」(同步分类 + * jd_login / 任务致命公告 kind=jd_login)就置会话旗;此后建单/重试前的 ensure 放行闸 + * 自动开登录窗,登录成功清旗回到零探测常态。靶子是三种错法: + * ① 旗未置位也开窗(每次建单都闪浏览器窗口=常态化探测,探测必须有成本理由才做); + * ② 登录成功不清旗(旗永远置着 ⇒ 每次建单都多等一次登录窗确认,自动链路退化为手动); + * ③ busy 档不重试(任务判死瞬间 worker 还在收尾,第一发必撞 jd_busy,不重试=自动弹窗 + * 十有八九哑火,用户又回到「找不到登录入口」的死局)。 + * + * 跑法:`cd crawler-plugin/frontend-vue && node --test tests/jd-login-autoflow.test.ts` + */ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' + +import { + clearJdLoginExpired, + ensureJdLogin, + isJdLoginExpired, + JD_BUSY_RETRY_DELAY_MS, + markJdLoginExpired, + openJdLoginViaBridge, + resetJdLoginAutoflowForTest, +} from '../src/shared/stores/jd-login-autoflow.ts' + +const sleepCalls: number[] = [] +const sleepSpy = async (ms: number) => { sleepCalls.push(ms) } + +function bridgeOf(result: unknown, calls: unknown[] = []) { + return { open_jd_login: async () => { calls.push(result); return result } } +} + +test('会话旗:默认未置、mark/clear/reset 各归其位', () => { + resetJdLoginAutoflowForTest() + assert.equal(isJdLoginExpired(), false) + markJdLoginExpired() + assert.equal(isJdLoginExpired(), true) + clearJdLoginExpired() + assert.equal(isJdLoginExpired(), false) +}) + +test('旗未置位时 ensure 直接放行,绝不碰桥(零探测常态,不闪浏览器窗口)', async () => { + resetJdLoginAutoflowForTest() + // 桥桩一被调就抛:旗未置位的路径任何桥调用都是判红点 + const hostile = { open_jd_login: async () => { throw new Error('桥不该被调') } } + const gate = await ensureJdLogin(hostile, { sleep: sleepSpy }) + assert.deepEqual(gate, { status: 'skipped', reason: 'flag_not_set' }) + assert.equal(sleepCalls.length, 0) +}) + +test('旗置位+无桥(老客户端/纯浏览器)=升级指引的 error 档', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const gate = await ensureJdLogin(null, { sleep: sleepSpy }) + assert.equal(gate.status, 'unresolved') + assert.equal(gate.reason, 'no_bridge') + assert.equal(gate.severity, 'error') + assert.match(gate.hint ?? '', /客户端版本较旧|本机客户端/) +}) + +test('already_logged_in = ok 且清旗:下次建单回到零探测常态', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const gate = await ensureJdLogin(bridgeOf({ success: true, code: 'already_logged_in', + message: '京麦已是登录状态' }), { sleep: sleepSpy }) + assert.equal(gate.status, 'ok') + assert.equal(gate.hint, '京麦已是登录状态') + assert.equal(isJdLoginExpired(), false, '登录成功必须清会话旗,否则每次建单都卡一次登录窗') +}) + +test('jd_busy 档自动重试一次(覆盖任务判死后 worker 收尾窗口),第二次成功=ok', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + let calls = 0 + const api = { open_jd_login: async () => { + calls += 1 + return calls === 1 + ? { success: false, code: 'jd_busy', error: '京东采集/发布任务正在运行' } + : { success: true, code: 'logged_in', message: '京麦登录成功' } + } } + const gate = await ensureJdLogin(api, { sleep: sleepSpy }) + assert.equal(calls, 2, 'busy 必须自动重试一次:判死瞬间 worker 还在收尾,不重试=自动弹窗哑火') + assert.deepEqual(sleepCalls, [JD_BUSY_RETRY_DELAY_MS]) + assert.equal(gate.status, 'ok') +}) + +test('两连 busy = busy 档(amber 动作句),busyRetry:false 关掉重试', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const busy = { success: false, code: 'jd_busy', error: '京东采集/发布任务正在运行' } + const gate = await ensureJdLogin(bridgeOf(busy), { sleep: sleepSpy }) + assert.equal(gate.status, 'busy') + assert.equal(gate.severity, 'notice') + assert.match(gate.hint ?? '', /收尾|自动再弹出/) + + markJdLoginExpired() + sleepCalls.length = 0 + const noRetry = await ensureJdLogin(bridgeOf(busy), { sleep: sleepSpy, busyRetry: false }) + assert.equal(noRetry.status, 'busy') + assert.deepEqual(sleepCalls, [], 'busyRetry:false 不得重试') +}) + +test('jd_login_running 与 jd_busy 同档(登录窗口已在等待=可恢复)', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const gate = await ensureJdLogin(bridgeOf({ success: false, code: 'jd_login_running', + error: '登录窗口已在等待登录' }), { sleep: sleepSpy }) + assert.equal(gate.status, 'busy') +}) + +test('timeout/window_closed = unresolved notice(窗口还在或下次动作自动再弹);jd_page/未知 = error', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const timeout = await ensureJdLogin(bridgeOf({ success: false, code: 'timeout', + error: '等待登录超时' }), { sleep: sleepSpy }) + assert.equal(timeout.status, 'unresolved') + assert.equal(timeout.severity, 'notice') + + markJdLoginExpired() + const closed = await ensureJdLogin(bridgeOf({ success: false, code: 'window_closed', + error: '采集浏览器窗口已关闭' }), { sleep: sleepSpy }) + assert.equal(closed.status, 'unresolved') + assert.equal(closed.severity, 'notice') + + markJdLoginExpired() + const page = await ensureJdLogin(bridgeOf({ success: false, code: 'jd_page', + error: '打开登录窗口失败:boom' }), { sleep: sleepSpy }) + assert.equal(page.status, 'unresolved') + assert.equal(page.severity, 'error') + assert.equal(page.hint, '打开登录窗口失败:boom') + + markJdLoginExpired() + const unknown = await ensureJdLogin(bridgeOf({ success: false }), { sleep: sleepSpy }) + assert.equal(unknown.status, 'unresolved') + assert.equal(unknown.severity, 'error') +}) + +test('桥抛异常兜底成 jd_page error 档(桥线程契约:不往调用方抛)', async () => { + resetJdLoginAutoflowForTest() + markJdLoginExpired() + const result = await openJdLoginViaBridge({ open_jd_login: async () => { throw new Error('boom') } }) + assert.equal(result?.success, false) + assert.equal(result?.code, 'jd_page') + assert.match(result?.error ?? '', /boom/) +}) + +test('CredentialFatalAlert.vue 接线锚点:jd_login 公告必须置旗并 ensure 自动开窗', () => { + const here = fileURLToPath(new URL('.', import.meta.url)) + const src = readFileSync(`${here}../src/shared/components/CredentialFatalAlert.vue`, 'utf8') + assert.ok(src.includes("queued.notice.kind === 'jd_login'"), + '致命公告组件必须按 kind 分档:只有京麦未登录才自动开登录窗(代理/LLM 欠费弹浏览器=灾难)') + assert.ok(src.includes('autoOpenJdLoginWindow()') && src.includes('markJdLoginExpired()') + && src.includes('ensureJdLogin(getPywebviewApi())'), + 'jd_login 公告的自动开窗链路必须接线(置旗 + ensure)') + assert.ok(src.includes('void ensureJdLogin'), + '自动开窗必须 fire-and-forget:登录窗要等人工登完(最长 10 分钟),不能阻塞公告循环') +}) + +test('JdCollectTab.vue 锚点:登录桥已不在页面直调(统一走 jd-login-autoflow)', () => { + const here = fileURLToPath(new URL('.', import.meta.url)) + const src = readFileSync(`${here}../src/pages/jd/JdCollectTab.vue`, 'utf8') + assert.ok(!src.includes("api?.open_jd_login"), + '页面不得再直调 open_jd_login 桥:分档与重试统一收口在 jd-login-autoflow(重复实现=改一处漏一处)') + assert.ok(src.includes("from '@/shared/stores/jd-login-autoflow'"), + '页面必须经 jd-login-autoflow 的 ensure 闸触发登录') +}) diff --git a/frontend-vue/tests/mount/jd-collect-progress.mount.test.ts b/frontend-vue/tests/mount/jd-collect-progress.mount.test.ts index c772f6f46..f8729578d 100644 --- a/frontend-vue/tests/mount/jd-collect-progress.mount.test.ts +++ b/frontend-vue/tests/mount/jd-collect-progress.mount.test.ts @@ -17,6 +17,7 @@ import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import ElementPlus, { ElOption, ElSelect } from 'element-plus' import JdCollectTab from '@/pages/jd/JdCollectTab.vue' +import { resetJdLoginAutoflowForTest } from '@/shared/stores/jd-login-autoflow' const api = vi.hoisted(() => ({ createJdCollectTask: vi.fn(), @@ -34,6 +35,8 @@ const api = vi.hoisted(() => ({ enqueue: vi.fn(), // 2026-11-19「同步分类」:选项集正本从冻结快照改为桥实时拉取(每家店的店内分类不同)。 syncCategories: vi.fn(), + // 2026-11-23「登录京麦」按钮退役:jd_login 自动开登录窗走桥 open_jd_login(autoflow 闸)。 + openJdLogin: vi.fn(), })) vi.mock('@/shared/api/types/modules/jd-collect', () => ({ @@ -52,7 +55,11 @@ vi.mock('@/shared/api/task-retry', () => ({ retryClientTask: api.retryClientTask, })) vi.mock('@/shared/bridges/pywebview', () => ({ - getPywebviewApi: () => ({ enqueue_json: api.enqueue, get_jd_shop_categories: api.syncCategories }), + getPywebviewApi: () => ({ + enqueue_json: api.enqueue, + get_jd_shop_categories: api.syncCategories, + open_jd_login: api.openJdLogin, + }), })) const EMPTY_DASHBOARD = { @@ -157,8 +164,8 @@ function syncedResult(over: Record = {}) { } async function syncCategories(w: VueWrapper) { - // 2026-11-20 起同一样式类下有两个按钮:「登录京麦」在前、「同步分类」在后; - // 按文案取,别再拿 find('.shop-cat-sync') 点第一个(点到登录按钮=同步根本没跑)。 + // 2026-11-23 起「登录京麦」按钮退役,.shop-cat-sync 只剩「同步分类」一个; + // 按文案取仍是最稳的定位(将来再加按钮也不会点错)。 const syncBtn = w.findAll('.shop-cat-sync').find((btn) => btn.text().includes('同步分类')) if (!syncBtn) throw new Error('页面缺「同步分类」按钮') await syncBtn.trigger('click') @@ -168,6 +175,8 @@ async function syncCategories(w: VueWrapper) { beforeEach(() => { vi.useFakeTimers() localStorage.setItem('username', 'admin') + // 会话旗是模块级单例:jd_login 用例置过旗会泄漏进后续用例的建单预检(误开登录窗)。 + resetJdLoginAutoflowForTest() for (const mock of Object.values(api)) { // 无桥用例会把 syncCategories 覆写成 undefined,这里按可重置性防御(保持全量 reset 语义)。 if (typeof (mock as { mockReset?: unknown })?.mockReset === 'function') mock.mockReset() @@ -280,8 +289,12 @@ describe('获取店铺数据:一键采集 + 任务面板', () => { const meta = w.find('.file-progress-meta') expect(meta.exists()).toBe(true) expect(meta.text()).toContain('已采集 30 个商品') + expect(meta.text()).toContain('总量未知') expect(meta.text()).not.toContain('%') - expect(w.find('.file-progress-bar').attributes('style')).toContain('width: 0%') + // 分母未知 + 在跑:进度条走不确定态流动条纹(宽度不再按 percent 摆成 0% 空轨道)。 + const bar = w.find('.file-progress-bar') + expect(bar.classes()).toContain('indeterminate') + expect(bar.attributes('style') ?? '').not.toContain('width') }) it('0 行且无分母时报进行时文案,不把「已采集 0 个商品」挂出来像卡死(35089 误删实录)', async () => { @@ -527,16 +540,36 @@ describe('获取店铺数据:一键采集 + 任务面板', () => { expect(w.findAllComponents(ElOption).length).toBe(0) }) - it('同步失败 jd_login:京麦未登录要用户去登录,走红色 error', async () => { - api.syncCategories.mockResolvedValue( - syncedResult({ success: false, code: 'jd_login', error: '京麦未登录(登录态失效),请先在客户端登录京麦' })) + it('同步失败 jd_login:自动开京麦登录窗,登录成功后自动重拉分类(登录按钮已退役)', async () => { + // 第一次同步回 jd_login ⇒ 自动开登录窗(already_logged_in 秒回)⇒ 自动重拉第二次成功。 + api.syncCategories + .mockResolvedValueOnce(syncedResult({ success: false, code: 'jd_login', + error: '京麦未登录(登录态失效),请先在客户端登录京麦' })) + .mockResolvedValueOnce(syncedResult()) + api.openJdLogin.mockResolvedValue({ success: true, code: 'already_logged_in', message: '京麦已是登录状态' }) const w = await mountPage(true) await syncCategories(w) - const error = w.find('.feedback.error') - expect(error.exists()).toBe(true) - expect(error.text()).toContain('京麦未登录') - expect(w.find('.feedback.notice').exists()).toBe(false) + expect(api.openJdLogin).toHaveBeenCalledTimes(1) + expect(api.syncCategories).toHaveBeenCalledTimes(2, '登录成功后必须自动重拉一次分类(闭环,不劳用户再点)') + expect(w.findAllComponents(ElOption).length).toBe(SYNCED_CATEGORIES.length) + expect(w.find('.feedback.error').exists()).toBe(false) + }) + + it('同步失败 jd_login 且登录未完成:amber 提示等登录,不递归开窗不假同步', async () => { + // 超时档(窗口仍开着等人工登录):只提示、不重拉——用户登完再点同步/获取。 + api.syncCategories.mockResolvedValue( + syncedResult({ success: false, code: 'jd_login', error: '京麦未登录(登录态失效),请先在客户端登录京麦' })) + api.openJdLogin.mockResolvedValue({ success: false, code: 'timeout', error: '等待登录超时' }) + const w = await mountPage(true) + await syncCategories(w) + + const notice = w.find('.feedback.notice') + expect(notice.exists()).toBe(true) + expect(notice.text()).toContain('登录') + expect(w.find('.feedback.error').exists()).toBe(false) + expect(api.openJdLogin).toHaveBeenCalledTimes(1) + expect(api.syncCategories).toHaveBeenCalledTimes(1, '登录未完成不得自动重拉(再拉还是 jd_login)') expect(w.findAllComponents(ElOption).length).toBe(0) })