feat: 活跃会话拦截补结束与放弃出口

This commit is contained in:
2026-10-09 12:42:59 +08:00
parent 87e4ceab11
commit 25fbc67ad2
4 changed files with 372 additions and 15 deletions
+13 -2
View File
@@ -149,16 +149,27 @@ describe('StartTask.vue', () => {
wrapper.unmount()
})
it('redirects to another active task when one exists', async () => {
it('redirects to another active task only after the user picks 前往继续', async () => {
vi.mocked(getActiveSession).mockResolvedValue({
code: 200,
data: { taskNum: 'T002', taskName: '其他任务', sessionNum: 'S002' },
} as any)
const pushSpy = vi.spyOn(router, 'push').mockResolvedValue()
const wrapper = await mountTask()
await flushPromises()
// 会话-05:拦截弹窗出现,用户未选出口前不开始、也不跳转
expect(wrapper.vm.conflictSession?.taskNum).toBe('T002')
expect(startOrContinueStudySession).not.toHaveBeenCalled()
expect(router.currentRoute.value.path).toBe('/start-task/T002')
expect(pushSpy).not.toHaveBeenCalled()
// 执行「前往继续」出口
wrapper.vm.resolveConflict('continue')
await flushPromises()
expect(pushSpy).toHaveBeenCalledWith('/start-task/T002')
expect(startOrContinueStudySession).not.toHaveBeenCalled()
pushSpy.mockRestore()
wrapper.unmount()
})
@@ -0,0 +1,202 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus, { ElDialog, ElMessage } from 'element-plus'
import { createMemoryHistory, createRouter } from 'vue-router'
import StartTask from '@/components/StartTask.vue'
import {
abortSession,
endSession,
getActiveSession,
getExpectation,
getSessionDetail,
startOrContinueStudySession,
} from '@/api/studySessions'
import { getFragmentsBySession } from '@/api/reportFragments'
import appRouter from '@/router'
import type { ApiResponse } from '@/utils/request'
vi.mock('@/api/studySessions', () => ({
abortSession: vi.fn(),
continueSession: vi.fn(),
endSession: vi.fn(),
getActiveSession: vi.fn(),
getExpectation: vi.fn(),
getReportDraft: vi.fn(),
getSessionDetail: vi.fn(),
getTaskFragments: vi.fn(),
getTaskReports: vi.fn(),
pauseSession: vi.fn(),
startOrContinueStudySession: vi.fn(),
upsertExpectation: vi.fn(),
}))
vi.mock('@/api/reportFragments', () => ({
createFragments: vi.fn(),
getFragmentsBySession: vi.fn(),
updateFragments: vi.fn(),
}))
const ok = <T,>(data: T) => ({ code: 200, message: '请求成功', data }) as ApiResponse<T>
/** 搁置很久的旧任务会话:正是「堵住所有新任务」的那个会话(会话-05) */
const staleActiveSession = {
taskNum: 'T_OLD',
sessionNum: 'SESSION_OLD',
taskName: '三个月前的旧任务',
sessionState: 'PAUSED',
}
const sessionOngoing = {
sessionNum: 'SESSION_001',
sessionState: 'ONGOING',
taskName: '测试任务',
taskNum: 'T001',
taskId: 1,
startTime: '2026-08-27 10:00:00',
endTime: '',
lastStartTime: '2026-08-27 10:00:00',
actualTime: 0,
effectiveTime: 0,
effectivenessRatio: '--',
pointerPosition: 1_500_000,
systemMessage: '',
autoConverged: false,
}
/**
* 交互式集成测试:覆盖「有其他活跃会话」拦截弹窗的三个出口。
* 旧行为只有「前往继续 / 取消」,取消后无处可去,新任务被永久堵死。
*/
describe('StartTask 活跃会话拦截出口(集成,会话-05)', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
localStorage.setItem('isLoggedIn', 'true')
vi.mocked(getActiveSession).mockResolvedValue(ok(staleActiveSession))
vi.mocked(startOrContinueStudySession).mockResolvedValue(ok(sessionOngoing))
vi.mocked(getExpectation).mockResolvedValue(ok({ description: '本次学习预期' }))
vi.mocked(getFragmentsBySession).mockResolvedValue(ok([]))
vi.mocked(endSession).mockResolvedValue(ok())
vi.mocked(abortSession).mockResolvedValue(ok())
vi.mocked(getSessionDetail).mockResolvedValue(ok(sessionOngoing))
})
const mountPage = async () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/start-task/:taskNum', component: StartTask },
{ path: '/study', component: { template: '<div />' } },
],
})
await router.push('/start-task/T001')
await router.isReady()
const wrapper = mount(StartTask, {
global: {
plugins: [ElementPlus, router],
stubs: { ElTag: true },
},
})
await flushPromises()
return { wrapper, router }
}
const findButton = (wrapper: VueWrapper, text: string) =>
wrapper.findAll('button').find((b) => b.text().trim() === text)
const conflictDialog = (wrapper: VueWrapper) =>
wrapper.findAllComponents(ElDialog).find((d) => d.props('modelValue') === true)
it('存在其他活跃会话时弹出拦截弹窗,并给出三个出口', async () => {
const { wrapper } = await mountPage()
const dialog = conflictDialog(wrapper)
expect(dialog).toBeTruthy()
expect(wrapper.text()).toContain('三个月前的旧任务')
expect(findButton(wrapper, '前往继续')).toBeTruthy()
expect(findButton(wrapper, '结束它并开始新任务')).toBeTruthy()
expect(findButton(wrapper, '放弃该会话')).toBeTruthy()
// 尚未选择出口:不应开始当前任务
expect(startOrContinueStudySession).not.toHaveBeenCalled()
wrapper.unmount()
})
it('「结束它并开始新任务」先结束旧会话,再开始当前任务', async () => {
const { wrapper } = await mountPage()
await findButton(wrapper, '结束它并开始新任务').trigger('click')
await flushPromises()
expect(endSession).toHaveBeenCalledWith(
'SESSION_OLD',
expect.stringContaining('开始新任务时结束了这个会话'),
)
// 解除阻塞后继续开始当前任务
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
expect(wrapper.find('.status-text').text()).toContain('进行中')
wrapper.unmount()
})
it('「放弃该会话」零数据关闭旧会话,随后开始当前任务', async () => {
const { wrapper } = await mountPage()
await findButton(wrapper, '放弃该会话').trigger('click')
await flushPromises()
expect(abortSession).toHaveBeenCalledWith('SESSION_OLD', '我误操作导致开启了本次学习')
expect(endSession).not.toHaveBeenCalled()
expect(startOrContinueStudySession).toHaveBeenCalledWith('T001')
expect(ElMessage.success).toHaveBeenCalledWith('已放弃该会话,未产生任何数据')
wrapper.unmount()
})
it('放弃失败(旧会话已产生残片)时不开始当前任务,并转达后端原因', async () => {
vi.mocked(abortSession).mockResolvedValue({
code: 400,
message: '这次学习已经产生了学习残片,不能按误操作结束了哦',
})
const { wrapper } = await mountPage()
await findButton(wrapper, '放弃该会话').trigger('click')
await flushPromises()
expect(startOrContinueStudySession).not.toHaveBeenCalled()
expect(ElMessage.error).toHaveBeenCalledWith('这次学习已经产生了学习残片,不能按误操作结束了哦')
wrapper.unmount()
})
it('「前往继续」跳转到旧会话所属任务', async () => {
const { wrapper } = await mountPage()
// 组件使用的是应用级 router 单例,测试路由器看不到它的 push
const pushSpy = vi.spyOn(appRouter, 'push').mockResolvedValue()
await findButton(wrapper, '前往继续').trigger('click')
await flushPromises()
expect(pushSpy).toHaveBeenCalledWith('/start-task/T_OLD')
expect(startOrContinueStudySession).not.toHaveBeenCalled()
pushSpy.mockRestore()
wrapper.unmount()
})
it('取消时保持阻塞并给出提示,不静默失败', async () => {
const { wrapper } = await mountPage()
await findButton(wrapper, '取消').trigger('click')
await flushPromises()
expect(startOrContinueStudySession).not.toHaveBeenCalled()
expect(ElMessage.warning).toHaveBeenCalledWith('请先完成进行中的任务后再开始')
wrapper.unmount()
})
it('服务端自动收敛的旧会话给出「疑似忘记结束」说明', async () => {
vi.mocked(getActiveSession).mockResolvedValue(ok({ ...staleActiveSession, autoConverged: true }))
const { wrapper } = await mountPage()
expect(wrapper.text()).toContain('忘记结束')
wrapper.unmount()
})
})
+5
View File
@@ -17,6 +17,8 @@ export interface SessionDetail {
effectivenessRatio?: number | string;
pointerPosition?: number;
systemMessage?: string;
/** 是否由服务端自动收敛(疑似忘记结束,会话-04) */
autoConverged?: boolean;
}
/** 当前活跃会话摘要(跨页面恢复用) */
@@ -24,6 +26,9 @@ export interface ActiveSessionInfo {
taskNum: string;
sessionNum: string;
taskName?: string;
sessionState?: "ONGOING" | "PAUSED" | "ENDED";
/** 是否由服务端自动收敛(疑似忘记结束,会话-04) */
autoConverged?: boolean;
}
/** 后端 MyBatis-Plus 分页包装 */
+152 -13
View File
@@ -12,6 +12,7 @@ import {
getSessionDetail,
pauseSession,
startOrContinueStudySession,
type ActiveSessionInfo,
} from "@/api/studySessions";
import { useStudyFragment } from "@/components/composables/fragment";
import { getFragmentsBySession, updateFragments } from "@/api/reportFragments";
@@ -44,6 +45,82 @@ const canAbortSession = computed(
() => taskInfo.value.sessionState !== "ENDED" && fragmentsList.value.length === 0,
);
// 会话-05:有其他活跃会话时的出口选择(前往继续 / 结束并开始新任务 / 放弃该会话)
type ConflictAction = "continue" | "end" | "abort" | "cancel";
const conflictDialogVisible = ref(false);
const conflictSession = ref<ActiveSessionInfo | null>(null);
const conflictResolving = ref<ConflictAction | null>(null);
let conflictResolve: ((action: ConflictAction) => void) | null = null;
/** 结束旧会话时写入的报告正文:让用户看得出这条报告是怎么来的 */
const STALE_SESSION_SUMMARY = "(开始新任务时结束了这个会话,未填写学习总结)";
/** 从异常里取用户可见文案:请求层抛出的多为带 message 的业务对象 */
const errorMessageOf = (error: unknown, fallback: string): string => {
if (error && typeof error === "object" && "message" in error) {
const message = (error as { message?: unknown }).message;
if (typeof message === "string" && message.trim()) return message;
}
return fallback;
};
/** 弹出冲突弹窗并等待用户选择出口 */
const askConflictAction = (active: ActiveSessionInfo): Promise<ConflictAction> => {
conflictSession.value = active;
conflictDialogVisible.value = true;
return new Promise<ConflictAction>((resolve) => {
conflictResolve = resolve;
});
};
const resolveConflict = (action: ConflictAction) => {
conflictDialogVisible.value = false;
conflictResolving.value = null;
const resolve = conflictResolve;
conflictResolve = null;
resolve?.(action);
};
/** 结束旧会话;成功或幂等(已结束)都返回 true */
const resolveStaleSessionByEnding = async (active: ActiveSessionInfo): Promise<boolean> => {
conflictResolving.value = "end";
try {
const res = await endSession(active.sessionNum, STALE_SESSION_SUMMARY);
if (res.code !== 200) {
ElMessage.error(res.message || "结束旧会话失败");
return false;
}
if (res.message && res.message !== "请求成功") {
ElMessage.warning(res.message);
}
return true;
} catch (e) {
ElMessage.error(errorMessageOf(e, "结束旧会话失败,请重试"));
return false;
} finally {
conflictResolving.value = null;
}
};
/** 放弃旧会话(零数据关闭);已产生学习残片时后端会拒绝,这里原样转达 */
const resolveStaleSessionByDiscarding = async (active: ActiveSessionInfo): Promise<boolean> => {
conflictResolving.value = "abort";
try {
const res = await abortSession(active.sessionNum, MISOPERATION_PHRASE);
if (res.code !== 200) {
ElMessage.error(res.message || "放弃该会话失败");
return false;
}
ElMessage.success("已放弃该会话,未产生任何数据");
return true;
} catch (e) {
ElMessage.error(errorMessageOf(e, "放弃该会话失败,请重试"));
return false;
} finally {
conflictResolving.value = null;
}
};
// 结束会话总结弹窗(有残片时先取 AI 草稿,等待期间展示已等待秒数)
const {
summaryDialogVisible,
@@ -114,6 +191,7 @@ const taskInfo = ref({
effectivenessRatio: "-",
pointerPosition: 0,
systemMessage: "",
autoConverged: false,
});
// 学习材料展示/编辑
@@ -431,26 +509,31 @@ const loadTaskSession = async () => {
const activeRes = await getActiveSession();
const active = activeRes?.data;
if (active?.taskNum && active.taskNum !== taskNum) {
let goToActive = false;
try {
await ElMessageBox.confirm(
`你还有一个未完成的学习任务「${active.taskName}」(${active.sessionNum}),是否前往继续?`,
"有其他任务正在进行",
{ confirmButtonText: "前往继续", cancelButtonText: "取消", type: "warning" },
);
goToActive = true;
} catch {
// 用户取消,不开始当前任务
}
if (goToActive) {
// 会话-05:拦截弹窗必须给出路,否则一个陌生的陈旧会话会永久堵住所有新任务
const action = await askConflictAction(active);
if (action === "continue") {
router.push(`/start-task/${encodeURIComponent(active.taskNum)}`);
return;
}
if (action === "end") {
if (!(await resolveStaleSessionByEnding(active))) return;
} else if (action === "abort") {
if (!(await resolveStaleSessionByDiscarding(active))) return;
} else {
ElMessage.warning("请先完成进行中的任务后再开始");
return;
}
return;
// 解除阻塞后继续开始当前任务
}
const res = await startOrContinueStudySession(taskNum);
Object.assign(taskInfo.value, res.data);
// 会话-04:服务端自动收敛过的会话,明确告知用户本次只计算了多少时间
if (taskInfo.value.autoConverged) {
ElMessage.warning(
taskInfo.value.systemMessage
|| "上一次学习疑似忘记结束,已自动截止,本次只计入一个番茄钟的有效学习时间",
);
}
await loadExpectation();
// 检查是否有未结束的休息
@@ -852,6 +935,48 @@ defineExpose({
</template>
</el-dialog>
<!-- 会话-05:有其他活跃会话时的出口选择(不再只有「前往继续」和无处可去的取消) -->
<el-dialog
v-model="conflictDialogVisible"
title="还有未结束的学习会话"
width="560px"
:close-on-click-modal="false"
:close-on-press-escape="false"
>
<template v-if="conflictSession">
<p class="dialog-hint">
你已经有一个未结束的学习会话:
<strong>「{{ conflictSession.taskName || conflictSession.taskNum }}」</strong>
({{ conflictSession.sessionNum }})。
</p>
<p v-if="conflictSession.autoConverged" class="dialog-hint dialog-hint-warning">
这个会话看起来是忘记结束了,服务端已按一个番茄钟自动截止。
</p>
<p class="dialog-hint">
可以直接开始当前任务:开始时会先把上面这个会话结束(会生成一份未填总结的学习报告);
如果它本来就是误操作开启的,可以选择放弃,不会留下任何记录。
</p>
</template>
<template #footer>
<div class="conflict-actions">
<el-button @click="resolveConflict('cancel')">取消</el-button>
<el-button
type="danger"
plain
:loading="conflictResolving === 'abort'"
@click="resolveConflict('abort')"
>放弃该会话</el-button>
<el-button
type="primary"
plain
:loading="conflictResolving === 'end'"
@click="resolveConflict('end')"
>结束它并开始新任务</el-button>
<el-button type="success" @click="resolveConflict('continue')">前往继续</el-button>
</div>
</template>
</el-dialog>
<el-dialog
v-model="abortDialogVisible"
title="误操作结束"
@@ -967,6 +1092,20 @@ defineExpose({
color: var(--text-secondary);
}
.dialog-hint-warning {
padding: 6px 10px;
border-left: 3px solid var(--accent-warning, #e6a23c);
background: var(--accent-warning-soft, #fdf6ec);
border-radius: 4px;
}
.conflict-actions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px;
}
.ai-waiting {
font-size: 13px;
color: var(--accent-warning);