- 后端新增 PUT /api/ai-writing/sessions/{id}/draft(属主校验,draft_title 可选)
- 前端历史模式放开只读,工具栏新增「保存」按钮持久化修改
- 实时写作完成态保持原样(仅导出,不落库)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
181 lines
6.3 KiB
TypeScript
181 lines
6.3 KiB
TypeScript
import { getBackendBaseURL } from '@/core/config';
|
|
import { apiFetch } from '@/core/api';
|
|
|
|
import type { ProgressEvent, CompletedIntervention } from '../types/ai-writing';
|
|
|
|
export interface AIWritingSessionSummary {
|
|
id: string;
|
|
user_id: string | null;
|
|
title: string;
|
|
user_intent: string | null;
|
|
status: string;
|
|
draft_title: string | null;
|
|
draft_markdown: string | null;
|
|
completed_interventions: CompletedInterventionRecord[] | null;
|
|
review_result: Record<string, unknown> | null;
|
|
transcript: AIWritingTranscript | null;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export interface CompletedInterventionRecord {
|
|
pausePoint: string;
|
|
action: string;
|
|
timestamp: string;
|
|
}
|
|
|
|
/** 完整对话时间线快照:与实时对话用同一份数据结构,历史回显时直接喂给 AIWritingTimeline。 */
|
|
export interface AIWritingTranscript {
|
|
progressEvents: ProgressEvent[];
|
|
completedInterventions: CompletedIntervention[];
|
|
}
|
|
|
|
const BASE = () => `${getBackendBaseURL()}/api/ai-writing/sessions`;
|
|
|
|
// ── admin 调试用 —— 阶段 7 删冗余时一并移除 ───────────────────────────────────
|
|
export interface AIWritingCleanupResult {
|
|
deleted_db: number;
|
|
deleted_checkpoints: number;
|
|
skipped_active: number;
|
|
elapsed_seconds: number;
|
|
params: { retention_days: number; only_finished: boolean; batch_size: number };
|
|
}
|
|
|
|
/** 仅 admin 可用:触发一次性会话清理(保留 ai-writing-优化.md 迁移期临时调试入口)。 */
|
|
export async function adminCleanupAIWritingSessions(body: {
|
|
retention_days?: number;
|
|
only_finished?: boolean;
|
|
batch_size?: number;
|
|
} = {}): Promise<AIWritingCleanupResult> {
|
|
const resp = await apiFetch(`${getBackendBaseURL()}/api/ai-writing/admin/cleanup`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
});
|
|
if (!resp.ok) {
|
|
const text = await resp.text().catch(() => '');
|
|
throw new Error(`清理失败 ${resp.status}: ${text || resp.statusText}`);
|
|
}
|
|
return resp.json();
|
|
}
|
|
|
|
|
|
export async function listAIWritingSessions(): Promise<AIWritingSessionSummary[]> {
|
|
const resp = await apiFetch(BASE());
|
|
if (!resp.ok) throw new Error(`获取历史记录失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
export async function getAIWritingSession(id: string): Promise<AIWritingSessionSummary> {
|
|
const resp = await apiFetch(`${BASE()}/${id}`);
|
|
if (!resp.ok) throw new Error(`获取会话失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
export async function renameAIWritingSession(id: string, title: string): Promise<AIWritingSessionSummary> {
|
|
const resp = await apiFetch(`${BASE()}/${id}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ title }),
|
|
});
|
|
if (!resp.ok) throw new Error(`重命名失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
/**
|
|
* 更新历史会话的成稿正文(历史回看时用户在右侧编辑器里直接修改并保存)。
|
|
* draftTitle 省略时后端不动原标题。
|
|
*/
|
|
export async function updateAIWritingDraft(
|
|
id: string,
|
|
draftMarkdown: string,
|
|
draftTitle?: string,
|
|
): Promise<AIWritingSessionSummary> {
|
|
const resp = await apiFetch(`${BASE()}/${id}/draft`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
draft_markdown: draftMarkdown,
|
|
...(draftTitle === undefined ? {} : { draft_title: draftTitle }),
|
|
}),
|
|
});
|
|
if (!resp.ok) throw new Error(`保存修改失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
export async function deleteAIWritingSession(id: string): Promise<void> {
|
|
const resp = await apiFetch(`${BASE()}/${id}`, { method: 'DELETE' });
|
|
if (!resp.ok) throw new Error(`删除失败: ${resp.status}`);
|
|
}
|
|
|
|
/**
|
|
* 把一篇写作转入「后台挂起」:后端自动驱动剩余流程到定稿(离页/刷新/切号不打断)。
|
|
*
|
|
* 幂等——同一会话已在后台跑则后端直接返回 ``started:false``。
|
|
*/
|
|
export async function suspendAIWritingToBackground(
|
|
id: string,
|
|
): Promise<{ started: boolean; status: string }> {
|
|
const resp = await apiFetch(`${BASE()}/${id}/background`, { method: 'POST' });
|
|
if (!resp.ok) throw new Error(`后台挂起失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
/** 一篇写作的实际进度(供「查看进度」流程图弹窗轮询)。 */
|
|
export interface AIWritingProgress {
|
|
sessionStatus: string;
|
|
/** 规范化阶段 key(与流程图阶段一一对应);null = 还没建 checkpoint。 */
|
|
stage: string | null;
|
|
note: string | null;
|
|
revisionCount: number;
|
|
maxRevisions: number;
|
|
reviewVerdict: string | null;
|
|
isRunning: boolean;
|
|
}
|
|
|
|
export async function getAIWritingProgress(id: string): Promise<AIWritingProgress> {
|
|
const resp = await apiFetch(`${BASE()}/${id}/progress`);
|
|
if (!resp.ok) throw new Error(`获取进度失败: ${resp.status}`);
|
|
return resp.json();
|
|
}
|
|
|
|
/**
|
|
* beforeunload 兜底:离开/刷新页面时用 keepalive 发起后台挂起,
|
|
* 保证浏览器卸载页面后请求仍能发完。fire-and-forget,不读响应;
|
|
* 重复触发由后端「同会话已在后台跑」幂等兜住。
|
|
*/
|
|
export function suspendAIWritingToBackgroundKeepalive(id: string): void {
|
|
try {
|
|
void apiFetch(`${BASE()}/${id}/background`, { method: 'POST', keepalive: true }).catch(() => {});
|
|
} catch {
|
|
/* 卸载阶段尽力而为,忽略一切异常 */
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 保存会话的完整对话时间线,供历史回显出与实时对话一致的富时间线。
|
|
*
|
|
* 该功能属于「锦上添花」:保存失败不应影响写作主流程,因此本函数永不抛错,
|
|
* 内部捕获所有异常(网络错误 / 接口 500 等),仅打印告警并返回是否成功。
|
|
*/
|
|
export async function saveAIWritingTranscript(
|
|
id: string,
|
|
transcript: AIWritingTranscript,
|
|
): Promise<boolean> {
|
|
try {
|
|
const resp = await apiFetch(`${BASE()}/${id}/transcript`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ transcript }),
|
|
});
|
|
if (!resp.ok) {
|
|
console.warn(`[ai-writing] 保存对话时间线失败: HTTP ${resp.status}(已忽略,不影响写作流程)`);
|
|
return false;
|
|
}
|
|
return true;
|
|
} catch (err) {
|
|
console.warn('[ai-writing] 保存对话时间线异常(已忽略,不影响写作流程):', err);
|
|
return false;
|
|
}
|
|
}
|