feat: AI 生成改为异步任务轮询
This commit is contained in:
@@ -0,0 +1,61 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||||
|
|
||||||
|
vi.mock('@/utils/request', () => ({
|
||||||
|
default: {
|
||||||
|
get: vi.fn(),
|
||||||
|
post: vi.fn(),
|
||||||
|
put: vi.fn(),
|
||||||
|
del: vi.fn(),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
import request from '@/utils/request'
|
||||||
|
import { submitAiTask, getAiTask, getLatestAiTask } from '@/api/aiTasks'
|
||||||
|
|
||||||
|
const mockedRequest = vi.mocked(request)
|
||||||
|
|
||||||
|
describe('aiTasks API', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks()
|
||||||
|
mockedRequest.post.mockResolvedValue({ code: 200, data: null })
|
||||||
|
mockedRequest.get.mockResolvedValue({ code: 200, data: null })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('submitAiTask 提交 type / targetNum / params', async () => {
|
||||||
|
await submitAiTask({
|
||||||
|
type: 'RECALL_COMPARE',
|
||||||
|
targetNum: 'T001',
|
||||||
|
params: { recallOutline: '根主题\n- 子节点' },
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(mockedRequest.post).toHaveBeenCalledWith('/ai/tasks', {
|
||||||
|
type: 'RECALL_COMPARE',
|
||||||
|
targetNum: 'T001',
|
||||||
|
params: { recallOutline: '根主题\n- 子节点' },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('submitAiTask 未传 params 时不发送 params 字段', async () => {
|
||||||
|
await submitAiTask({ type: 'REPORT_DRAFT', targetNum: 'S001' })
|
||||||
|
|
||||||
|
expect(mockedRequest.post).toHaveBeenCalledWith('/ai/tasks', {
|
||||||
|
type: 'REPORT_DRAFT',
|
||||||
|
targetNum: 'S001',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getAiTask 按任务编号查询状态', async () => {
|
||||||
|
await getAiTask('AI001')
|
||||||
|
|
||||||
|
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/tasks/AI001')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('getLatestAiTask 带 type 与 targetNum 查询最新任务', async () => {
|
||||||
|
await getLatestAiTask('MIND_MAP', 'T001')
|
||||||
|
|
||||||
|
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/tasks/latest', {
|
||||||
|
type: 'MIND_MAP',
|
||||||
|
targetNum: 'T001',
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -10,43 +10,39 @@ vi.mock('@/utils/request', () => ({
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
import request from '@/utils/request'
|
import request from '@/utils/request'
|
||||||
import { recallCompare } from '@/api/standardMindMap'
|
import {
|
||||||
|
getStandardMindMap,
|
||||||
|
listRecallRecords,
|
||||||
|
updateStandardMindMap,
|
||||||
|
} from '@/api/standardMindMap'
|
||||||
|
|
||||||
const mockedRequest = vi.mocked(request)
|
const mockedRequest = vi.mocked(request)
|
||||||
|
|
||||||
describe('standardMindMap API', () => {
|
describe('standardMindMap API', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
mockedRequest.post.mockResolvedValue({ code: 200, data: {} })
|
mockedRequest.get.mockResolvedValue({ code: 200, data: null })
|
||||||
|
mockedRequest.put.mockResolvedValue({ code: 200, data: {} })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('recallCompare 不带 timing 时不发送三个耗时字段', async () => {
|
it('getStandardMindMap 只读取导图,未生成时 data 为 null(不再自动生成)', async () => {
|
||||||
await recallCompare('T001', '根主题\n- 子节点')
|
const res = await getStandardMindMap('T001')
|
||||||
|
|
||||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
expect(mockedRequest.get).toHaveBeenCalledWith('/review/standard-mind-map/T001')
|
||||||
'/review/standard-mind-map/T001/recall',
|
expect(res.data).toBeNull()
|
||||||
{ recallOutline: '根主题\n- 子节点' },
|
|
||||||
{ timeout: 300_000 },
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
it('recallCompare 带 timing 时映射为后端字段', async () => {
|
it('updateStandardMindMap 提交大纲文本', async () => {
|
||||||
await recallCompare('T001', '根主题', '根主题 / 子节点', {
|
await updateStandardMindMap('T001', '根主题\n- 子节点')
|
||||||
startedAt: '2026-01-15T09:00:00',
|
|
||||||
lastInteractionAt: '2026-01-15T09:00:30',
|
expect(mockedRequest.put).toHaveBeenCalledWith('/review/standard-mind-map/T001', {
|
||||||
durationSeconds: 30,
|
outline: '根主题\n- 子节点',
|
||||||
})
|
})
|
||||||
|
})
|
||||||
|
|
||||||
expect(mockedRequest.post).toHaveBeenCalledWith(
|
it('listRecallRecords 拉取回忆对比记录', async () => {
|
||||||
'/review/standard-mind-map/T001/recall',
|
await listRecallRecords('T001')
|
||||||
{
|
|
||||||
recallOutline: '根主题',
|
expect(mockedRequest.get).toHaveBeenCalledWith('/review/standard-mind-map/T001/recall-records')
|
||||||
focusPath: '根主题 / 子节点',
|
|
||||||
reviewStartedAt: '2026-01-15T09:00:00',
|
|
||||||
reviewLastInteractionAt: '2026-01-15T09:00:30',
|
|
||||||
reviewDurationSeconds: 30,
|
|
||||||
},
|
|
||||||
{ timeout: 300_000 },
|
|
||||||
)
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
endSession: vi.fn(),
|
endSession: vi.fn(),
|
||||||
getActiveSession: vi.fn(),
|
getActiveSession: vi.fn(),
|
||||||
getExpectation: vi.fn(),
|
getExpectation: vi.fn(),
|
||||||
getReportDraft: vi.fn(),
|
|
||||||
getSessionDetail: vi.fn(),
|
getSessionDetail: vi.fn(),
|
||||||
getTaskFragments: vi.fn(),
|
getTaskFragments: vi.fn(),
|
||||||
getTaskReports: vi.fn(),
|
getTaskReports: vi.fn(),
|
||||||
@@ -32,6 +31,16 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
upsertExpectation: vi.fn(),
|
upsertExpectation: 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(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
vi.mock('@/api/reportFragments', () => ({
|
vi.mock('@/api/reportFragments', () => ({
|
||||||
createFragments: vi.fn(),
|
createFragments: vi.fn(),
|
||||||
getFragmentsBySession: vi.fn(),
|
getFragmentsBySession: vi.fn(),
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||||
|
import { defineComponent, h } from 'vue'
|
||||||
|
import { mount } from '@vue/test-utils'
|
||||||
|
import { useAiTask } from '@/components/composables/useAiTask'
|
||||||
|
import type { AiTask } from '@/api/aiTasks'
|
||||||
|
|
||||||
|
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(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
import {
|
||||||
|
AI_TASK_POLL_INTERVAL_MS,
|
||||||
|
getAiTask,
|
||||||
|
getLatestAiTask,
|
||||||
|
submitAiTask,
|
||||||
|
} from '@/api/aiTasks'
|
||||||
|
|
||||||
|
const ok = <T,>(data: T) => ({ code: 200, message: '请求成功', data })
|
||||||
|
|
||||||
|
const task = (overrides: Partial<AiTask> = {}): AiTask => ({
|
||||||
|
taskNum: 'AI001',
|
||||||
|
type: 'MIND_MAP',
|
||||||
|
targetNum: 'T001',
|
||||||
|
status: 'RUNNING',
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** 假定时器下推进时间并刷新微任务:单次推进不足以跑完“提交 → 轮询”的链式 promise */
|
||||||
|
const advancePolls = async (times = 3) => {
|
||||||
|
for (let i = 0; i < times; i++) {
|
||||||
|
await vi.advanceTimersByTimeAsync(AI_TASK_POLL_INTERVAL_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('useAiTask', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers()
|
||||||
|
vi.clearAllMocks()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('run 提交任务后轮询,SUCCEEDED 返回 result 并复位 running', async () => {
|
||||||
|
vi.mocked(submitAiTask).mockResolvedValue(ok(task({ status: 'PENDING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(ok(task({ status: 'SUCCEEDED', result: { standardMapId: 9 } })))
|
||||||
|
|
||||||
|
const { run, running } = useAiTask()
|
||||||
|
const promise = run('MIND_MAP', 'T001', { mode: 'full' })
|
||||||
|
|
||||||
|
await advancePolls()
|
||||||
|
await expect(promise).resolves.toEqual({ standardMapId: 9 })
|
||||||
|
|
||||||
|
expect(submitAiTask).toHaveBeenCalledWith({
|
||||||
|
type: 'MIND_MAP',
|
||||||
|
targetNum: 'T001',
|
||||||
|
params: { mode: 'full' },
|
||||||
|
})
|
||||||
|
expect(getAiTask).toHaveBeenCalledWith('AI001')
|
||||||
|
expect(running.value).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('轮询期间保持 running 并暴露已等待秒数', async () => {
|
||||||
|
vi.mocked(submitAiTask).mockResolvedValue(ok(task({ status: 'PENDING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(ok(task({ status: 'RUNNING' })))
|
||||||
|
|
||||||
|
const { run, running, seconds, stop } = useAiTask()
|
||||||
|
const promise = run('MIND_MAP', 'T001')
|
||||||
|
promise.catch(() => {})
|
||||||
|
|
||||||
|
await vi.advanceTimersByTimeAsync(3000)
|
||||||
|
|
||||||
|
expect(running.value).toBe(true)
|
||||||
|
expect(seconds.value).toBe(3)
|
||||||
|
|
||||||
|
stop()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('任务 FAILED 时抛出带 errorMessage 的错误', async () => {
|
||||||
|
vi.mocked(submitAiTask).mockResolvedValue(ok(task({ status: 'PENDING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(
|
||||||
|
ok(task({ status: 'FAILED', errorMessage: '思维导图生成失败' })),
|
||||||
|
)
|
||||||
|
|
||||||
|
const { run } = useAiTask()
|
||||||
|
|
||||||
|
await expect(run('MIND_MAP', 'T001')).rejects.toThrow('思维导图生成失败')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('组件卸载时停止轮询', async () => {
|
||||||
|
vi.mocked(submitAiTask).mockResolvedValue(ok(task({ status: 'PENDING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(ok(task({ status: 'RUNNING' })))
|
||||||
|
|
||||||
|
let exposed!: ReturnType<typeof useAiTask>
|
||||||
|
const Host = defineComponent({
|
||||||
|
setup() {
|
||||||
|
exposed = useAiTask()
|
||||||
|
return () => h('div')
|
||||||
|
},
|
||||||
|
})
|
||||||
|
const wrapper = mount(Host)
|
||||||
|
|
||||||
|
const promise = exposed.run('MIND_MAP', 'T001')
|
||||||
|
promise.catch(() => {})
|
||||||
|
await advancePolls()
|
||||||
|
const callsBeforeUnmount = vi.mocked(getAiTask).mock.calls.length
|
||||||
|
expect(callsBeforeUnmount).toBeGreaterThan(0)
|
||||||
|
|
||||||
|
wrapper.unmount()
|
||||||
|
await advancePolls(5)
|
||||||
|
|
||||||
|
expect(vi.mocked(getAiTask).mock.calls.length).toBe(callsBeforeUnmount)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resume 找到进行中的任务时继续轮询并返回结果', async () => {
|
||||||
|
vi.mocked(getLatestAiTask).mockResolvedValue(ok(task({ type: 'REPORT_DRAFT', status: 'RUNNING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(ok(task({ status: 'SUCCEEDED', result: { draft: '草稿' } })))
|
||||||
|
|
||||||
|
const { resume, running } = useAiTask()
|
||||||
|
const restore = await resume('REPORT_DRAFT', 'S001')
|
||||||
|
|
||||||
|
expect(getLatestAiTask).toHaveBeenCalledWith('REPORT_DRAFT', 'S001')
|
||||||
|
expect(restore.found).toBe(true)
|
||||||
|
await expect(restore.done).resolves.toEqual({ draft: '草稿' })
|
||||||
|
expect(running.value).toBe(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('resume 没有进行中的任务时 found=false 且不轮询', async () => {
|
||||||
|
vi.mocked(getLatestAiTask).mockResolvedValue(ok(task({ status: 'SUCCEEDED' })))
|
||||||
|
|
||||||
|
const { resume, running } = useAiTask()
|
||||||
|
const restore = await resume('MIND_MAP', 'T001')
|
||||||
|
|
||||||
|
expect(restore.found).toBe(false)
|
||||||
|
expect(restore.done).toBeNull()
|
||||||
|
expect(getAiTask).not.toHaveBeenCalled()
|
||||||
|
expect(running.value).toBe(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -3,23 +3,36 @@ import { flushPromises, mount } from '@vue/test-utils'
|
|||||||
import ElementPlus, { ElMessage } from 'element-plus'
|
import ElementPlus, { ElMessage } from 'element-plus'
|
||||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||||
import ReviewRecall from '@/components/ReviewRecall.vue'
|
import ReviewRecall from '@/components/ReviewRecall.vue'
|
||||||
import {
|
import { getStandardMindMap, listRecallRecords } from '@/api/standardMindMap'
|
||||||
getStandardMindMap,
|
import { getAiTask, getLatestAiTask, submitAiTask, type AiTask } from '@/api/aiTasks'
|
||||||
listRecallRecords,
|
|
||||||
recallCompare,
|
|
||||||
} from '@/api/standardMindMap'
|
|
||||||
|
|
||||||
vi.mock('@/api/standardMindMap', () => ({
|
vi.mock('@/api/standardMindMap', () => ({
|
||||||
findNode: vi.fn(),
|
findNode: vi.fn(),
|
||||||
getStandardMindMap: vi.fn(),
|
getStandardMindMap: vi.fn(),
|
||||||
listRecallRecords: vi.fn(),
|
listRecallRecords: vi.fn(),
|
||||||
recallCompare: vi.fn(),
|
|
||||||
regenerateStandardMindMap: vi.fn(),
|
|
||||||
updateStandardMindMap: vi.fn(),
|
updateStandardMindMap: 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 ok = (data: any = null) => ({ code: 200, message: '请求成功', data })
|
const ok = (data: any = null) => ({ code: 200, message: '请求成功', data })
|
||||||
|
|
||||||
|
const aiTask = (overrides: Partial<AiTask> = {}): AiTask => ({
|
||||||
|
taskNum: 'AI001',
|
||||||
|
type: 'MIND_MAP',
|
||||||
|
targetNum: 'T001',
|
||||||
|
status: 'SUCCEEDED',
|
||||||
|
...overrides,
|
||||||
|
})
|
||||||
|
|
||||||
const standardMap = {
|
const standardMap = {
|
||||||
id: 1,
|
id: 1,
|
||||||
taskNum: 'T001',
|
taskNum: 'T001',
|
||||||
@@ -42,7 +55,7 @@ const MindMapViewerStub = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 交互式集成测试:真实挂载 ReviewRecall,
|
* 交互式集成测试:真实挂载 ReviewRecall,
|
||||||
* 点击“提交对比”模拟回忆对比流,断言 API 参数与对比结果渲染。
|
* 点击“提交对比”模拟回忆对比流(提交 RECALL_COMPARE 任务 + 轮询),断言 API 参数与结果渲染。
|
||||||
*/
|
*/
|
||||||
describe('ReviewRecall 交互流程(集成)', () => {
|
describe('ReviewRecall 交互流程(集成)', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -77,13 +90,19 @@ describe('ReviewRecall 交互流程(集成)', () => {
|
|||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
)
|
)
|
||||||
vi.mocked(recallCompare).mockResolvedValue(ok(standardMap))
|
// 任务提交后立即成功:轮询本身由 useAiTask.spec.ts 覆盖
|
||||||
|
vi.mocked(submitAiTask).mockResolvedValue(ok(aiTask({ status: 'PENDING' })))
|
||||||
|
vi.mocked(getAiTask).mockResolvedValue(ok(aiTask({ result: { standardMapId: 1 } })))
|
||||||
|
vi.mocked(getLatestAiTask).mockResolvedValue(ok(null))
|
||||||
})
|
})
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.useRealTimers()
|
vi.useRealTimers()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const findButton = (wrapper: ReturnType<typeof mount>, label: string) =>
|
||||||
|
wrapper.findAll('button').find((b) => b.text().trim() === label)!
|
||||||
|
|
||||||
const mountPage = async () => {
|
const mountPage = async () => {
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createMemoryHistory(),
|
history: createMemoryHistory(),
|
||||||
@@ -102,21 +121,27 @@ describe('ReviewRecall 交互流程(集成)', () => {
|
|||||||
return { wrapper }
|
return { wrapper }
|
||||||
}
|
}
|
||||||
|
|
||||||
it('加载后展示标准导图标题,点击“提交对比”调用对比接口并渲染结果', async () => {
|
it('点击“提交对比”提交 RECALL_COMPARE 任务并轮询,渲染对比结果', async () => {
|
||||||
const { wrapper } = await mountPage()
|
const { wrapper } = await mountPage()
|
||||||
// 默认折叠标准导图(防剧透),回忆面板可见
|
// 默认折叠标准导图(防剧透),回忆面板可见
|
||||||
expect(wrapper.text()).toContain('你的回忆')
|
expect(wrapper.text()).toContain('你的回忆')
|
||||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
|
const submit = findButton(wrapper, '提交对比')
|
||||||
expect(submit).toBeTruthy()
|
expect(submit).toBeTruthy()
|
||||||
await submit.trigger('click')
|
await submit.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined, {
|
expect(submitAiTask).toHaveBeenCalledWith({
|
||||||
startedAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
|
type: 'RECALL_COMPARE',
|
||||||
lastInteractionAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
|
targetNum: 'T001',
|
||||||
durationSeconds: expect.any(Number),
|
params: {
|
||||||
|
recallOutline: '根主题\n- 子节点',
|
||||||
|
reviewStartedAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
|
||||||
|
reviewLastInteractionAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/),
|
||||||
|
reviewDurationSeconds: expect.any(Number),
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
expect(getAiTask).toHaveBeenCalledWith('AI001')
|
||||||
expect(ElMessage.success).toHaveBeenCalledWith('回忆对比完成')
|
expect(ElMessage.success).toHaveBeenCalledWith('回忆对比完成')
|
||||||
// 提交后统计卡片展示“本次耗时”
|
// 提交后统计卡片展示“本次耗时”
|
||||||
expect(wrapper.text()).toContain('本次耗时')
|
expect(wrapper.text()).toContain('本次耗时')
|
||||||
@@ -125,17 +150,17 @@ describe('ReviewRecall 交互流程(集成)', () => {
|
|||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
it('回忆导图内容为单行时点击“提交对比”,提示先添加节点且不调接口', async () => {
|
it('回忆导图内容为单行时点击“提交对比”,提示先添加节点且不提交任务', async () => {
|
||||||
const { wrapper } = await mountPage()
|
const { wrapper } = await mountPage()
|
||||||
toOutline.mockReturnValue('只有一个根')
|
toOutline.mockReturnValue('只有一个根')
|
||||||
|
|
||||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
|
const submit = findButton(wrapper, '提交对比')
|
||||||
await submit.trigger('click')
|
await submit.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
const { ElMessage: Msg } = await import('element-plus')
|
const { ElMessage: Msg } = await import('element-plus')
|
||||||
expect(Msg.warning).toHaveBeenCalledWith('请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)')
|
expect(Msg.warning).toHaveBeenCalledWith('请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)')
|
||||||
expect(recallCompare).not.toHaveBeenCalled()
|
expect(submitAiTask).not.toHaveBeenCalled()
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -149,17 +174,65 @@ describe('ReviewRecall 交互流程(集成)', () => {
|
|||||||
|
|
||||||
// 之后 20 秒无交互,直接点提交按钮
|
// 之后 20 秒无交互,直接点提交按钮
|
||||||
vi.setSystemTime(new Date(2026, 0, 15, 9, 0, 30))
|
vi.setSystemTime(new Date(2026, 0, 15, 9, 0, 30))
|
||||||
const submit = wrapper.findAll('button').find((b) => b.text().trim() === '提交对比')!
|
const submit = findButton(wrapper, '提交对比')
|
||||||
await submit.trigger('click')
|
await submit.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
expect(recallCompare).toHaveBeenCalledWith('T001', '根主题\n- 子节点', undefined, {
|
expect(submitAiTask).toHaveBeenCalledWith({
|
||||||
startedAt: '2026-01-15T09:00:00',
|
type: 'RECALL_COMPARE',
|
||||||
lastInteractionAt: '2026-01-15T09:00:10',
|
targetNum: 'T001',
|
||||||
durationSeconds: 30,
|
params: {
|
||||||
|
recallOutline: '根主题\n- 子节点',
|
||||||
|
reviewStartedAt: '2026-01-15T09:00:00',
|
||||||
|
reviewLastInteractionAt: '2026-01-15T09:00:10',
|
||||||
|
reviewDurationSeconds: 30,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
expect(wrapper.text()).toContain('30秒')
|
expect(wrapper.text()).toContain('30秒')
|
||||||
wrapper.unmount()
|
wrapper.unmount()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('标准导图不存在时自动提交 MIND_MAP(ensure) 任务并轮询补生成', async () => {
|
||||||
|
vi.mocked(getStandardMindMap)
|
||||||
|
.mockResolvedValueOnce(ok(null))
|
||||||
|
.mockResolvedValue(ok(standardMap))
|
||||||
|
|
||||||
|
const { wrapper } = await mountPage()
|
||||||
|
|
||||||
|
expect(submitAiTask).toHaveBeenCalledWith({
|
||||||
|
type: 'MIND_MAP',
|
||||||
|
targetNum: 'T001',
|
||||||
|
params: { mode: 'ensure' },
|
||||||
|
})
|
||||||
|
// 生成成功后重新拉取导图
|
||||||
|
expect(getStandardMindMap).toHaveBeenCalledTimes(2)
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('恢复查询失败时不阻塞页面,仍正常拉取标准导图', async () => {
|
||||||
|
vi.mocked(getLatestAiTask).mockRejectedValue(new Error('恢复查询失败'))
|
||||||
|
|
||||||
|
const { wrapper } = await mountPage()
|
||||||
|
|
||||||
|
expect(getStandardMindMap).toHaveBeenCalled()
|
||||||
|
expect(wrapper.text()).toContain('你的回忆')
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('重新进入页面时有进行中的对比任务,恢复结果展示且不重复提交', async () => {
|
||||||
|
vi.mocked(getLatestAiTask)
|
||||||
|
.mockResolvedValueOnce(ok(null))
|
||||||
|
.mockResolvedValueOnce(ok(aiTask({ type: 'RECALL_COMPARE', status: 'RUNNING' })))
|
||||||
|
|
||||||
|
const { wrapper } = await mountPage()
|
||||||
|
await flushPromises()
|
||||||
|
|
||||||
|
// 恢复而非重提
|
||||||
|
expect(submitAiTask).not.toHaveBeenCalled()
|
||||||
|
expect(getAiTask).toHaveBeenCalledWith('AI001')
|
||||||
|
expect(wrapper.text()).toContain('本次耗时')
|
||||||
|
expect(wrapper.findAll('button').some((b) => b.text().trim() === '清空重写')).toBe(true)
|
||||||
|
wrapper.unmount()
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
endSession: vi.fn(),
|
endSession: vi.fn(),
|
||||||
getActiveSession: vi.fn(),
|
getActiveSession: vi.fn(),
|
||||||
getExpectation: vi.fn(),
|
getExpectation: vi.fn(),
|
||||||
getReportDraft: vi.fn(),
|
|
||||||
getSessionDetail: vi.fn(),
|
getSessionDetail: vi.fn(),
|
||||||
getTaskFragments: vi.fn(),
|
getTaskFragments: vi.fn(),
|
||||||
getTaskReports: vi.fn(),
|
getTaskReports: vi.fn(),
|
||||||
@@ -30,6 +29,16 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
upsertExpectation: vi.fn(),
|
upsertExpectation: 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(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
vi.mock('@/api/reportFragments', () => ({
|
vi.mock('@/api/reportFragments', () => ({
|
||||||
createFragments: vi.fn(),
|
createFragments: vi.fn(),
|
||||||
getFragmentsBySession: vi.fn(),
|
getFragmentsBySession: vi.fn(),
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
endSession,
|
endSession,
|
||||||
getActiveSession,
|
getActiveSession,
|
||||||
getExpectation,
|
getExpectation,
|
||||||
getReportDraft,
|
|
||||||
getSessionDetail,
|
getSessionDetail,
|
||||||
pauseSession,
|
pauseSession,
|
||||||
startOrContinueStudySession,
|
startOrContinueStudySession,
|
||||||
@@ -21,7 +20,6 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
endSession: vi.fn(),
|
endSession: vi.fn(),
|
||||||
getActiveSession: vi.fn(),
|
getActiveSession: vi.fn(),
|
||||||
getExpectation: vi.fn(),
|
getExpectation: vi.fn(),
|
||||||
getReportDraft: vi.fn(),
|
|
||||||
getSessionDetail: vi.fn(),
|
getSessionDetail: vi.fn(),
|
||||||
getTaskFragments: vi.fn(),
|
getTaskFragments: vi.fn(),
|
||||||
getTaskReports: vi.fn(),
|
getTaskReports: vi.fn(),
|
||||||
@@ -30,12 +28,24 @@ vi.mock('@/api/studySessions', () => ({
|
|||||||
upsertExpectation: vi.fn(),
|
upsertExpectation: 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(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
vi.mock('@/api/reportFragments', () => ({
|
vi.mock('@/api/reportFragments', () => ({
|
||||||
createFragments: vi.fn(),
|
createFragments: vi.fn(),
|
||||||
getFragmentsBySession: vi.fn(),
|
getFragmentsBySession: vi.fn(),
|
||||||
updateFragments: vi.fn(),
|
updateFragments: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
import { submitAiTask } from '@/api/aiTasks'
|
||||||
|
|
||||||
const sessionOngoing = {
|
const sessionOngoing = {
|
||||||
sessionNum: 'SESSION_001',
|
sessionNum: 'SESSION_001',
|
||||||
sessionState: 'ONGOING',
|
sessionState: 'ONGOING',
|
||||||
@@ -133,9 +143,9 @@ describe('StartTask 交互流程(集成)', () => {
|
|||||||
await endBtn.trigger('click')
|
await endBtn.trigger('click')
|
||||||
await flushPromises()
|
await flushPromises()
|
||||||
|
|
||||||
// 总结弹窗出现(无残片 → 不触发 AI 草稿等待)
|
// 总结弹窗出现(无残片 → 不提交 AI 草稿任务)
|
||||||
expect(wrapper.text()).toContain('结束会话总结')
|
expect(wrapper.text()).toContain('结束会话总结')
|
||||||
expect(getReportDraft).not.toHaveBeenCalled()
|
expect(submitAiTask).not.toHaveBeenCalled()
|
||||||
|
|
||||||
// 总结内容为空时点击确认结束:弹警示、不调接口
|
// 总结内容为空时点击确认结束:弹警示、不调接口
|
||||||
const confirmEnd = findButton(wrapper, '确认结束')
|
const confirmEnd = findButton(wrapper, '确认结束')
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
// src/api/aiTasks.ts
|
||||||
|
import request from "@/utils/request";
|
||||||
|
|
||||||
|
/** AI 异步任务类型 */
|
||||||
|
export type AiTaskType = "RECALL_COMPARE" | "MIND_MAP" | "REPORT_DRAFT";
|
||||||
|
|
||||||
|
export type AiTaskStatus = "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED";
|
||||||
|
|
||||||
|
/** AI 异步任务:提交秒级返回,之后由前端轮询状态 */
|
||||||
|
export interface AiTask {
|
||||||
|
taskNum: string;
|
||||||
|
type: AiTaskType;
|
||||||
|
targetNum: string;
|
||||||
|
status: AiTaskStatus;
|
||||||
|
errorMessage?: string | null;
|
||||||
|
createdTime?: string;
|
||||||
|
finishedTime?: string;
|
||||||
|
/** 仅 SUCCEEDED 时非空 */
|
||||||
|
result?: Record<string, unknown> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 任务结果载荷(各 type 的字段见后端契约) */
|
||||||
|
export type AiTaskResult = Record<string, unknown>;
|
||||||
|
|
||||||
|
/** 提交任务时透传给后端的业务参数 */
|
||||||
|
export type AiTaskParams = Record<string, unknown>;
|
||||||
|
|
||||||
|
/** RECALL_COMPARE:targetNum 为任务编号,三个时间字段沿用复习耗时快照 */
|
||||||
|
export type RecallCompareParams = {
|
||||||
|
recallOutline: string;
|
||||||
|
focusPath?: string;
|
||||||
|
reviewStartedAt?: string;
|
||||||
|
reviewLastInteractionAt?: string;
|
||||||
|
reviewDurationSeconds?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** MIND_MAP:ensure 仅在不存在时生成,full 全量重新生成,incremental 增量合并 */
|
||||||
|
export type MindMapParams = {
|
||||||
|
mode: "full" | "incremental" | "ensure";
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 轮询间隔(毫秒):提交本身秒级返回,后续进度靠轮询获取 */
|
||||||
|
export const AI_TASK_POLL_INTERVAL_MS = 2000;
|
||||||
|
|
||||||
|
export interface SubmitAiTaskPayload {
|
||||||
|
type: AiTaskType;
|
||||||
|
targetNum: string;
|
||||||
|
params?: AiTaskParams;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isAiTaskInProgress = (
|
||||||
|
task: AiTask | null | undefined,
|
||||||
|
): task is AiTask => !!task && (task.status === "PENDING" || task.status === "RUNNING");
|
||||||
|
|
||||||
|
/** 提交 AI 异步任务,返回任务快照 */
|
||||||
|
export const submitAiTask = (payload: SubmitAiTaskPayload) => {
|
||||||
|
const body: SubmitAiTaskPayload = { type: payload.type, targetNum: payload.targetNum };
|
||||||
|
if (payload.params) body.params = payload.params;
|
||||||
|
return request.post<AiTask>("/ai/tasks", body);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 按任务编号查询任务状态 */
|
||||||
|
export const getAiTask = (taskNum: string) => {
|
||||||
|
return request.get<AiTask>(`/ai/tasks/${taskNum}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 查询指定类型 + 目标下最新的任务(用于离开页面再回来时恢复生成状态) */
|
||||||
|
export const getLatestAiTask = (type: AiTaskType, targetNum: string) => {
|
||||||
|
return request.get<AiTask | null>("/ai/tasks/latest", { type, targetNum });
|
||||||
|
};
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import request from "@/utils/request";
|
import request from "@/utils/request";
|
||||||
import type { ApiResponse } from "@/utils/request";
|
|
||||||
|
|
||||||
// ============ 标准思维导图 ============
|
// ============ 标准思维导图 ============
|
||||||
|
|
||||||
@@ -33,24 +32,9 @@ export interface RecallRecord {
|
|||||||
reviewDurationSeconds?: number;
|
reviewDurationSeconds?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 回忆对比耗时口径:本地时间字符串(yyyy-MM-ddTHH:mm:ss,无时区)+ 秒数 */
|
/** 获取标准思维导图:不再自动生成,未生成时 data 为 null(生成走 MIND_MAP 异步任务) */
|
||||||
export interface RecallTiming {
|
|
||||||
startedAt: string;
|
|
||||||
lastInteractionAt: string;
|
|
||||||
durationSeconds: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
// AI 聚合类接口耗时较长,统一放宽到 5 分钟(默认全局 30s)
|
|
||||||
const AI_TIMEOUT = { timeout: 300_000 };
|
|
||||||
|
|
||||||
/** 获取/自动生成标准思维导图(首次访问会触发 AI 生成) */
|
|
||||||
export const getStandardMindMap = (taskNum: string) => {
|
export const getStandardMindMap = (taskNum: string) => {
|
||||||
return request.get<StandardMindMap>(`/review/standard-mind-map/${taskNum}`, {}, AI_TIMEOUT);
|
return request.get<StandardMindMap | null>(`/review/standard-mind-map/${taskNum}`);
|
||||||
};
|
|
||||||
|
|
||||||
/** 强制重新生成标准思维导图(全量或增量) */
|
|
||||||
export const regenerateStandardMindMap = (taskNum: string, mode: "full" | "incremental" = "full") => {
|
|
||||||
return request.post<StandardMindMap>(`/review/standard-mind-map/${taskNum}/regenerate?mode=${mode}`, null, AI_TIMEOUT);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 用户编辑标准思维导图(大纲文本) */
|
/** 用户编辑标准思维导图(大纲文本) */
|
||||||
@@ -58,23 +42,6 @@ export const updateStandardMindMap = (taskNum: string, outline: string) => {
|
|||||||
return request.put(`/review/standard-mind-map/${taskNum}`, { outline });
|
return request.put(`/review/standard-mind-map/${taskNum}`, { outline });
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 用户提交回忆大纲,与标准导图对比(可选指定起始节点路径与复习耗时口径) */
|
|
||||||
export const recallCompare = (
|
|
||||||
taskNum: string,
|
|
||||||
recallOutline: string,
|
|
||||||
focusPath?: string,
|
|
||||||
timing?: RecallTiming,
|
|
||||||
): Promise<ApiResponse<StandardMindMap>> => {
|
|
||||||
const body: Record<string, any> = { recallOutline };
|
|
||||||
if (focusPath) body.focusPath = focusPath;
|
|
||||||
if (timing) {
|
|
||||||
body.reviewStartedAt = timing.startedAt;
|
|
||||||
body.reviewLastInteractionAt = timing.lastInteractionAt;
|
|
||||||
body.reviewDurationSeconds = timing.durationSeconds;
|
|
||||||
}
|
|
||||||
return request.post(`/review/standard-mind-map/${taskNum}/recall`, body, AI_TIMEOUT);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 在标准导图中查找与内容最匹配的节点 */
|
/** 在标准导图中查找与内容最匹配的节点 */
|
||||||
export const findNode = (taskNum: string, content: string) => {
|
export const findNode = (taskNum: string, content: string) => {
|
||||||
return request.post<{ path: string }>(`/review/standard-mind-map/${taskNum}/find-node`, { content });
|
return request.post<{ path: string }>(`/review/standard-mind-map/${taskNum}/find-node`, { content });
|
||||||
|
|||||||
@@ -77,11 +77,6 @@ export const upsertExpectation = (sessionNum: string, description: string) => {
|
|||||||
return request.put(`/study-sessions/${sessionNum}/expectation`, { description });
|
return request.put(`/study-sessions/${sessionNum}/expectation`, { description });
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 获取报告草稿(AI 聚合残片,不可用时为拼接),生成失败不阻塞手写总结 */
|
|
||||||
export const getReportDraft = (sessionNum: string) => {
|
|
||||||
return request.get<string>(`/study-sessions/${sessionNum}/report-draft`, {}, AI_TIMEOUT);
|
|
||||||
};
|
|
||||||
|
|
||||||
/** 查询当前是否有活跃会话 */
|
/** 查询当前是否有活跃会话 */
|
||||||
export const getActiveSession = (excludeTaskNum?: string) => {
|
export const getActiveSession = (excludeTaskNum?: string) => {
|
||||||
const params: Record<string, any> = {};
|
const params: Record<string, any> = {};
|
||||||
|
|||||||
+110
-54
@@ -4,16 +4,19 @@ import { useRoute, useRouter } from "vue-router";
|
|||||||
import {
|
import {
|
||||||
findNode,
|
findNode,
|
||||||
getStandardMindMap,
|
getStandardMindMap,
|
||||||
regenerateStandardMindMap,
|
|
||||||
recallCompare,
|
|
||||||
updateStandardMindMap,
|
updateStandardMindMap,
|
||||||
listRecallRecords,
|
listRecallRecords,
|
||||||
type StandardMindMap,
|
type StandardMindMap,
|
||||||
type RecallRecord,
|
type RecallRecord,
|
||||||
} from "@/api/standardMindMap";
|
} from "@/api/standardMindMap";
|
||||||
|
import type { RecallCompareParams } from "@/api/aiTasks";
|
||||||
import { ElMessage, ElMessageBox } from "element-plus";
|
import { ElMessage, ElMessageBox } from "element-plus";
|
||||||
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
|
import MindMapViewer, { type MindMapTreeNode } from "@/components/MindMapViewer.vue";
|
||||||
import { useElapsedSeconds } from "@/components/composables/useElapsedSeconds";
|
import {
|
||||||
|
isAiTaskCancelled,
|
||||||
|
useAiTask,
|
||||||
|
type AiTaskRestore,
|
||||||
|
} from "@/components/composables/useAiTask";
|
||||||
import { useReviewDuration } from "@/components/composables/useReviewDuration";
|
import { useReviewDuration } from "@/components/composables/useReviewDuration";
|
||||||
import { formatDurationSeconds } from "@/utils/format";
|
import { formatDurationSeconds } from "@/utils/format";
|
||||||
|
|
||||||
@@ -23,12 +26,16 @@ const taskNum = computed(() => route.params.taskNum as string);
|
|||||||
|
|
||||||
const loading = ref(false);
|
const loading = ref(false);
|
||||||
const standard = ref<StandardMindMap | null>(null);
|
const standard = ref<StandardMindMap | null>(null);
|
||||||
const comparing = ref(false);
|
|
||||||
const {
|
// AI 异步任务:提交后轮询到结束;已等待秒数与进行状态由 composable 提供
|
||||||
seconds: comparingSeconds,
|
const mindMapTask = useAiTask();
|
||||||
start: startComparingTimer,
|
const { running: regenerating, seconds: regeneratingSeconds } = mindMapTask;
|
||||||
stop: stopComparingTimer,
|
const recallTask = useAiTask();
|
||||||
} = useElapsedSeconds();
|
const { running: comparing, seconds: comparingSeconds } = recallTask;
|
||||||
|
|
||||||
|
/** 从异常里取用户可见文案 */
|
||||||
|
const errorMessageOf = (error: unknown, fallback: string): string =>
|
||||||
|
error instanceof Error && error.message ? error.message : fallback;
|
||||||
|
|
||||||
// 复习耗时:从标准导图加载完成开始,记录到提交对比结束(超 5 分钟无交互自动截断)
|
// 复习耗时:从标准导图加载完成开始,记录到提交对比结束(超 5 分钟无交互自动截断)
|
||||||
const {
|
const {
|
||||||
@@ -39,14 +46,6 @@ const {
|
|||||||
} = useReviewDuration();
|
} = useReviewDuration();
|
||||||
const currentDurationSeconds = ref(0);
|
const currentDurationSeconds = ref(0);
|
||||||
|
|
||||||
// 重新生成标准导图
|
|
||||||
const regenerating = ref(false);
|
|
||||||
|
|
||||||
const {
|
|
||||||
seconds: regeneratingSeconds,
|
|
||||||
start: startRegeneratingTimer,
|
|
||||||
stop: stopRegeneratingTimer,
|
|
||||||
} = useElapsedSeconds();
|
|
||||||
const lastResult = ref<any>(null);
|
const lastResult = ref<any>(null);
|
||||||
const hasCompared = ref(false);
|
const hasCompared = ref(false);
|
||||||
|
|
||||||
@@ -130,10 +129,76 @@ const parseOutlineToTree = (text: string): MindMapTreeNode | null => {
|
|||||||
return root;
|
return root;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 重新拉取标准导图(生成/对比完成后使用)
|
||||||
|
const refreshStandardMap = async () => {
|
||||||
|
const res = await getStandardMindMap(taskNum.value);
|
||||||
|
standard.value = res?.data || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 拉取最新的回忆对比记录并展示结果
|
||||||
|
const loadComparisonResult = async () => {
|
||||||
|
const recordRes = await listRecallRecords(taskNum.value);
|
||||||
|
const records: RecallRecord[] = recordRes?.data || [];
|
||||||
|
historyRecords.value = records;
|
||||||
|
if (records.length === 0) return;
|
||||||
|
const latest = records[0];
|
||||||
|
try {
|
||||||
|
lastResult.value = JSON.parse(latest.compareResult);
|
||||||
|
} catch {
|
||||||
|
lastResult.value = null;
|
||||||
|
}
|
||||||
|
hasCompared.value = true;
|
||||||
|
currentDurationSeconds.value = latest.reviewDurationSeconds ?? currentDurationSeconds.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 提交 MIND_MAP(ensure) 任务:接口不再自动生成,没有导图时由前端触发
|
||||||
|
const ensureStandardMindMap = async () => {
|
||||||
|
try {
|
||||||
|
await mindMapTask.run("MIND_MAP", taskNum.value, { mode: "ensure" });
|
||||||
|
await refreshStandardMap();
|
||||||
|
} catch (e) {
|
||||||
|
if (isAiTaskCancelled(e)) return;
|
||||||
|
ElMessage.error(errorMessageOf(e, "标准思维导图生成失败,请稍后重试"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 重新进入页面时恢复仍在进行的任务,避免用户重复提交;返回是否有进行中的生成任务 */
|
||||||
|
const resumeInProgressTasks = async (): Promise<boolean> => {
|
||||||
|
let mindMap: AiTaskRestore;
|
||||||
|
let compare: AiTaskRestore;
|
||||||
|
try {
|
||||||
|
[mindMap, compare] = await Promise.all([
|
||||||
|
mindMapTask.resume("MIND_MAP", taskNum.value),
|
||||||
|
recallTask.resume("RECALL_COMPARE", taskNum.value),
|
||||||
|
]);
|
||||||
|
} catch {
|
||||||
|
// 恢复查询失败不阻塞页面加载,退化为正常拉取
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (mindMap.done) {
|
||||||
|
void mindMap.done
|
||||||
|
.then(() => refreshStandardMap())
|
||||||
|
.catch(() => {
|
||||||
|
// 恢复失败不打断当前页面,用户可手动重新生成
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (compare.done) {
|
||||||
|
void compare.done
|
||||||
|
.then(() => loadComparisonResult())
|
||||||
|
.then(() => resetReviewDuration())
|
||||||
|
.catch(() => {
|
||||||
|
// 恢复失败不打断当前页面
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return mindMap.found;
|
||||||
|
};
|
||||||
|
|
||||||
// 加载数据
|
// 加载数据
|
||||||
const loadData = async () => {
|
const loadData = async () => {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
try {
|
try {
|
||||||
|
const mindMapInProgress = await resumeInProgressTasks();
|
||||||
|
|
||||||
const res = await getStandardMindMap(taskNum.value);
|
const res = await getStandardMindMap(taskNum.value);
|
||||||
standard.value = res?.data || null;
|
standard.value = res?.data || null;
|
||||||
if (focusContent.value && standard.value) {
|
if (focusContent.value && standard.value) {
|
||||||
@@ -147,6 +212,11 @@ const loadData = async () => {
|
|||||||
// 匹配失败时仍可进入回忆页
|
// 匹配失败时仍可进入回忆页
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 接口不再自动生成:无导图且没有进行中的生成任务时,提交 ensure 任务补齐
|
||||||
|
if (!standard.value && !mindMapInProgress) {
|
||||||
|
await ensureStandardMindMap();
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
standard.value = null;
|
standard.value = null;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -201,8 +271,8 @@ const handleRegenerate = async () => {
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
// confirm → 全量(保持 mode = "full")
|
// confirm → 全量(保持 mode = "full")
|
||||||
} catch (e: any) {
|
} catch (e) {
|
||||||
if (e === "cancel" || e?.toString()?.includes("cancel")) {
|
if (e === "cancel" || String(e).includes("cancel")) {
|
||||||
mode = "incremental";
|
mode = "incremental";
|
||||||
} else {
|
} else {
|
||||||
return; // 点 X 关闭 → 不做操作
|
return; // 点 X 关闭 → 不做操作
|
||||||
@@ -221,59 +291,45 @@ const handleRegenerate = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 开始生成
|
// 提交 MIND_MAP 任务并轮询
|
||||||
regenerating.value = true;
|
|
||||||
startRegeneratingTimer();
|
|
||||||
try {
|
try {
|
||||||
const res = await regenerateStandardMindMap(taskNum.value, mode);
|
await mindMapTask.run("MIND_MAP", taskNum.value, { mode });
|
||||||
standard.value = res?.data || null;
|
await refreshStandardMap();
|
||||||
ElMessage.success(mode === "incremental" ? "标准思维导图已增量更新" : "标准思维导图已重新生成");
|
ElMessage.success(mode === "incremental" ? "标准思维导图已增量更新" : "标准思维导图已重新生成");
|
||||||
} catch (e: any) {
|
} catch (e) {
|
||||||
ElMessage.error(e.message || "重新生成失败");
|
if (isAiTaskCancelled(e)) return;
|
||||||
} finally {
|
ElMessage.error(errorMessageOf(e, "重新生成失败"));
|
||||||
regenerating.value = false;
|
|
||||||
stopRegeneratingTimer();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 提交回忆对比
|
// 提交回忆对比:提交 RECALL_COMPARE 任务并轮询
|
||||||
const handleRecallCompare = async () => {
|
const handleRecallCompare = async () => {
|
||||||
const outline = recallViewer.value?.toOutline() || "";
|
const outline = recallViewer.value?.toOutline() || "";
|
||||||
if (outline.split(/\r?\n/).filter((l) => l.trim()).length <= 1) {
|
if (outline.split(/\r?\n/).filter((l) => l.trim()).length <= 1) {
|
||||||
ElMessage.warning("请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)");
|
ElMessage.warning("请先在回忆导图中添加节点(选中节点后按 Tab 加子节点)");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
comparing.value = true;
|
|
||||||
startComparingTimer();
|
|
||||||
// 提交按钮本身不计入交互,这里取提交前的耗时快照
|
// 提交按钮本身不计入交互,这里取提交前的耗时快照
|
||||||
const timing = reviewDurationSnapshot();
|
const timing = reviewDurationSnapshot();
|
||||||
|
const params: RecallCompareParams = {
|
||||||
|
recallOutline: outline,
|
||||||
|
reviewStartedAt: timing.startedAt,
|
||||||
|
reviewLastInteractionAt: timing.lastInteractionAt,
|
||||||
|
reviewDurationSeconds: timing.durationSeconds,
|
||||||
|
};
|
||||||
|
if (focusPath.value) params.focusPath = focusPath.value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await recallCompare(taskNum.value, outline, focusPath.value || undefined, timing);
|
await recallTask.run("RECALL_COMPARE", taskNum.value, params);
|
||||||
standard.value = res?.data || null;
|
|
||||||
hasCompared.value = true;
|
|
||||||
currentDurationSeconds.value = timing.durationSeconds;
|
currentDurationSeconds.value = timing.durationSeconds;
|
||||||
// 解析对比结果
|
await refreshStandardMap();
|
||||||
if (standard.value) {
|
await loadComparisonResult();
|
||||||
const recordRes = await listRecallRecords(taskNum.value);
|
|
||||||
const records: RecallRecord[] = recordRes?.data || [];
|
|
||||||
if (records.length > 0) {
|
|
||||||
const latest = records[0];
|
|
||||||
try {
|
|
||||||
lastResult.value = JSON.parse(latest.compareResult);
|
|
||||||
} catch {
|
|
||||||
lastResult.value = null;
|
|
||||||
}
|
|
||||||
historyRecords.value = records;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 提交成功后开启新一轮计时
|
// 提交成功后开启新一轮计时
|
||||||
resetReviewDuration();
|
resetReviewDuration();
|
||||||
ElMessage.success("回忆对比完成");
|
ElMessage.success("回忆对比完成");
|
||||||
} catch (e: any) {
|
} catch (e) {
|
||||||
ElMessage.error(e.message || "对比失败");
|
if (isAiTaskCancelled(e)) return;
|
||||||
} finally {
|
ElMessage.error(errorMessageOf(e, "对比失败"));
|
||||||
comparing.value = false;
|
|
||||||
stopComparingTimer();
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// src/components/composables/useAiTask.ts
|
||||||
|
import { getCurrentInstance, onUnmounted, ref } from "vue";
|
||||||
|
import {
|
||||||
|
AI_TASK_POLL_INTERVAL_MS,
|
||||||
|
getAiTask,
|
||||||
|
getLatestAiTask,
|
||||||
|
isAiTaskInProgress,
|
||||||
|
submitAiTask,
|
||||||
|
type AiTaskParams,
|
||||||
|
type AiTaskResult,
|
||||||
|
type AiTaskType,
|
||||||
|
} from "@/api/aiTasks";
|
||||||
|
import { useElapsedSeconds } from "./useElapsedSeconds";
|
||||||
|
|
||||||
|
/** 轮询期间组件被卸载/主动停止时抛出,调用方应静默忽略,不再弹提示 */
|
||||||
|
export class AiTaskCancelledError extends Error {
|
||||||
|
constructor() {
|
||||||
|
super("AI 任务轮询已取消");
|
||||||
|
this.name = "AiTaskCancelledError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isAiTaskCancelled = (error: unknown): boolean =>
|
||||||
|
error instanceof AiTaskCancelledError;
|
||||||
|
|
||||||
|
/** resume 的返回:found 表示存在进行中的任务,done 是它的轮询结果 */
|
||||||
|
export interface AiTaskRestore {
|
||||||
|
found: boolean;
|
||||||
|
done: Promise<AiTaskResult> | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 异步任务轮询:把「提交 → 轮询 → 返回 result」串成一次 await。
|
||||||
|
* - run():提交新任务并轮询到结束,SUCCEEDED 返回 result,FAILED 抛出带 errorMessage 的错误
|
||||||
|
* - resume():用 getLatestAiTask 判断是否有进行中的任务,有则继续轮询(刷新/重进页面恢复等待态)
|
||||||
|
* - seconds:已等待秒数,供“AI 正在生成,已等待 N 秒”文案使用
|
||||||
|
* 组件卸载时自动停止轮询,进行中的 run/resume 会以 AiTaskCancelledError 结束。
|
||||||
|
*/
|
||||||
|
export function useAiTask() {
|
||||||
|
const { seconds, start: startTimer, stop: stopTimer } = useElapsedSeconds();
|
||||||
|
const running = ref(false);
|
||||||
|
let cancelled = false;
|
||||||
|
/** 每次 run/resume 递增,避免旧调用的收尾影响新调用 */
|
||||||
|
let generation = 0;
|
||||||
|
let pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
let wakePoll: (() => void) | null = null;
|
||||||
|
|
||||||
|
const clearPendingPoll = () => {
|
||||||
|
if (pollTimer !== null) {
|
||||||
|
clearTimeout(pollTimer);
|
||||||
|
pollTimer = null;
|
||||||
|
}
|
||||||
|
if (wakePoll) {
|
||||||
|
const wake = wakePoll;
|
||||||
|
wakePoll = null;
|
||||||
|
wake();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
cancelled = true;
|
||||||
|
generation += 1;
|
||||||
|
running.value = false;
|
||||||
|
clearPendingPoll();
|
||||||
|
stopTimer();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (getCurrentInstance()) {
|
||||||
|
onUnmounted(stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 等待下一次轮询;stop() 会立即唤醒它以便轮询循环退出 */
|
||||||
|
const waitNextPoll = () =>
|
||||||
|
new Promise<void>((resolve) => {
|
||||||
|
wakePoll = resolve;
|
||||||
|
pollTimer = setTimeout(() => {
|
||||||
|
pollTimer = null;
|
||||||
|
wakePoll = null;
|
||||||
|
resolve();
|
||||||
|
}, AI_TASK_POLL_INTERVAL_MS);
|
||||||
|
});
|
||||||
|
|
||||||
|
const pollUntilDone = async (aiTaskNum: string): Promise<AiTaskResult> => {
|
||||||
|
for (;;) {
|
||||||
|
if (cancelled) throw new AiTaskCancelledError();
|
||||||
|
const res = await getAiTask(aiTaskNum);
|
||||||
|
const task = res?.data;
|
||||||
|
if (!task) throw new Error("AI 任务状态查询失败,请稍后重试");
|
||||||
|
if (task.status === "SUCCEEDED") return task.result ?? {};
|
||||||
|
if (task.status === "FAILED") throw new Error(task.errorMessage || "AI 处理失败,请稍后重试");
|
||||||
|
await waitNextPoll();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const startTracking = () => {
|
||||||
|
cancelled = false;
|
||||||
|
generation += 1;
|
||||||
|
running.value = true;
|
||||||
|
startTimer();
|
||||||
|
return generation;
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopTracking = (token: number) => {
|
||||||
|
if (token !== generation) return;
|
||||||
|
running.value = false;
|
||||||
|
stopTimer();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 提交 AI 任务并轮询到结束,返回 SUCCEEDED 的 result */
|
||||||
|
const run = async (
|
||||||
|
type: AiTaskType,
|
||||||
|
targetNum: string,
|
||||||
|
params?: AiTaskParams,
|
||||||
|
): Promise<AiTaskResult> => {
|
||||||
|
const token = startTracking();
|
||||||
|
try {
|
||||||
|
const res = await submitAiTask(params ? { type, targetNum, params } : { type, targetNum });
|
||||||
|
const submitted = res?.data;
|
||||||
|
if (!submitted?.taskNum) throw new Error("AI 任务提交失败,请稍后重试");
|
||||||
|
return await pollUntilDone(submitted.taskNum);
|
||||||
|
} finally {
|
||||||
|
stopTracking(token);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 恢复进行中的任务:找到就继续轮询,没找到返回 found=false */
|
||||||
|
const resume = async (type: AiTaskType, targetNum: string): Promise<AiTaskRestore> => {
|
||||||
|
const res = await getLatestAiTask(type, targetNum);
|
||||||
|
const latest = res?.data;
|
||||||
|
if (!isAiTaskInProgress(latest)) return { found: false, done: null };
|
||||||
|
const token = startTracking();
|
||||||
|
const done = pollUntilDone(latest.taskNum).finally(() => stopTracking(token));
|
||||||
|
return { found: true, done };
|
||||||
|
};
|
||||||
|
|
||||||
|
return { seconds, running, run, resume, stop };
|
||||||
|
}
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import { getReportDraft } from '@/api/studySessions';
|
import { useAiTask } from './useAiTask';
|
||||||
import { useElapsedSeconds } from './useElapsedSeconds';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* “结束会话总结”弹窗:编辑/预览总结内容。
|
* “结束会话总结”弹窗:编辑/预览总结内容。
|
||||||
* 有学习残片且尚未填写内容时,先取 AI 聚合草稿作为编辑起点(失败不阻塞手写),
|
* 有学习残片且尚未填写内容时,先提交 REPORT_DRAFT 任务并轮询取回草稿作为编辑起点(失败不阻塞手写),
|
||||||
* 等待期间展示“已等待 N 秒”提示。
|
* 等待期间展示“已等待 N 秒”提示。
|
||||||
*/
|
*/
|
||||||
export function useSummaryReport(options: {
|
export function useSummaryReport(options: {
|
||||||
@@ -15,31 +14,30 @@ export function useSummaryReport(options: {
|
|||||||
const summaryContent = ref("");
|
const summaryContent = ref("");
|
||||||
const summaryPreview = ref(false);
|
const summaryPreview = ref(false);
|
||||||
const summaryLoading = ref(false);
|
const summaryLoading = ref(false);
|
||||||
const { seconds: summaryLoadingSeconds, start: startLoadingTimer, stop: stopLoadingTimer } = useElapsedSeconds();
|
const reportTask = useAiTask();
|
||||||
|
|
||||||
const openSummaryDialog = async () => {
|
const openSummaryDialog = async () => {
|
||||||
summaryDialogVisible.value = true;
|
summaryDialogVisible.value = true;
|
||||||
// 有残片且未填写过总结时,用 AI 聚合草稿作为编辑起点
|
// 有残片且未填写过总结时,用 AI 聚合草稿作为编辑起点
|
||||||
if (!summaryContent.value.trim() && options.hasFragments()) {
|
if (!summaryContent.value.trim() && options.hasFragments()) {
|
||||||
summaryLoading.value = true;
|
summaryLoading.value = true;
|
||||||
startLoadingTimer();
|
|
||||||
try {
|
try {
|
||||||
const res = await getReportDraft(options.getSessionNum());
|
const result = await reportTask.run("REPORT_DRAFT", options.getSessionNum());
|
||||||
if (res?.code === 200 && res.data) {
|
const draft = result?.draft;
|
||||||
summaryContent.value = res.data;
|
if (typeof draft === "string" && draft) {
|
||||||
|
summaryContent.value = draft;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 草稿失败不阻塞手写
|
// 草稿失败不阻塞手写
|
||||||
} finally {
|
} finally {
|
||||||
summaryLoading.value = false;
|
summaryLoading.value = false;
|
||||||
stopLoadingTimer();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeSummaryDialog = () => {
|
const closeSummaryDialog = () => {
|
||||||
summaryDialogVisible.value = false;
|
summaryDialogVisible.value = false;
|
||||||
stopLoadingTimer();
|
reportTask.stop();
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -47,7 +45,7 @@ export function useSummaryReport(options: {
|
|||||||
summaryContent,
|
summaryContent,
|
||||||
summaryPreview,
|
summaryPreview,
|
||||||
summaryLoading,
|
summaryLoading,
|
||||||
summaryLoadingSeconds,
|
summaryLoadingSeconds: reportTask.seconds,
|
||||||
openSummaryDialog,
|
openSummaryDialog,
|
||||||
closeSummaryDialog,
|
closeSummaryDialog,
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user