238 lines
7.6 KiB
TypeScript
238 lines
7.6 KiB
TypeScript
// src/components/composables/useGuidance.ts
|
|
import { ref } from "vue";
|
|
import {
|
|
abandonGuidance,
|
|
createGuidanceFragment,
|
|
getGuidanceSession,
|
|
startGuidance,
|
|
submitGuidanceTurn,
|
|
type GuidanceSession,
|
|
type GuidanceTurn,
|
|
} from "@/api/guidance";
|
|
import { 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;
|
|
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 parseTurns = (payload: string): GuidanceTurn[] => {
|
|
try {
|
|
const parsed = JSON.parse(payload);
|
|
if (!Array.isArray(parsed)) return [];
|
|
return parsed
|
|
.filter((item): item is GuidanceTurn =>
|
|
!!item && typeof item === "object" &&
|
|
(item.role === "user" || item.role === "assistant") &&
|
|
typeof item.content === "string",
|
|
)
|
|
.map((item) => ({ role: item.role, content: item.content }));
|
|
} catch {
|
|
return [];
|
|
}
|
|
};
|
|
|
|
const storageKey = (taskNum: string, concept: string) => `lpt-guidance:${taskNum}:${concept}`;
|
|
|
|
/**
|
|
* 一次学习引导会话的状态机:开启/恢复对话、多轮问答、确认产出碎片、放弃。
|
|
* 对话上下文一律以后端会话为准;AI 每轮的回复通过轮询 AI 任务获取。
|
|
*/
|
|
export function useGuidanceSession() {
|
|
const session = ref<GuidanceSession | null>(null);
|
|
const turns = ref<GuidanceTurn[]>([]);
|
|
const starting = ref(false);
|
|
const sending = ref(false);
|
|
const error = ref("");
|
|
const aiTask = useAiTask();
|
|
const { seconds: waitingSeconds, running: waiting } = 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);
|
|
const reply = result?.reply;
|
|
if (typeof reply !== "string" || !reply.trim()) {
|
|
throw new Error("AI 这次没有给出回应,请稍后再试");
|
|
}
|
|
return reply;
|
|
};
|
|
|
|
const clearStorage = (taskNum: string, concept: string) => {
|
|
localStorage.removeItem(storageKey(taskNum, concept));
|
|
};
|
|
|
|
const reset = () => {
|
|
session.value = null;
|
|
turns.value = [];
|
|
starting.value = false;
|
|
sending.value = false;
|
|
error.value = "";
|
|
};
|
|
|
|
/** 打开引导:优先恢复未结束的会话,否则新开一次 */
|
|
const open = async (taskNum: string, concept: string) => {
|
|
reset();
|
|
if (!taskNum || !concept) {
|
|
error.value = "这条内容还没有归属任务,暂时不能做学习引导";
|
|
return;
|
|
}
|
|
|
|
// 离开页面再回来:用本地记下的编号恢复同一段对话
|
|
const stored = localStorage.getItem(storageKey(taskNum, concept));
|
|
if (stored) {
|
|
try {
|
|
const res = await getGuidanceSession(stored);
|
|
const restored = res?.data;
|
|
if (restored && !restored.finished) {
|
|
session.value = restored;
|
|
turns.value = parseTurns(restored.turnsPayload);
|
|
startDuration();
|
|
return;
|
|
}
|
|
clearStorage(taskNum, concept);
|
|
} catch {
|
|
clearStorage(taskNum, concept);
|
|
}
|
|
}
|
|
|
|
if (unavailable.value) {
|
|
error.value = "学习引导暂时用不了,可以先继续复习,等 AI 恢复后再来。";
|
|
return;
|
|
}
|
|
|
|
starting.value = true;
|
|
try {
|
|
const res = await startGuidance(taskNum, concept);
|
|
const data = res?.data;
|
|
if (!data?.guidanceNum || !data.aiTaskNum) {
|
|
throw new Error("学习引导没开起来,请稍后再试");
|
|
}
|
|
session.value = {
|
|
guidanceNum: data.guidanceNum,
|
|
taskNum: data.taskNum,
|
|
concept: data.concept,
|
|
turnsPayload: "[]",
|
|
reviewDurationSeconds: 0,
|
|
finished: false,
|
|
};
|
|
localStorage.setItem(storageKey(taskNum, concept), data.guidanceNum);
|
|
startDuration();
|
|
const reply = await pollReply(data.aiTaskNum);
|
|
turns.value = [{ role: "assistant", content: reply }];
|
|
} catch (e) {
|
|
markGuidanceUnavailable();
|
|
error.value = errorMessageOf(e, "学习引导暂时用不了,可以先继续复习,等 AI 恢复后再来。");
|
|
} finally {
|
|
starting.value = false;
|
|
}
|
|
};
|
|
|
|
/** 发送一轮:先回显用户输入,再轮询 AI 回复 */
|
|
const send = async (message: string): Promise<boolean> => {
|
|
const text = message.trim();
|
|
if (!session.value || !text || sending.value || waiting.value || unavailable.value) return false;
|
|
sending.value = true;
|
|
error.value = "";
|
|
markInteraction();
|
|
turns.value = [...turns.value, { role: "user", content: text }];
|
|
try {
|
|
const res = await submitGuidanceTurn(session.value.guidanceNum, text);
|
|
const aiTaskNum = res?.data?.taskNum;
|
|
if (!aiTaskNum) throw new Error("这一轮没有提交成功,请稍后再试");
|
|
const reply = await pollReply(aiTaskNum);
|
|
turns.value = [...turns.value, { role: "assistant", content: reply }];
|
|
return true;
|
|
} catch (e) {
|
|
markGuidanceUnavailable();
|
|
error.value = errorMessageOf(e, "AI 暂时没有回应,学习引导已停用,可以先继续复习。");
|
|
return false;
|
|
} finally {
|
|
sending.value = false;
|
|
}
|
|
};
|
|
|
|
/** 确认产出碎片;耗时快照与回忆对比同一口径 */
|
|
const confirmFragment = async (content: string): Promise<boolean> => {
|
|
const text = content.trim();
|
|
if (!session.value || session.value.finished || !text) return false;
|
|
const timing = snapshot();
|
|
markInteraction();
|
|
try {
|
|
const res = await createGuidanceFragment(session.value.guidanceNum, {
|
|
content: text,
|
|
reviewStartedAt: timing.startedAt,
|
|
reviewLastInteractionAt: timing.lastInteractionAt,
|
|
reviewDurationSeconds: timing.durationSeconds,
|
|
});
|
|
if (res?.code === 200) {
|
|
session.value = { ...session.value, finished: true };
|
|
clearStorage(session.value.taskNum, session.value.concept);
|
|
stopDuration();
|
|
return true;
|
|
}
|
|
error.value = "这条收获没能记下来,请稍后再试";
|
|
return false;
|
|
} catch (e) {
|
|
error.value = errorMessageOf(e, "这条收获没能记下来,请稍后再试");
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/** 放弃这次引导:不产出任何数据 */
|
|
const abandon = async (): Promise<void> => {
|
|
const current = session.value;
|
|
if (!current) return;
|
|
if (!current.finished) {
|
|
try {
|
|
await abandonGuidance(current.guidanceNum);
|
|
} catch {
|
|
// 放弃失败也不该拦住用户,本地照常收尾
|
|
}
|
|
}
|
|
clearStorage(current.taskNum, current.concept);
|
|
stopDuration();
|
|
session.value = { ...current, finished: true };
|
|
};
|
|
|
|
return {
|
|
session,
|
|
turns,
|
|
starting,
|
|
sending,
|
|
waiting,
|
|
waitingSeconds,
|
|
error,
|
|
unavailable,
|
|
open,
|
|
send,
|
|
confirmFragment,
|
|
abandon,
|
|
markInteraction,
|
|
reset,
|
|
};
|
|
}
|