点击「转后台」后立刻 reset 回初始页,挂起请求 fire-and-forget; 历史下拉靠 markBackground/clearBackground 乐观标记马上显示「挂起中」, 不等后端确认,与「多智能体会商」交互一致。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import { useCallback, useMemo, useState } from 'react';
|
|
|
|
import {
|
|
listAIWritingSessions,
|
|
renameAIWritingSession,
|
|
deleteAIWritingSession,
|
|
} from '../api/ai-writing-sessions';
|
|
import type { AIWritingSessionSummary } from '../api/ai-writing-sessions';
|
|
|
|
export function useAIWritingSessions() {
|
|
const [sessions, setSessions] = useState<AIWritingSessionSummary[]>([]);
|
|
const [loading, setLoading] = useState(false);
|
|
// 「后台挂起」乐观标记:点击挂起后立刻让历史下拉显示「挂起中」,不必等后端确认。
|
|
// 后端状态(status='background')刷新到位后由调用方 clearBackground 清除。
|
|
const [pendingBackground, setPendingBackground] = useState<Set<string>>(() => new Set());
|
|
|
|
const markBackground = useCallback((id: string) => {
|
|
setPendingBackground((prev) => {
|
|
if (prev.has(id)) return prev;
|
|
const next = new Set(prev);
|
|
next.add(id);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const clearBackground = useCallback((id: string) => {
|
|
setPendingBackground((prev) => {
|
|
if (!prev.has(id)) return prev;
|
|
const next = new Set(prev);
|
|
next.delete(id);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const refresh = useCallback(async () => {
|
|
setLoading(true);
|
|
try {
|
|
const data = await listAIWritingSessions();
|
|
setSessions(data);
|
|
} catch {
|
|
// silently ignore — history is non-critical
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
const rename = useCallback(async (id: string, title: string) => {
|
|
try {
|
|
const updated = await renameAIWritingSession(id, title);
|
|
setSessions((prev) => prev.map((s) => (s.id === id ? updated : s)));
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}, []);
|
|
|
|
const remove = useCallback(async (id: string) => {
|
|
try {
|
|
await deleteAIWritingSession(id);
|
|
setSessions((prev) => prev.filter((s) => s.id !== id));
|
|
} catch {
|
|
// ignore
|
|
}
|
|
}, []);
|
|
|
|
// 把乐观「挂起中」标记叠加到真实列表上:已在列表里的会话立刻显示 background。
|
|
const displaySessions = useMemo(
|
|
() =>
|
|
pendingBackground.size === 0
|
|
? sessions
|
|
: sessions.map((s) =>
|
|
pendingBackground.has(s.id) && s.status !== 'done'
|
|
? { ...s, status: 'background' }
|
|
: s,
|
|
),
|
|
[sessions, pendingBackground],
|
|
);
|
|
|
|
return { sessions: displaySessions, loading, refresh, rename, remove, markBackground, clearBackground };
|
|
}
|