fix: 学习引导失败后不再永久禁用入口

This commit is contained in:
2026-10-10 09:36:13 +08:00
parent 232fdb88ad
commit f51e499127
6 changed files with 135 additions and 58 deletions
+60 -2
View File
@@ -2,9 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import { createMemoryHistory, createRouter } from 'vue-router'
import { nextTick } from 'vue'
import Welcome from '@/components/Welcome.vue'
import { resetGuidanceAvailability } from '@/components/composables/useGuidance'
import { getReviewFeed, getReviewTaskStats, submitReviewFeedback, touchReviewFragment } from '@/api/review'
import { getAiTask } from '@/api/aiTasks'
import { startGuidance } from '@/api/guidance'
import { filterByMarker, getMarkersBatch } from '@/api/markers'
import { updateFragmentOwnership } from '@/api/reportFragments'
import appRouter from '@/router'
@@ -31,6 +33,19 @@ vi.mock('@/api/reportFragments', () => ({
updateFragmentOwnership: vi.fn(),
}))
vi.mock('@/api/guidance', () => ({
startGuidance: vi.fn(),
submitGuidanceTurn: vi.fn(),
getGuidanceSession: vi.fn(),
createGuidanceFragment: vi.fn(),
abandonGuidance: vi.fn(),
}))
vi.mock('@/api/aiTasks', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/aiTasks')>()
return { ...actual, submitAiTask: vi.fn(), getAiTask: vi.fn(), getLatestAiTask: vi.fn() }
})
const makeFragment = (id: number) => ({
id,
contextNum: `SESSION_${id}`,
@@ -117,7 +132,6 @@ beforeEach(() => {
return anim as unknown as Animation
})
Element.prototype.animate = animateSpy as unknown as Element['animate']
resetGuidanceAvailability()
vi.mocked(getMarkersBatch).mockResolvedValue({ code: 200, data: {} } as never)
vi.mocked(touchReviewFragment).mockResolvedValue({ code: 200, data: null } as never)
vi.mocked(getReviewFeed).mockResolvedValue({ code: 200, data: [makeFragment(1), makeFragment(2)] })
@@ -438,3 +452,47 @@ describe('Welcome Feed 标记、反馈与摘要', () => {
expect(wrapper.text()).toContain('全文 380 字')
})
})
/**
* 学习引导入口(复习-06):入口只依赖是否归属任务,不因 AI 失败被停用。
*/
describe('Welcome 学习引导入口', () => {
beforeEach(() => {
vi.clearAllMocks()
stubLayout(4000, 1000)
vi.mocked(getReviewFeed).mockResolvedValue({ code: 200, data: [makeFragment(1)] } as never)
vi.mocked(startGuidance).mockResolvedValue({
code: 200,
data: { guidanceNum: 'G1', taskNum: 'T001', concept: '残片内容1', aiTaskNum: 'AI1' },
} as never)
vi.mocked(getAiTask).mockResolvedValue({
code: 200,
data: {
taskNum: 'AI1',
type: 'GUIDANCE',
targetNum: 'G1',
status: 'SUCCEEDED',
result: { reply: '第一个问题' },
},
} as never)
})
it('残片有归属任务时「学习引导」入口不禁用,点击后打开引导弹窗', async () => {
const wrapper = await mountWelcome()
const guidanceButton = wrapper.findAll('button').find((b) => b.text().trim() === '学习引导')
expect(guidanceButton).toBeDefined()
expect(guidanceButton!.attributes('disabled')).toBeUndefined()
expect(guidanceButton!.attributes('title')).toBe('和 AI 一起把这个概念聊透')
await guidanceButton!.trigger('click')
await flushPromises()
await nextTick()
expect(startGuidance).toHaveBeenCalledWith('T1', '残片内容1')
expect(wrapper.find('.guidance-dialog').exists()).toBe(true)
expect(wrapper.text()).toContain('正在引导的概念')
wrapper.unmount()
})
})
+54 -12
View File
@@ -11,10 +11,6 @@ import {
submitGuidanceTurn,
} from '@/api/guidance'
import { getAiTask, type AiTask } from '@/api/aiTasks'
import {
guidanceUnavailable,
resetGuidanceAvailability,
} from '@/components/composables/useGuidance'
vi.mock('@/api/guidance', () => ({
startGuidance: vi.fn(),
@@ -62,12 +58,11 @@ const mountDialog = async () => {
}
/**
* 学习引导主流程(复习-06):开对话 → 多轮 → 确认产出碎片 / 放弃 / AI 失败置不可用。
* 学习引导主流程(复习-06):开对话 → 多轮 → 确认产出碎片 / 放弃 / AI 失败只提示不停用入口。
*/
describe('学习引导(集成)', () => {
beforeEach(() => {
vi.clearAllMocks()
resetGuidanceAvailability()
localStorage.clear()
vi.mocked(startGuidance).mockResolvedValue(
ok({ guidanceNum: 'G1', taskNum: 'T001', concept: '组合式 API', aiTaskNum: 'AI1' }),
@@ -129,18 +124,65 @@ describe('学习引导(集成)', () => {
expect(createGuidanceFragment).not.toHaveBeenCalled()
})
it('AI 失败时给出可读提示并把入口置为不可用', async () => {
vi.mocked(getAiTask).mockResolvedValue(
it('AI 失败时给出可读提示,但入口仍可用并能重试成功', async () => {
vi.mocked(getAiTask).mockResolvedValueOnce(
ok(aiTask({ status: 'FAILED', errorMessage: 'AI 暂时用不了' })),
)
const wrapper = await mountDialog()
expect(wrapper.text()).toContain('AI 暂时用不了')
expect(guidanceUnavailable.value).toBe(true)
// 入口整体停用:输入与「记成知识碎片」不再可用
expect(findButton(wrapper, '发送')).toBeUndefined()
expect(findButton(wrapper, '记成知识碎片')).toBeUndefined()
// 失败只提示,不改变入口可用性
expect(findButton(wrapper, '发送')).toBeDefined()
expect(findButton(wrapper, '记成知识碎片')).toBeDefined()
// 重新打开即可再次发起引导,并拿到 AI 回复
vi.mocked(getAiTask).mockResolvedValue(ok(aiTask({ result: { reply: '重试后的第一个问题' } })))
await wrapper.setProps({ modelValue: false })
await flushPromises()
await wrapper.setProps({ modelValue: true })
await flushPromises()
await nextTick()
await flushPromises()
expect(startGuidance).toHaveBeenCalledTimes(2)
expect(wrapper.text()).toContain('重试后的第一个问题')
})
it('关闭弹窗后到达的 AI 失败不影响入口,重新打开仍能发起引导', async () => {
// AI 任务迟迟不返回:让 getAiTask 挂住,模拟 LLM 未响应
let resolveTask: (value: unknown) => void = () => {}
vi.mocked(getAiTask).mockReturnValue(
new Promise((resolve) => {
resolveTask = resolve as (value: unknown) => void
}) as ReturnType<typeof getAiTask>,
)
const wrapper = await mountDialog()
expect(startGuidance).toHaveBeenCalledTimes(1)
// 用户等不到回应,关闭弹窗
await wrapper.setProps({ modelValue: false })
await nextTick()
await flushPromises()
// 关闭之后后端才把这次任务标为 FAILED
resolveTask(ok(aiTask({ status: 'FAILED', errorMessage: 'AI 没有回应' })))
await flushPromises()
await nextTick()
await flushPromises()
// 重新打开:照常发起新的引导,且不带任何“停用”类错误或上一轮的残留失败
vi.mocked(getAiTask).mockResolvedValue(ok(aiTask({ result: { reply: '重新开始的问题' } })))
await wrapper.setProps({ modelValue: true })
await flushPromises()
await nextTick()
await flushPromises()
expect(startGuidance).toHaveBeenCalledTimes(2)
expect(wrapper.text()).toContain('重新开始的问题')
expect(wrapper.text()).not.toContain('停用')
expect(wrapper.text()).not.toContain('AI 没有回应')
})
it('离开页面再回来用 GET 恢复同一段对话,不重新开启', async () => {
+8 -6
View File
@@ -5,7 +5,7 @@ import { useGuidanceSession } from "@/components/composables/useGuidance";
/**
* 学习引导对话框:围绕一个概念和 AI 多轮对话,随时可以把收获记成知识碎片或放弃。
* 不判分、不设轮数上限;AI 不可用时整体停用(入口由 guidanceUnavailable 控制)。
* 不判分、不设轮数上限;AI 失败只提示,入口随时可重试。
*/
const props = defineProps<{
modelValue: boolean;
@@ -26,12 +26,12 @@ const {
waiting,
waitingSeconds,
error,
unavailable,
open,
send,
confirmFragment,
abandon,
markInteraction,
reset,
} = useGuidanceSession();
const draft = ref("");
@@ -48,7 +48,10 @@ watch(
fragmentVisible.value = false;
fragmentContent.value = "";
void open(props.taskNum, props.concept);
return;
}
// 关闭弹窗即取消在途轮询(含本组件未被销毁的情况)
reset();
},
);
@@ -65,7 +68,6 @@ const sendTurn = async () => {
};
const openFragmentForm = () => {
if (unavailable.value) return;
fragmentVisible.value = true;
};
@@ -147,7 +149,7 @@ const giveUp = async () => {
:title="error"
/>
<div v-if="!unavailable && !session?.finished" class="guidance-input">
<div v-if="!session?.finished" class="guidance-input">
<el-input
v-model="draft"
type="textarea"
@@ -166,7 +168,7 @@ const giveUp = async () => {
>发送</el-button>
</div>
<div v-if="fragmentVisible && !unavailable" class="guidance-fragment-form">
<div v-if="fragmentVisible" class="guidance-fragment-form">
<span class="fragment-label">把这次引导的收获记成知识碎片</span>
<el-input
v-model="fragmentContent"
@@ -186,7 +188,7 @@ const giveUp = async () => {
<template #footer>
<el-button :disabled="ending" @click="giveUp">放弃这次引导</el-button>
<el-button
v-if="!unavailable && !session?.finished"
v-if="!session?.finished"
type="success"
:disabled="fragmentVisible || starting"
@click="openFragmentForm"
+2 -4
View File
@@ -13,7 +13,6 @@ import type { RecallCompareParams } from "@/api/aiTasks";
import { ElMessage, ElMessageBox } from "element-plus";
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
import GuidanceDialog from "@/components/GuidanceDialog.vue";
import { guidanceUnavailable } from "@/components/composables/useGuidance";
import {
isAiTaskCancelled,
useAiTask,
@@ -465,7 +464,7 @@ const handleNodeSelect = (node: { title: string; path: string; childCount: numbe
const guidance = ref<{ visible: boolean; concept: string }>({ visible: false, concept: "" });
const openGuidanceForNode = () => {
if (!selectedNodeInfo.value || guidanceUnavailable.value) return;
if (!selectedNodeInfo.value) return;
focusConfirmVisible.value = false;
guidance.value = { visible: true, concept: selectedNodeInfo.value.title };
};
@@ -513,8 +512,7 @@ onMounted(() => {
<template #footer>
<el-button @click="focusConfirmVisible = false">取消</el-button>
<el-button
:disabled="guidanceUnavailable"
:title="guidanceUnavailable ? 'AI 暂时用不了,学习引导已停用' : '和 AI 一起把这个概念聊透'"
title="和 AI 一起把这个概念聊透"
@click="openGuidanceForNode"
>学习引导</el-button>
<el-button type="success" @click="confirmFocus">确定</el-button>
+2 -4
View File
@@ -13,7 +13,6 @@ import {
import { updateFragmentOwnership } from "@/api/reportFragments";
import type { Marker } from "@/api/markers";
import { useMarkers } from "@/components/composables/useMarkers";
import { guidanceUnavailable } from "@/components/composables/useGuidance";
import MarkerChips from "@/components/MarkerChips.vue";
import GuidanceDialog from "@/components/GuidanceDialog.vue";
import {
@@ -193,7 +192,7 @@ const toggleFeedback = async (chip: FragmentChip, action: "mastered" | "revisit"
};
const openGuidance = (chip: FragmentChip) => {
if (!chip.taskNum || guidanceUnavailable.value) return;
if (!chip.taskNum) return;
guidance.value = { visible: true, taskNum: chip.taskNum, concept: chip.rawContent || chip.content };
};
@@ -521,8 +520,7 @@ onBeforeUnmount(() => {
v-if="chip.taskNum"
type="button"
class="chip-action chip-action-guidance"
:disabled="guidanceUnavailable"
:title="guidanceUnavailable ? 'AI 暂时用不了,学习引导已停用' : '和 AI 一起把这个概念聊透'"
title="和 AI 一起把这个概念聊透"
@click="openGuidance(chip)"
>学习引导</button>
</span>
+9 -30
View File
@@ -9,24 +9,9 @@ import {
type GuidanceSession,
type GuidanceTurn,
} from "@/api/guidance";
import { useAiTask } from "./useAiTask";
import { isAiTaskCancelled, useAiTask } from "./useAiTask";
import { useReviewDuration } from "./useReviewDuration";
/**
* 学习引导可用性:没有探测接口,一旦「首次提交失败 / AI 任务失败」就把入口整体置为不可用。
* 这是模块级状态,只影响引导本身,不牵连复习其他部分;刷新页面即复位。
*/
export const guidanceUnavailable = ref(false);
export const markGuidanceUnavailable = () => {
guidanceUnavailable.value = true;
};
/** 供测试复位模块级状态 */
export const resetGuidanceAvailability = () => {
guidanceUnavailable.value = false;
};
/** 从异常里取用户可见文案 */
const errorMessageOf = (error: unknown, fallback: string): string => {
if (error instanceof Error && error.message) return error.message;
@@ -66,11 +51,9 @@ export function useGuidanceSession() {
const sending = ref(false);
const error = ref("");
const aiTask = useAiTask();
const { seconds: waitingSeconds, running: waiting } = aiTask;
const { seconds: waitingSeconds, running: waiting, stop: stopPolling } = aiTask;
const { start: startDuration, markInteraction, snapshot, stop: stopDuration } = useReviewDuration();
const unavailable = guidanceUnavailable;
/** 轮询本轮 AI 任务,取出回复文本 */
const pollReply = async (aiTaskNum: string): Promise<string> => {
const result = await aiTask.poll(aiTaskNum);
@@ -86,6 +69,8 @@ export function useGuidanceSession() {
};
const reset = () => {
// 关弹窗/重开时取消在途轮询,避免无人等待的轮询结果影响下一次引导
stopPolling();
session.value = null;
turns.value = [];
starting.value = false;
@@ -119,11 +104,6 @@ export function useGuidanceSession() {
}
}
if (unavailable.value) {
error.value = "学习引导暂时用不了,可以先继续复习,等 AI 恢复后再来。";
return;
}
starting.value = true;
try {
const res = await startGuidance(taskNum, concept);
@@ -144,8 +124,8 @@ export function useGuidanceSession() {
const reply = await pollReply(data.aiTaskNum);
turns.value = [{ role: "assistant", content: reply }];
} catch (e) {
markGuidanceUnavailable();
error.value = errorMessageOf(e, "学习引导暂时用不了,可以先继续复习,等 AI 恢复后再来。");
if (isAiTaskCancelled(e)) return;
error.value = errorMessageOf(e, "学习引导没能开起来,请稍后再试");
} finally {
starting.value = false;
}
@@ -154,7 +134,7 @@ export function useGuidanceSession() {
/** 发送一轮:先回显用户输入,再轮询 AI 回复 */
const send = async (message: string): Promise<boolean> => {
const text = message.trim();
if (!session.value || !text || sending.value || waiting.value || unavailable.value) return false;
if (!session.value || !text || sending.value || waiting.value) return false;
sending.value = true;
error.value = "";
markInteraction();
@@ -167,8 +147,8 @@ export function useGuidanceSession() {
turns.value = [...turns.value, { role: "assistant", content: reply }];
return true;
} catch (e) {
markGuidanceUnavailable();
error.value = errorMessageOf(e, "AI 暂时没有回应,学习引导已停用,可以先继续复习。");
if (isAiTaskCancelled(e)) return false;
error.value = errorMessageOf(e, "AI 暂时没有回应,请稍后再试。");
return false;
} finally {
sending.value = false;
@@ -226,7 +206,6 @@ export function useGuidanceSession() {
waiting,
waitingSeconds,
error,
unavailable,
open,
send,
confirmFragment,