2656 lines
94 KiB
TypeScript
2656 lines
94 KiB
TypeScript
import type { AIMessage, Message, ThreadState } from "@langchain/langgraph-sdk";
|
||
import type { ThreadsClient } from "@langchain/langgraph-sdk/client";
|
||
import { useStream } from "@langchain/langgraph-sdk/react";
|
||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import type { QueryClient } from "@tanstack/react-query";
|
||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||
import { useNavigate } from "react-router-dom";
|
||
import { toast } from "sonner";
|
||
|
||
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
||
|
||
import { createStreamAPIClient, getAPIClient } from "../api";
|
||
import { apiFetch } from "../api";
|
||
import { getStoredAuth } from "../auth";
|
||
import { rememberAskTime } from "../chat-timestamps";
|
||
import { getBackendBaseURL, getLangGraphBaseURL } from "../config";
|
||
import { useI18n } from "../i18n/hooks";
|
||
import { OptType, writeYLog } from "../log/y-log";
|
||
import { reasoningEffortForRun } from "../models/reasoning-effort";
|
||
import type { FileInMessage } from "../messages/utils";
|
||
import type { LocalSettings } from "../settings";
|
||
import {
|
||
isThreadRagModeLocked,
|
||
lockThreadRagMode,
|
||
useLocalSettings,
|
||
} from "../settings";
|
||
import { useCitationDisplaySettings } from "../system-settings/hooks";
|
||
import { useUpdateSubtask } from "../tasks/context";
|
||
import type { UploadedFileInfo } from "../uploads";
|
||
import { promptInputFilePartToFile, uploadFiles } from "../uploads";
|
||
|
||
import type { AgentThread, AgentThreadState } from "./types";
|
||
import { BackgroundHistory } from "./background-history";
|
||
import { STREAM_RENDER_BATCHING } from "./stream-batching";
|
||
import { createReactStreamRecoveryBudget, reportReactUiError } from "./react-ui-error";
|
||
import {
|
||
finalizeResearchReportStream,
|
||
ingestResearchReportEvent,
|
||
} from "./use-research-report-stream";
|
||
import {
|
||
collectHumanMessageIds,
|
||
createNewConversationDisplayBoundary,
|
||
hasServerEchoedOptimisticHuman,
|
||
isolateNewConversationMessages,
|
||
isStaleStreamFinish,
|
||
mergeStreamDisplayValues,
|
||
shouldDiscardTerminalOverlay,
|
||
type NewConversationDisplayBoundary,
|
||
} from "./stream-display";
|
||
import {
|
||
STREAM_RECOVERY_LIVE_IDLE_MS,
|
||
runStreamRecoverySingleFlight,
|
||
stopRecoveredRunReader,
|
||
shouldReconcileRunStream,
|
||
shouldIgnoreReaderRecycleFinish,
|
||
type StreamRecoveryResult,
|
||
type StreamRecoverySingleFlight,
|
||
} from "./stream-recovery";
|
||
import {
|
||
getStreamErrorMessage,
|
||
isAbortLikeError,
|
||
isReactMaximumUpdateDepthError,
|
||
isTransientStreamTransportError,
|
||
} from "./thread-access-error";
|
||
import {
|
||
beginKnowledgeRetrievalProgress,
|
||
bindKnowledgeRetrievalProgressRun,
|
||
clearKnowledgeRetrievalProgress,
|
||
ingestKnowledgeRetrievalProgress,
|
||
} from "./knowledge-retrieval-progress";
|
||
import { isHiddenFromRecentChats, shouldHideSystemThreadsFromList } from "./utils";
|
||
import {
|
||
resolveKnowledgeRagModeEnabled,
|
||
withExplicitKnowledgeRetrievalMode,
|
||
withKnowledgeRetrievalModeMetadata,
|
||
type KnowledgeRetrievalMode,
|
||
} from "./knowledge-retrieval-mode";
|
||
|
||
export type ToolEndEvent = {
|
||
name: string;
|
||
data: unknown;
|
||
toolCallId?: string;
|
||
};
|
||
|
||
export type ToolStartEvent = ToolEndEvent;
|
||
|
||
export type ThreadStreamOptions = {
|
||
threadId?: string | null | undefined;
|
||
context: LocalSettings["context"] & {
|
||
knowledge_retrieval_mode?: KnowledgeRetrievalMode;
|
||
};
|
||
isMock?: boolean;
|
||
assistantId?: string;
|
||
/**
|
||
* Per-page run behaviour. Most chats keep the SDK defaults; long-running
|
||
* workspace flows can opt into a resumable stream without changing global
|
||
* chat semantics.
|
||
*/
|
||
runOptions?: {
|
||
onDisconnect?: "cancel" | "continue";
|
||
multitaskStrategy?: "reject" | "rollback" | "interrupt" | "enqueue";
|
||
};
|
||
/** 额外写到新建 thread 的 metadata(与 agent_id 合并)。
|
||
* 任务深链会写 taskId + taskRecordId + taskGoPath,供专用历史索引登记。 */
|
||
threadMetadata?: Record<string, unknown>;
|
||
/**
|
||
* 任务深链接的单智能体运行允许后台恢复继续完成。此时把流式运行的
|
||
* 非阻断性提示留在控制台,避免无关 Toast 打断任务工作区的操作。
|
||
*/
|
||
suppressUserFacingStreamErrors?: boolean;
|
||
onStart?: (threadId: string) => void;
|
||
onFinish?: (state: AgentThreadState) => void;
|
||
onToolStart?: (event: ToolStartEvent) => void;
|
||
onToolEnd?: (event: ToolEndEvent) => void;
|
||
};
|
||
|
||
type SendMessageOptions = {
|
||
additionalKwargs?: Record<string, unknown>;
|
||
/**
|
||
* Extra human-context messages submitted before the visible user message.
|
||
* They are persisted with `hide_from_ui` so the model receives rich business
|
||
* context without dumping long prompts into the conversation surface.
|
||
*/
|
||
hiddenContext?:
|
||
| string
|
||
| {
|
||
text: string;
|
||
name?: string;
|
||
additionalKwargs?: Record<string, unknown>;
|
||
}
|
||
| Array<{
|
||
text: string;
|
||
name?: string;
|
||
additionalKwargs?: Record<string, unknown>;
|
||
}>;
|
||
};
|
||
|
||
type ThreadTitleRefreshState = Pick<AgentThreadState, "title"> & {
|
||
title_provisional: boolean | null;
|
||
};
|
||
|
||
function normalizeHiddenContextMessages(options?: SendMessageOptions) {
|
||
const value = options?.hiddenContext;
|
||
if (!value) return [];
|
||
const items =
|
||
typeof value === "string"
|
||
? [{ text: value }]
|
||
: Array.isArray(value)
|
||
? value
|
||
: [value];
|
||
return items
|
||
.map((item) => ({
|
||
...item,
|
||
text: item.text.trim(),
|
||
}))
|
||
.filter((item) => item.text.length > 0);
|
||
}
|
||
|
||
function normalizeStoredRunId(runId: string | null): string | null {
|
||
if (!runId) {
|
||
return null;
|
||
}
|
||
|
||
const trimmed = runId.trim();
|
||
if (!trimmed) {
|
||
return null;
|
||
}
|
||
|
||
const queryIndex = trimmed.indexOf("?");
|
||
if (queryIndex >= 0) {
|
||
const params = new URLSearchParams(trimmed.slice(queryIndex + 1));
|
||
const queryRunId = params.get("run_id")?.trim();
|
||
if (queryRunId) {
|
||
return queryRunId;
|
||
}
|
||
}
|
||
|
||
const pathWithoutQueryOrHash = trimmed.split(/[?#]/, 1)[0]?.trim() ?? "";
|
||
if (!pathWithoutQueryOrHash) {
|
||
return null;
|
||
}
|
||
|
||
const runsMarker = "/runs/";
|
||
const runsIndex = pathWithoutQueryOrHash.lastIndexOf(runsMarker);
|
||
if (runsIndex >= 0) {
|
||
const runIdAfterMarker = pathWithoutQueryOrHash
|
||
.slice(runsIndex + runsMarker.length)
|
||
.split("/", 1)[0]
|
||
?.trim();
|
||
if (runIdAfterMarker) {
|
||
return runIdAfterMarker;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
const segments = pathWithoutQueryOrHash
|
||
.split("/")
|
||
.map((segment) => segment.trim())
|
||
.filter(Boolean);
|
||
return segments.at(-1) ?? null;
|
||
}
|
||
|
||
function getRunMetadataStorage(): {
|
||
getItem(key: `lg:stream:${string}`): string | null;
|
||
setItem(key: `lg:stream:${string}`, value: string): void;
|
||
removeItem(key: `lg:stream:${string}`): void;
|
||
} {
|
||
return {
|
||
getItem(key) {
|
||
const normalized = normalizeStoredRunId(
|
||
window.sessionStorage.getItem(key),
|
||
);
|
||
if (normalized) {
|
||
window.sessionStorage.setItem(key, normalized);
|
||
return normalized;
|
||
}
|
||
window.sessionStorage.removeItem(key);
|
||
return null;
|
||
},
|
||
setItem(key, value) {
|
||
const normalized = normalizeStoredRunId(value);
|
||
if (normalized) {
|
||
window.sessionStorage.setItem(key, normalized);
|
||
return;
|
||
}
|
||
window.sessionStorage.removeItem(key);
|
||
},
|
||
removeItem(key) {
|
||
window.sessionStorage.removeItem(key);
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* SDK ``useStream`` stores the in-flight run id at ``lg:stream:{threadId}``
|
||
* but **deletes that key on stream onSuccess**. We keep a second key the SDK
|
||
* never touches so a 409 / dropped-SSE exception can still rejoin. Normal
|
||
* SSE close clears it immediately — do not wait for ``runs.get``.
|
||
*/
|
||
const ACTIVE_RUN_STORAGE_PREFIX = "df:active-run:";
|
||
|
||
function persistActiveRunId(threadId: string, runId: string): void {
|
||
if (typeof window === "undefined") return;
|
||
const normalized = normalizeStoredRunId(runId);
|
||
if (!normalized) return;
|
||
try {
|
||
window.sessionStorage.setItem(`lg:stream:${threadId}`, normalized);
|
||
window.sessionStorage.setItem(
|
||
`${ACTIVE_RUN_STORAGE_PREFIX}${threadId}`,
|
||
normalized,
|
||
);
|
||
} catch {
|
||
/* private-mode / quota */
|
||
}
|
||
}
|
||
|
||
function readActiveRunId(threadId: string): string | null {
|
||
if (typeof window === "undefined") return null;
|
||
try {
|
||
return (
|
||
normalizeStoredRunId(
|
||
window.sessionStorage.getItem(`${ACTIVE_RUN_STORAGE_PREFIX}${threadId}`),
|
||
) ||
|
||
normalizeStoredRunId(window.sessionStorage.getItem(`lg:stream:${threadId}`))
|
||
);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function clearActiveRunId(threadId: string): void {
|
||
if (typeof window === "undefined") return;
|
||
try {
|
||
window.sessionStorage.removeItem(`lg:stream:${threadId}`);
|
||
window.sessionStorage.removeItem(
|
||
`${ACTIVE_RUN_STORAGE_PREFIX}${threadId}`,
|
||
);
|
||
} catch {
|
||
/* noop */
|
||
}
|
||
}
|
||
|
||
function isInflightRunStatus(status: string | undefined): boolean {
|
||
return status === "pending" || status === "running";
|
||
}
|
||
|
||
/**
|
||
* 显式停止某会话「服务端正在跑」的 run。
|
||
*
|
||
* 注意:useStream / `thread.stop()` 只中断本地 SSE 监听,服务端 run 仍会继续跑。
|
||
* 任务流程要求「开启新对话时老对话要停止」,所以这里读出 SDK 存在 sessionStorage
|
||
* (``lg:stream:{threadId}``)里的 run id,调用 ``runs.cancel`` 真正取消后端 run,
|
||
* 再清掉本地 reconnect 记录。已结束 / 不存在的 run 取消失败时静默忽略。
|
||
*/
|
||
export async function stopThreadRun(
|
||
threadId: string | null | undefined,
|
||
): Promise<void> {
|
||
if (!threadId || typeof window === "undefined") return;
|
||
let runId: string | null = null;
|
||
try {
|
||
runId =
|
||
normalizeStoredRunId(
|
||
window.sessionStorage.getItem(`lg:stream:${threadId}`),
|
||
) || readActiveRunId(threadId);
|
||
} catch {
|
||
runId = null;
|
||
}
|
||
if (!runId) return;
|
||
try {
|
||
await getAPIClient().runs.cancel(threadId, runId);
|
||
} catch {
|
||
/* 已结束 / 不存在 / 网络错误等忽略 */
|
||
}
|
||
clearActiveRunId(threadId);
|
||
}
|
||
|
||
/**
|
||
* 协助卡提交前:若上一轮还在流式(弱模型出卡后偶发未停干净),先取消服务端 run
|
||
* 并断开本地 SSE,避免 409「已有活跃 run」或用户点了选项却发不出去。
|
||
*
|
||
* 不在发送前 GET /runs —— 协助卡出现时图多半已经结束,为兜底去查会让每次
|
||
* 点选项都卡住。未在流式则直接发;真遇到 409 再走 confirmOrRejoin。
|
||
*/
|
||
export async function stopActiveThreadBeforeClarificationReply(
|
||
threadId: string | null | undefined,
|
||
thread: { isLoading?: boolean; stop: () => void | Promise<void> },
|
||
): Promise<void> {
|
||
if (!thread.isLoading) {
|
||
if (threadId) clearActiveRunId(threadId);
|
||
return;
|
||
}
|
||
try {
|
||
await stopThreadRun(threadId);
|
||
} catch {
|
||
/* best-effort */
|
||
}
|
||
try {
|
||
await Promise.resolve(thread.stop());
|
||
} catch {
|
||
/* best-effort */
|
||
}
|
||
// cancel 落地需要一拍,立刻 submit 仍可能 409。
|
||
await new Promise((resolve) => setTimeout(resolve, 120));
|
||
}
|
||
|
||
const TERMINAL_RUN_STATUSES = new Set([
|
||
"success",
|
||
"error",
|
||
"timeout",
|
||
"interrupted",
|
||
]);
|
||
|
||
const STREAM_RECONCILIATION_POLL_MS = 5_000;
|
||
// A run can legitimately be quiet while a long tool call / slow model write is
|
||
// in progress. Reconnect only after a long stall; replacing the local reader
|
||
// must NOT cancel the backend run (see reconnect below).
|
||
const STREAM_RECONNECT_MAX_ATTEMPTS = 3;
|
||
|
||
async function fetchThreadTitleRefreshState(
|
||
threadId: string,
|
||
signal?: AbortSignal,
|
||
): Promise<ThreadTitleRefreshState | null> {
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(threadId)}/title-state`,
|
||
{ signal },
|
||
);
|
||
if (!response.ok) {
|
||
return null;
|
||
}
|
||
const json = (await response.json()) as {
|
||
title?: string;
|
||
title_provisional?: boolean | null;
|
||
};
|
||
return {
|
||
title: json.title ?? "",
|
||
title_provisional: json.title_provisional ?? null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Detect "thread not found" / forbidden errors from the LangGraph SDK.
|
||
*
|
||
* Backend returns 404 both when a thread truly doesn't exist and when the
|
||
* currently authenticated user doesn't own it — the SDK surfaces both as
|
||
* ``HTTP 404: {"detail":"Thread <uuid> not found"}``. The most common cause
|
||
* we see in practice is a stale tab whose URL still points at the previous
|
||
* login session's thread. Raw-toasting the 404 just confuses the user, so
|
||
* we re-frame it around the current login identity.
|
||
*/
|
||
function isThreadNotAccessibleError(message: string): boolean {
|
||
const lowered = message.toLowerCase();
|
||
// Backend now returns "not found" (no row + no checkpoint) and
|
||
// "not accessible" (row owned by another user / stale login session) as
|
||
// distinct details — both mean the current user can't use this thread.
|
||
if (/thread\s+[\w-]{8,}\s+not\s+(found|accessible)/i.test(message)) {
|
||
return true;
|
||
}
|
||
// Fallback: a bare 404/403 from the threads endpoint when the SDK has
|
||
// wrapped the detail differently.
|
||
return (
|
||
(lowered.includes("http 404") || lowered.includes("http 403")) &&
|
||
lowered.includes("thread")
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Detect a "Run <id> not found" 404 from the LangGraph SDK.
|
||
*
|
||
* The SDK persists the in-flight run id under ``lg:stream:{threadId}`` in
|
||
* sessionStorage and, on mount, auto-``joinStream``s it to resume a dropped
|
||
* SSE. After a backend restart the in-memory run registry is gone, so the join
|
||
* 404s — and the SDK only clears that key on reconnect *success*, never on
|
||
* failure. So every switch back into the conversation re-fires the same 404.
|
||
* We detect it here to clear the stale key ourselves and stay silent (the
|
||
* conversation renders from history; there is nothing live to reconnect to).
|
||
*/
|
||
function isRunNotFoundError(message: string): boolean {
|
||
return /run\s+[\w-]{8,}\s+not\s+found/i.test(message);
|
||
}
|
||
|
||
/**
|
||
* 同一会话上一轮还没生成完,又提交了新问题 → 后端返回 409
|
||
* 「already has an active run」。匹配 HTTP 409、英文兜底文案,或后端已中文化
|
||
* 的提示,统一映射成一句友好的中文。
|
||
*/
|
||
function isActiveRunConflictError(message: string): boolean {
|
||
return (
|
||
/\b409\b/.test(message) ||
|
||
/already has an active run/i.test(message) ||
|
||
/还在生成回答/.test(message)
|
||
);
|
||
}
|
||
|
||
function isModelConcurrencyLimitError(message: string): boolean {
|
||
return (
|
||
/\b429\b/.test(message) ||
|
||
/并发已达到上限/.test(message) ||
|
||
/并发调用已达到上限/.test(message) ||
|
||
/使用人数较多/.test(message) ||
|
||
/too many requests/i.test(message)
|
||
);
|
||
}
|
||
|
||
function friendlySendLimitMessage(message: string): string | null {
|
||
if (isActiveRunConflictError(message)) {
|
||
return "当前对话还在生成回答,请等待本轮回复结束,或先点“停止”再发送新的问题。";
|
||
}
|
||
if (isModelConcurrencyLimitError(message)) {
|
||
return /当前账号对该模型/.test(message)
|
||
? "当前账号对该模型的并发调用已达到上限,请等待已有回答结束后再试。"
|
||
: "当前使用人数较多,请稍等一下再试。";
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function buildCurrentUserLabel(): string {
|
||
const auth = getStoredAuth();
|
||
if (!auth) {
|
||
return "未登录";
|
||
}
|
||
const email = auth.email?.trim();
|
||
if (email) {
|
||
return email;
|
||
}
|
||
const userId = auth.user_id?.trim();
|
||
return userId ? userId : "未知用户";
|
||
}
|
||
|
||
/**
|
||
* 从 `on_chat_model_end` 事件的 output 里尽力取出模型输出文本。
|
||
*
|
||
* output 形态可能是 AIMessage(`{ content: string | parts[] }`),也可能是
|
||
* LangChain 的 `{ generations: [[{ text, message }]] }`。全部容错,取不到返回空串。
|
||
*/
|
||
function textFromChatModelOutput(output: unknown): string {
|
||
if (output == null) return "";
|
||
if (typeof output === "string") return output;
|
||
if (typeof output !== "object") return String(output);
|
||
const o = output as Record<string, unknown>;
|
||
if ("content" in o) {
|
||
const c = o.content;
|
||
if (typeof c === "string") return c;
|
||
if (Array.isArray(c)) {
|
||
const parts = c
|
||
.map((p) =>
|
||
p && typeof p === "object" && "text" in p
|
||
? String((p as { text?: unknown }).text ?? "")
|
||
: "",
|
||
)
|
||
.filter(Boolean);
|
||
if (parts.length) return parts.join("");
|
||
}
|
||
}
|
||
if (Array.isArray(o.generations)) {
|
||
const texts: string[] = [];
|
||
const collect = (gen: unknown) => {
|
||
if (Array.isArray(gen)) {
|
||
gen.forEach(collect);
|
||
return;
|
||
}
|
||
if (gen && typeof gen === "object") {
|
||
const gg = gen as Record<string, unknown>;
|
||
if (typeof gg.text === "string" && gg.text) texts.push(gg.text);
|
||
else if (gg.message) {
|
||
const t = textFromChatModelOutput(gg.message);
|
||
if (t) texts.push(t);
|
||
}
|
||
}
|
||
};
|
||
collect(o.generations);
|
||
if (texts.length) return texts.join("");
|
||
}
|
||
return "";
|
||
}
|
||
|
||
/**
|
||
* 从 `on_chat_model_*` 事件的 input 里尽力取出最后一条 user/human 文本,
|
||
* 作为本次大模型调用的「问题」。input 可能是 `{ messages: BaseMessage[] | BaseMessage[][] }`。
|
||
*/
|
||
function lastHumanFromChatModelInput(input: unknown): string {
|
||
try {
|
||
const raw =
|
||
input && typeof input === "object" && "messages" in input
|
||
? (input as { messages?: unknown }).messages
|
||
: input;
|
||
const flat: unknown[] = [];
|
||
const push = (m: unknown) => {
|
||
if (Array.isArray(m)) m.forEach(push);
|
||
else if (m != null) flat.push(m);
|
||
};
|
||
push(raw);
|
||
for (let i = flat.length - 1; i >= 0; i--) {
|
||
const m = flat[i];
|
||
if (!m || typeof m !== "object") continue;
|
||
const obj = m as Record<string, unknown>;
|
||
const type = obj.type ?? obj.role;
|
||
if (type === "human" || type === "user") {
|
||
const kwargs = obj.additional_kwargs;
|
||
if (
|
||
kwargs &&
|
||
typeof kwargs === "object" &&
|
||
(kwargs as Record<string, unknown>).hide_from_ui === true
|
||
) {
|
||
continue;
|
||
}
|
||
const text = textFromChatModelOutput(m);
|
||
if (text) return text;
|
||
}
|
||
}
|
||
} catch {
|
||
/* 取不到忽略 */
|
||
}
|
||
return "";
|
||
}
|
||
|
||
export function useThreadStream({
|
||
threadId,
|
||
context,
|
||
isMock,
|
||
assistantId,
|
||
runOptions,
|
||
threadMetadata,
|
||
suppressUserFacingStreamErrors = false,
|
||
onStart,
|
||
onFinish,
|
||
onToolStart,
|
||
onToolEnd,
|
||
}: ThreadStreamOptions) {
|
||
const { t } = useI18n();
|
||
const [localSettings] = useLocalSettings();
|
||
const { data: citationDisplay } = useCitationDisplaySettings();
|
||
const referenceModeEntryEnabled =
|
||
citationDisplay?.reference_mode_enabled ?? false;
|
||
// Track the thread ID that is currently streaming to handle thread changes during streaming
|
||
const [onStreamThreadId, setOnStreamThreadId] = useState(() => threadId);
|
||
// The cursor lifetime must match this hook's SDK message accumulator.
|
||
// Shared API clients cannot tell a same-reader recovery from a fresh mount.
|
||
const streamClient = useMemo(() => createStreamAPIClient(isMock), [isMock]);
|
||
const streamCursorThreadIdRef = useRef<string | null>(threadId ?? null);
|
||
// Ref to track current thread ID across async callbacks without causing re-renders,
|
||
// and to allow access to the current thread id in onUpdateEvent
|
||
const threadIdRef = useRef<string | null>(threadId ?? null);
|
||
const startedRef = useRef(false);
|
||
const lastStreamActivityAtRef = useRef(0);
|
||
const streamReconciliationFlightRef = useRef<StreamRecoverySingleFlight>({
|
||
current: null,
|
||
});
|
||
const streamReconnectAttemptsRef = useRef(0);
|
||
const streamReconnectFailureToastShownRef = useRef(false);
|
||
const streamReaderRecycleRunIdRef = useRef<string | null>(null);
|
||
const activeRunIdRef = useRef<string | null>(
|
||
threadId && typeof window !== "undefined" ? readActiveRunId(threadId) : null,
|
||
);
|
||
const confirmOrRejoinRef = useRef<
|
||
(
|
||
reason: "finish" | "error" | "poll" | "idle" | "conflict",
|
||
) => Promise<StreamRecoveryResult>
|
||
>(async () => "unknown");
|
||
// Held only on exception recovery (dropped SSE / 409). Normal turns rely
|
||
// on SDK `isLoading` so the send button unlocks as soon as SSE closes.
|
||
const [streamHoldOpen, setStreamHoldOpen] = useState(false);
|
||
const sendInFlightRef = useRef(false);
|
||
const sendEpochRef = useRef(0);
|
||
const activeRetrievalScopeRef = useRef<{
|
||
scopeId: string;
|
||
threadId: string;
|
||
runId: string | null;
|
||
} | null>(null);
|
||
const createdThreadIdRef = useRef<string | null>(null);
|
||
const [newConversationBoundary, setNewConversationBoundary] =
|
||
useState<NewConversationDisplayBoundary | null>(
|
||
threadId == null ? new Set<string>() : null,
|
||
);
|
||
const reactUiRecoveryRef = useRef(createReactStreamRecoveryBudget());
|
||
// Filled after useStream; onFinish/onError may read it asynchronously.
|
||
const threadStreamRef = useRef<{
|
||
isLoading: boolean;
|
||
stop: () => void | Promise<void>;
|
||
joinStream: (runId: string, lastEventId?: string) => Promise<unknown>;
|
||
messages: Message[];
|
||
values?: AgentThreadState;
|
||
} | null>(null);
|
||
|
||
const reportStreamIssue = useCallback(
|
||
(message: string, level: "error" | "info" = "error") => {
|
||
if (suppressUserFacingStreamErrors) {
|
||
const log = level === "error" ? console.error : console.warn;
|
||
log("[deer-flow] task-deeplink stream notification suppressed", {
|
||
message,
|
||
threadId: threadIdRef.current,
|
||
runId: activeRunIdRef.current,
|
||
});
|
||
return;
|
||
}
|
||
toast[level](message);
|
||
},
|
||
[suppressUserFacingStreamErrors],
|
||
);
|
||
|
||
const markStreamActivity = useCallback(() => {
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
streamReconnectAttemptsRef.current = 0;
|
||
streamReconnectFailureToastShownRef.current = false;
|
||
}, []);
|
||
|
||
const listeners = useRef({
|
||
onStart,
|
||
onFinish,
|
||
onToolStart,
|
||
onToolEnd,
|
||
});
|
||
const recoveryFinishPendingRef = useRef(false);
|
||
|
||
const backgroundHistory: BackgroundHistory<AgentThreadState> = useMemo(() => new BackgroundHistory<AgentThreadState>({
|
||
load: async (tid, signal) => {
|
||
// Latest head only. getState uses aget_tuple; getHistory(limit:1) used
|
||
// to walk the checkpoint iterator and, with dual-read, scan legacy DBs.
|
||
const state = await streamClient.client.threads.getState<AgentThreadState>(
|
||
tid,
|
||
undefined,
|
||
{ signal },
|
||
);
|
||
const flat = state as ThreadState<AgentThreadState> & {
|
||
checkpoint_id?: string;
|
||
parent_checkpoint_id?: string;
|
||
};
|
||
return [
|
||
{
|
||
...state,
|
||
checkpoint:
|
||
state.checkpoint ?? {
|
||
thread_id: tid,
|
||
checkpoint_ns: "",
|
||
checkpoint_id: flat.checkpoint_id ?? null,
|
||
checkpoint_map: null,
|
||
},
|
||
parent_checkpoint:
|
||
state.parent_checkpoint ??
|
||
(flat.parent_checkpoint_id
|
||
? {
|
||
thread_id: tid,
|
||
checkpoint_ns: "",
|
||
checkpoint_id: flat.parent_checkpoint_id,
|
||
checkpoint_map: null,
|
||
}
|
||
: null),
|
||
tasks: state.tasks ?? [],
|
||
},
|
||
];
|
||
},
|
||
values: () => threadStreamRef.current?.values,
|
||
started: () => {
|
||
recoveryFinishPendingRef.current = false;
|
||
setThreadValueOverrides((prev) => {
|
||
const { title, title_provisional } = prev;
|
||
return { ...(title !== undefined ? { title } : {}), ...(title_provisional !== undefined ? { title_provisional } : {}) };
|
||
});
|
||
},
|
||
hydrated: (state, scope, notifyFinish) => {
|
||
if (!backgroundHistory.current(scope)) return;
|
||
setThreadValueOverrides(state.values);
|
||
if (notifyFinish && recoveryFinishPendingRef.current) {
|
||
recoveryFinishPendingRef.current = false;
|
||
listeners.current.onFinish?.(state.values);
|
||
}
|
||
},
|
||
// Keep the final state refresh and its fallback hydration, but don't show
|
||
// a user-facing toast when the streamed answer is already available.
|
||
syncFailed: () => {},
|
||
}), [streamClient, reportStreamIssue]);
|
||
streamClient.setHistoryObserver(backgroundHistory.observe);
|
||
const historyRouteRef = useRef(threadId ?? null);
|
||
if (historyRouteRef.current !== (threadId ?? null)) {
|
||
historyRouteRef.current = threadId ?? null;
|
||
if (backgroundHistory.snapshot().threadId !== (threadId ?? null)) backgroundHistory.fence();
|
||
}
|
||
const historyView = useSyncExternalStore(backgroundHistory.subscribe, backgroundHistory.snapshot, backgroundHistory.snapshot);
|
||
useEffect(() => {
|
||
backgroundHistory.select(threadId ?? null);
|
||
void backgroundHistory.initial();
|
||
}, [backgroundHistory, threadId]);
|
||
useEffect(() => () => backgroundHistory.cancel(), [backgroundHistory]);
|
||
|
||
// Keep listeners ref updated with latest callbacks
|
||
useEffect(() => {
|
||
listeners.current = { onStart, onFinish, onToolStart, onToolEnd };
|
||
}, [onStart, onFinish, onToolStart, onToolEnd]);
|
||
|
||
useEffect(() => {
|
||
const normalizedThreadId = threadId ?? null;
|
||
if (streamCursorThreadIdRef.current !== normalizedThreadId) {
|
||
streamClient.clearResumeCursors();
|
||
streamCursorThreadIdRef.current = normalizedThreadId;
|
||
}
|
||
if (!normalizedThreadId) {
|
||
// Reset when the UI moves back to a brand new unsaved thread.
|
||
startedRef.current = false;
|
||
setOnStreamThreadId(normalizedThreadId);
|
||
} else {
|
||
setOnStreamThreadId(normalizedThreadId);
|
||
}
|
||
threadIdRef.current = normalizedThreadId;
|
||
}, [threadId, streamClient]);
|
||
|
||
const _handleOnStart = useCallback((id: string) => {
|
||
if (!startedRef.current) {
|
||
listeners.current.onStart?.(id);
|
||
startedRef.current = true;
|
||
}
|
||
}, []);
|
||
|
||
const handleStreamStart = useCallback(
|
||
(_threadId: string) => {
|
||
threadIdRef.current = _threadId;
|
||
markStreamActivity();
|
||
_handleOnStart(_threadId);
|
||
},
|
||
[_handleOnStart, markStreamActivity],
|
||
);
|
||
|
||
const queryClient = useQueryClient();
|
||
const updateSubtask = useUpdateSubtask();
|
||
const navigate = useNavigate();
|
||
const runMetadataStorageRef = useRef<
|
||
ReturnType<typeof getRunMetadataStorage> | undefined
|
||
>(undefined);
|
||
|
||
if (
|
||
typeof window !== "undefined" &&
|
||
runMetadataStorageRef.current === undefined
|
||
) {
|
||
runMetadataStorageRef.current = getRunMetadataStorage();
|
||
}
|
||
|
||
const reactUiRecoveryKey = () =>
|
||
`${threadIdRef.current ?? onStreamThreadId ?? "new"}:${sendEpochRef.current}`;
|
||
|
||
const handleReactUiStreamError = (error: unknown, phase: string) => {
|
||
const key = reactUiRecoveryKey();
|
||
const action = reactUiRecoveryRef.current.claim(key, error);
|
||
console.warn("[deer-flow] stream_ui_error_recovery", {
|
||
surface: "main-chat", phase, action,
|
||
errorType: "react_maximum_update_depth",
|
||
threadId: threadIdRef.current, runId: activeRunIdRef.current,
|
||
});
|
||
if (action === "duplicate") return;
|
||
// Leave the SDK/React notification stack before updating hook state.
|
||
window.setTimeout(() => {
|
||
if (key !== reactUiRecoveryKey()) return;
|
||
if (reactUiRecoveryRef.current.isPaused(key)) {
|
||
const tid = threadIdRef.current ?? onStreamThreadId;
|
||
// Clear both reconnect markers before stop(): only detach this browser
|
||
// reader, never cancel the server task because its UI failed.
|
||
if (tid) clearActiveRunId(tid);
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
setIsUploading(false);
|
||
setOptimisticMessages([]);
|
||
void Promise.resolve(threadStreamRef.current?.stop()).catch(() => undefined);
|
||
reportReactUiError(error, "main-chat", "automatic_recovery_paused");
|
||
return;
|
||
}
|
||
setStreamHoldOpen(true);
|
||
void confirmOrRejoinRef.current("error");
|
||
}, 0);
|
||
};
|
||
|
||
const thread = useStream<AgentThreadState>({
|
||
client: streamClient.client,
|
||
assistantId: assistantId ?? "lead_agent",
|
||
threadId: onStreamThreadId,
|
||
// Batch asynchronously; a numeric delay can hide fast continuous streams.
|
||
throttle: STREAM_RENDER_BATCHING,
|
||
reconnectOnMount: runMetadataStorageRef.current
|
||
? () => runMetadataStorageRef.current!
|
||
: false,
|
||
fetchStateHistory: { limit: 1 },
|
||
thread: { ...historyView, mutate: backgroundHistory.mutate },
|
||
onCreated(meta) {
|
||
// Assigning the first server thread id does not clear the SDK's live
|
||
// accumulator, unlike navigating to a different existing conversation.
|
||
streamCursorThreadIdRef.current = meta.thread_id;
|
||
createdThreadIdRef.current = meta.thread_id;
|
||
handleStreamStart(meta.thread_id);
|
||
setOnStreamThreadId(meta.thread_id);
|
||
if (meta.run_id) {
|
||
activeRunIdRef.current = meta.run_id;
|
||
persistActiveRunId(meta.thread_id, meta.run_id);
|
||
}
|
||
const retrievalScope = activeRetrievalScopeRef.current;
|
||
if (retrievalScope) {
|
||
const requestedThreadId = retrievalScope.threadId;
|
||
retrievalScope.threadId = meta.thread_id;
|
||
retrievalScope.runId = meta.run_id ?? null;
|
||
beginKnowledgeRetrievalProgress(meta.thread_id, {
|
||
scopeId: retrievalScope.scopeId,
|
||
runId: retrievalScope.runId,
|
||
});
|
||
bindKnowledgeRetrievalProgressRun(meta.thread_id, {
|
||
scopeId: retrievalScope.scopeId,
|
||
runId: retrievalScope.runId,
|
||
});
|
||
if (requestedThreadId !== meta.thread_id) {
|
||
clearKnowledgeRetrievalProgress(requestedThreadId);
|
||
}
|
||
}
|
||
const metadataAgentId = context.agent_id ?? context.agent_name;
|
||
const extraMetadata =
|
||
threadMetadata && typeof threadMetadata === "object" ? threadMetadata : {};
|
||
const metadata = withKnowledgeRetrievalModeMetadata(
|
||
{
|
||
...(metadataAgentId ? { agent_id: metadataAgentId } : {}),
|
||
...extraMetadata,
|
||
},
|
||
context.knowledge_retrieval_mode,
|
||
);
|
||
if (Object.keys(metadata).length > 0 && !isMock) {
|
||
void getAPIClient()
|
||
.threads.update(meta.thread_id, { metadata })
|
||
.then(() => {
|
||
// Task deep-link history is registered by this metadata patch.
|
||
// Refresh immediately so a long-running first answer appears in
|
||
// the left history list before the run reaches onFinish.
|
||
if (typeof metadata.taskGoPath === "string") {
|
||
void queryClient.invalidateQueries({
|
||
queryKey: ["threads", "search"],
|
||
});
|
||
}
|
||
})
|
||
.catch(() => ({}));
|
||
}
|
||
},
|
||
onLangChainEvent(event) {
|
||
markStreamActivity();
|
||
// 操作日志(Y-Log):每一次大模型调用结束都各上报一条(一次 LLM 调用 = 一条),
|
||
// 让问答日志尽量「多、全」——一个问答轮次里 lead agent / 子代理的每次模型调用
|
||
// 都会落一条。门控与失败静默都在 writeYLog 内部处理,绝不影响问答。
|
||
if (event.event === "on_chat_model_end") {
|
||
try {
|
||
const data = (event.data ?? {}) as {
|
||
input?: unknown;
|
||
output?: unknown;
|
||
};
|
||
const answer = textFromChatModelOutput(data.output);
|
||
const question = lastHumanFromChatModelInput(data.input);
|
||
writeYLog({
|
||
optType: OptType.other,
|
||
optDetail: "CM助手-全量-智能问答",
|
||
url: `/api/threads/${threadIdRef.current ?? ""}/runs/stream`,
|
||
reqParam: { model: event.name ?? "", question },
|
||
returnParam: { data: answer },
|
||
});
|
||
} catch {
|
||
/* 上报绝不影响问答 */
|
||
}
|
||
}
|
||
},
|
||
// The SDK emits UI tool lifecycle events on the dedicated `tools` stream
|
||
// mode. `events` is a separate LangChain trace channel; using it for UI
|
||
// reactions can miss a tool that the conversation has already rendered.
|
||
onToolEvent:
|
||
onToolStart || onToolEnd
|
||
? (event) => {
|
||
markStreamActivity();
|
||
if (event.event === "on_tool_start") {
|
||
listeners.current.onToolStart?.({
|
||
name: event.name,
|
||
data: event.input,
|
||
toolCallId: event.toolCallId,
|
||
});
|
||
return;
|
||
}
|
||
if (event.event === "on_tool_end") {
|
||
listeners.current.onToolEnd?.({
|
||
name: event.name,
|
||
data: event.output,
|
||
toolCallId: event.toolCallId,
|
||
});
|
||
}
|
||
}
|
||
: undefined,
|
||
onUpdateEvent(data) {
|
||
markStreamActivity();
|
||
const updates: Array<Partial<AgentThreadState> | null> = Object.values(
|
||
data || {},
|
||
);
|
||
for (const update of updates) {
|
||
if (update && "title" in update && update.title) {
|
||
const nextTitle = update.title;
|
||
updateCachedThreadLists(queryClient, (threads) =>
|
||
threads.map((t) =>
|
||
t.thread_id === threadIdRef.current
|
||
? {
|
||
...t,
|
||
values: {
|
||
...t.values,
|
||
title: nextTitle,
|
||
},
|
||
}
|
||
: t,
|
||
),
|
||
);
|
||
}
|
||
}
|
||
},
|
||
onCustomEvent(event: unknown) {
|
||
markStreamActivity();
|
||
if (
|
||
typeof event === "object" &&
|
||
event !== null &&
|
||
"type" in event &&
|
||
event.type === "knowledge_retrieval_progress"
|
||
) {
|
||
const tid = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
if (tid) {
|
||
let retrievalScope = activeRetrievalScopeRef.current;
|
||
if (!retrievalScope || retrievalScope.threadId !== tid) {
|
||
const runId = activeRunIdRef.current;
|
||
retrievalScope = {
|
||
scopeId: `recovered:${tid}:${runId ?? sendEpochRef.current}`,
|
||
threadId: tid,
|
||
runId,
|
||
};
|
||
activeRetrievalScopeRef.current = retrievalScope;
|
||
beginKnowledgeRetrievalProgress(tid, retrievalScope);
|
||
}
|
||
ingestKnowledgeRetrievalProgress(tid, event, {
|
||
scopeId: retrievalScope.scopeId,
|
||
runId: retrievalScope.runId,
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
// 写作模式内联深度研究的进度帧(deep_research_report 工具经
|
||
// get_stream_writer 转发):归约进 per-thread 状态,聊天页据此注入
|
||
// 进度步骤条与 report.md 流式预览。
|
||
if (
|
||
typeof event === "object" &&
|
||
event !== null &&
|
||
"type" in event &&
|
||
event.type === "deep_research_report" &&
|
||
"event" in event &&
|
||
typeof (event as { event?: unknown }).event === "object" &&
|
||
(event as { event?: unknown }).event !== null
|
||
) {
|
||
const tid = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
const frame = (event as { event: Record<string, unknown> }).event;
|
||
if (tid && typeof frame.type === "string") {
|
||
ingestResearchReportEvent(tid, frame as Parameters<typeof ingestResearchReportEvent>[1]);
|
||
}
|
||
return;
|
||
}
|
||
if (
|
||
typeof event === "object" &&
|
||
event !== null &&
|
||
"type" in event &&
|
||
event.type === "task_running"
|
||
) {
|
||
const e = event as {
|
||
type: "task_running";
|
||
task_id: string;
|
||
message: AIMessage;
|
||
};
|
||
updateSubtask({ id: e.task_id, latestMessage: e.message });
|
||
return;
|
||
}
|
||
|
||
if (
|
||
typeof event === "object" &&
|
||
event !== null &&
|
||
"type" in event &&
|
||
event.type === "llm_retry" &&
|
||
"message" in event &&
|
||
typeof event.message === "string" &&
|
||
event.message.trim()
|
||
) {
|
||
// The backend is already handling this with bounded retry/backoff.
|
||
// Surfacing every transient model retry as a toast made normal model
|
||
// stalls look like repeated "network fluctuation" failures.
|
||
return;
|
||
}
|
||
|
||
// Background compaction stays silent, including events from older backends.
|
||
if (
|
||
typeof event === "object" &&
|
||
event !== null &&
|
||
"type" in event &&
|
||
event.type === "context_compacting"
|
||
) {
|
||
return;
|
||
}
|
||
},
|
||
onError(error) {
|
||
// An error is not successful stream activity and must not reset retry
|
||
// budgets; otherwise repeated #185 failures can reconnect forever.
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
const message = getStreamErrorMessage(error);
|
||
// A synchronous SDK store notification used to let React's update-depth
|
||
// guard escape into the stream promise. Do not present that internal UI
|
||
// exception as a model failure. Reconcile/rejoin on the next task so the
|
||
// backend run can continue and the current answer is preserved.
|
||
if (isReactMaximumUpdateDepthError(error)) {
|
||
handleReactUiStreamError(error, "stream_on_error");
|
||
return;
|
||
}
|
||
// Replacing a stalled local SSE reader aborts the in-flight fetch. That
|
||
// is expected and must not look like a user-facing "network" failure.
|
||
if (isAbortLikeError(error)) {
|
||
return;
|
||
}
|
||
// A dropped SSE while the backend run is still alive: rejoin instead of
|
||
// toasting "Failed to fetch" / 网络波动 and leaving the answer half-done.
|
||
if (isTransientStreamTransportError(message)) {
|
||
setStreamHoldOpen(true);
|
||
void confirmOrRejoinRef.current("error");
|
||
return;
|
||
}
|
||
setOptimisticMessages([]);
|
||
// A stale auto-reconnect ("Run <id> not found") after a backend restart:
|
||
// drop the dirty ``lg:stream:{threadId}`` key so switching back into this
|
||
// conversation stops re-firing the same 404, and render from history
|
||
// silently — there is no live run to rejoin.
|
||
if (isRunNotFoundError(message)) {
|
||
const staleThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
if (staleThreadId) {
|
||
clearActiveRunId(staleThreadId);
|
||
}
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
return;
|
||
}
|
||
// A "thread not found" 404 means this route cannot accept another turn.
|
||
// Move to a fresh chat without a full browser reload; the old reload path
|
||
// made every click look like a crash and could loop indefinitely when a
|
||
// different tab's cookie kept overriding this tab's Bearer token.
|
||
if (isThreadNotAccessibleError(message)) {
|
||
const projectHash = typeof window !== "undefined" ? window.location.hash : "";
|
||
const projectMatch = projectHash.match(
|
||
/#\/page\/strategy\/qa\/projects\/(groups|solutions)\/[^/]+\//,
|
||
);
|
||
const legacyProjectMatch = projectHash.match(
|
||
/#\/page\/workspace\/projects\/[^/]+\//,
|
||
);
|
||
if (projectMatch || legacyProjectMatch) {
|
||
const category = projectMatch?.[1] === "solutions" ? "solution" : "qa";
|
||
reportStreamIssue("当前项目对话不存在或无权访问,已返回我的项目。", "info");
|
||
navigate(`/page/strategy/qa/projects?type=${category}`, { replace: true });
|
||
return;
|
||
}
|
||
const userLabel = buildCurrentUserLabel();
|
||
reportStreamIssue(
|
||
`当前登录用户为 ${userLabel},原对话不存在或无权访问,已为你打开新对话。`,
|
||
"info",
|
||
);
|
||
// Prefer staying inside an agent chat context when the user is on an
|
||
// agent thread URL — otherwise fall back to the global new chat.
|
||
const hash = typeof window !== "undefined" ? window.location.hash : "";
|
||
const agentMatch = hash.match(/#\/page\/workspace\/agents\/([^/]+)\//);
|
||
const iframeMatch = hash.match(/#\/page\/workspace\/chats_iframe\//);
|
||
const target = agentMatch
|
||
? `/page/workspace/agents/${agentMatch[1]}/chats/new`
|
||
: iframeMatch
|
||
? "/page/workspace/chats_iframe/new"
|
||
: "/page/workspace/chats/new";
|
||
navigate(target, { replace: true });
|
||
return;
|
||
}
|
||
// 上一轮还没结束又发了新问题(409)或并发达到上限(429):
|
||
// 给一句明确的中文提示,而不是把原始 HTTP 错误抛给用户。
|
||
const friendly = friendlySendLimitMessage(message);
|
||
if (friendly) {
|
||
if (isActiveRunConflictError(message)) {
|
||
setStreamHoldOpen(true);
|
||
void confirmOrRejoinRef.current("conflict").then((result) => {
|
||
reportStreamIssue(
|
||
result === "rejoined"
|
||
? "上一轮回答仍在生成,已重新连接当前回复。请等待结束或点“停止”后再提问。"
|
||
: friendly,
|
||
"info",
|
||
);
|
||
});
|
||
return;
|
||
}
|
||
reportStreamIssue(friendly, "info");
|
||
return;
|
||
}
|
||
reportStreamIssue(message);
|
||
},
|
||
onFinish(state, runMeta) {
|
||
const finishingRunId = runMeta?.run_id;
|
||
if (runMeta?.thread_id && runMeta.thread_id !== backgroundHistory.snapshot().threadId) return;
|
||
if (
|
||
shouldIgnoreReaderRecycleFinish({
|
||
recyclingRunId: streamReaderRecycleRunIdRef.current,
|
||
finishingRunId,
|
||
})
|
||
) {
|
||
return;
|
||
}
|
||
|
||
const finalizeCleanStream = () => {
|
||
if (
|
||
isStaleStreamFinish({
|
||
finishingRunId,
|
||
currentRunId: activeRunIdRef.current,
|
||
})
|
||
) {
|
||
return;
|
||
}
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
const finThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
if (finThreadId) {
|
||
clearActiveRunId(finThreadId);
|
||
finalizeResearchReportStream(finThreadId);
|
||
}
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
// End confirms the streamed snapshot is complete. Deliver this turn's
|
||
// business callback before another send can replace its page context;
|
||
// background hydration must not repeat or cancel it.
|
||
recoveryFinishPendingRef.current = false;
|
||
if (state?.values) listeners.current.onFinish?.(state.values);
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
};
|
||
|
||
if (!backgroundHistory.terminalSeen()) {
|
||
// EOF without an explicit end can be a proxy disconnect while the
|
||
// resumable backend run is alive. Confirm it before unlocking.
|
||
setStreamHoldOpen(true);
|
||
void confirmOrRejoinRef
|
||
.current("finish")
|
||
.catch(() => {});
|
||
return;
|
||
}
|
||
|
||
finalizeCleanStream();
|
||
},
|
||
});
|
||
|
||
// Optimistic messages shown before the server stream responds
|
||
const [optimisticMessages, setOptimisticMessages] = useState<Message[]>([]);
|
||
const [isUploading, setIsUploading] = useState(false);
|
||
const [threadValueOverrides, setThreadValueOverrides] = useState<
|
||
Partial<AgentThreadState>
|
||
>({});
|
||
// Carries the ask time of an in-flight send until the server-assigned human
|
||
// message id shows up, so we can bind the timestamp to the real id (see the
|
||
// reconciliation effect below). ``known`` is the set of human ids that
|
||
// already existed at send time, used to spot the newly-arrived one.
|
||
const pendingAskTimeRef = useRef<{ ts: string; known: Set<string> } | null>(
|
||
null,
|
||
);
|
||
// Human ids known at optimistic-send time; used to clear optimistic only when
|
||
// a *new* server human appears (not when length bumps from tool/checkpoint).
|
||
const optimisticKnownHumanIdsRef = useRef<Set<string>>(new Set());
|
||
// Track message count before sending so we know when server has responded
|
||
const prevMsgCountRef = useRef(thread.messages.length);
|
||
|
||
threadStreamRef.current = thread;
|
||
|
||
useEffect(() => {
|
||
if (thread.isLoading) {
|
||
// `write_file` arguments arrive through messages-tuple chunks. The SDK
|
||
// assembles those directly into `messages` and does not invoke the
|
||
// update/custom/tool callbacks above, so message changes are the only
|
||
// reliable business-activity signal for a long streaming tool call.
|
||
markStreamActivity();
|
||
}
|
||
}, [markStreamActivity, thread.isLoading, thread.messages]);
|
||
|
||
const confirmOrRejoin = useCallback(
|
||
(
|
||
reason: "finish" | "error" | "poll" | "idle" | "conflict",
|
||
): Promise<StreamRecoveryResult> => {
|
||
const reconcile = async (): Promise<StreamRecoveryResult> => {
|
||
const tid = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
if (!tid) {
|
||
setStreamHoldOpen(false);
|
||
return "unknown";
|
||
}
|
||
|
||
const epochAtStart = sendEpochRef.current;
|
||
const uiRecoveryKey = `${tid}:${epochAtStart}`;
|
||
const isCurrentRecovery = () =>
|
||
threadIdRef.current === tid &&
|
||
sendEpochRef.current === epochAtStart &&
|
||
!reactUiRecoveryRef.current.isPaused(uiRecoveryKey);
|
||
if (reactUiRecoveryRef.current.isPaused(uiRecoveryKey)) {
|
||
setStreamHoldOpen(false);
|
||
return "unknown";
|
||
}
|
||
const client = getAPIClient(isMock);
|
||
let runId = activeRunIdRef.current ?? readActiveRunId(tid);
|
||
const terminalRunId = runId;
|
||
|
||
const applyTerminalState = async (status: string) => {
|
||
if (
|
||
!isCurrentRecovery() ||
|
||
shouldDiscardTerminalOverlay({
|
||
epochAtStart,
|
||
currentEpoch: sendEpochRef.current,
|
||
terminalRunId,
|
||
currentRunId: activeRunIdRef.current,
|
||
})
|
||
) {
|
||
return false;
|
||
}
|
||
// A proxy can leave the local SSE open after the backend has ended.
|
||
// Clearing only streamHoldOpen leaves SDK isLoading=true and hides
|
||
// this checkpoint's messages behind the frozen live tool card.
|
||
// Remove the SDK marker first: stop() must only detach this reader.
|
||
const readerStopped = await stopRecoveredRunReader({
|
||
isCurrent: isCurrentRecovery,
|
||
clearReconnect: () => clearActiveRunId(tid),
|
||
stop: () => threadStreamRef.current?.stop(),
|
||
});
|
||
if (!readerStopped) return false;
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
streamReconnectAttemptsRef.current = 0;
|
||
streamReconnectFailureToastShownRef.current = false;
|
||
// Recovery can have missed the answer's final SSE frames. Its
|
||
// completion callback still needs the guarded persisted state.
|
||
recoveryFinishPendingRef.current = status === "success";
|
||
backgroundHistory.confirmTerminal();
|
||
void backgroundHistory.refresh(status === "success");
|
||
finalizeResearchReportStream(tid);
|
||
if (status === "success") {
|
||
setOptimisticMessages([]);
|
||
void queryClient.invalidateQueries({
|
||
queryKey: ["threads", "search"],
|
||
});
|
||
} else {
|
||
reportStreamIssue(
|
||
"本轮生成未能完成,已同步当前对话内容,可重新发起请求。",
|
||
);
|
||
}
|
||
return true;
|
||
};
|
||
|
||
let terminalStatus: string | undefined;
|
||
if (runId) {
|
||
try {
|
||
const run = await client.runs.get(tid, runId);
|
||
if (!isCurrentRecovery()) return "unknown";
|
||
console.info("[deer-flow] stream recovery probe", {
|
||
threadId: tid,
|
||
runId,
|
||
reason,
|
||
idleForMs: Math.max(
|
||
0,
|
||
Date.now() - lastStreamActivityAtRef.current,
|
||
),
|
||
attempt: streamReconnectAttemptsRef.current,
|
||
status: run.status,
|
||
});
|
||
if (TERMINAL_RUN_STATUSES.has(run.status)) {
|
||
terminalStatus = run.status;
|
||
}
|
||
} catch {
|
||
if (!isCurrentRecovery()) return "unknown";
|
||
console.info("[deer-flow] stream recovery probe", {
|
||
threadId: tid,
|
||
runId,
|
||
reason,
|
||
idleForMs: Math.max(
|
||
0,
|
||
Date.now() - lastStreamActivityAtRef.current,
|
||
),
|
||
attempt: streamReconnectAttemptsRef.current,
|
||
status: "lookup_failed",
|
||
});
|
||
runId = null;
|
||
}
|
||
}
|
||
|
||
if (terminalStatus) {
|
||
try {
|
||
return (await applyTerminalState(terminalStatus))
|
||
? "terminal"
|
||
: "unknown";
|
||
} catch {
|
||
// Reader cleanup can fail independently of the known terminal
|
||
// run. Keep recovery alive so a later probe can detach it.
|
||
if (isCurrentRecovery()) {
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
setStreamHoldOpen(true);
|
||
}
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
if (!runId) {
|
||
try {
|
||
const runs = await client.runs.list(tid, { limit: 20 });
|
||
if (!isCurrentRecovery()) return "unknown";
|
||
const inflight = runs.find((item) =>
|
||
isInflightRunStatus(item.status),
|
||
);
|
||
runId = inflight?.run_id ?? null;
|
||
if (runId) {
|
||
activeRunIdRef.current = runId;
|
||
} else {
|
||
const lastTerminal = runs.find((item) =>
|
||
TERMINAL_RUN_STATUSES.has(item.status),
|
||
);
|
||
if (lastTerminal) terminalStatus = lastTerminal.status;
|
||
}
|
||
} catch {
|
||
if (!isCurrentRecovery()) return "unknown";
|
||
// Unreachable is different from a confirmed empty run list.
|
||
// In particular, a dropped reader must keep retrying instead of
|
||
// silently losing its recovery flag after a control timeout.
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
setStreamHoldOpen(true);
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
if (terminalStatus) {
|
||
try {
|
||
return (await applyTerminalState(terminalStatus))
|
||
? "terminal"
|
||
: "unknown";
|
||
} catch {
|
||
if (isCurrentRecovery()) {
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
setStreamHoldOpen(true);
|
||
}
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
if (!runId) {
|
||
// The backend confirms there is no in-flight run, but an SDK reader
|
||
// can remain locally open after a proxy/SSE disconnect. Detach that
|
||
// reader only after removing its reconnect marker so stop() cannot
|
||
// accidentally cancel a server run.
|
||
try {
|
||
const readerStopped = await stopRecoveredRunReader({
|
||
isCurrent: isCurrentRecovery,
|
||
clearReconnect: () => clearActiveRunId(tid),
|
||
stop: () => threadStreamRef.current?.stop(),
|
||
});
|
||
if (!readerStopped) return "unknown";
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
streamReconnectAttemptsRef.current = 0;
|
||
backgroundHistory.confirmTerminal();
|
||
void backgroundHistory.refresh(false);
|
||
return "terminal";
|
||
} catch {
|
||
if (isCurrentRecovery()) {
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
setStreamHoldOpen(true);
|
||
}
|
||
return "unknown";
|
||
}
|
||
}
|
||
|
||
// A second UI failure can pause recovery while /runs is in flight.
|
||
if (!isCurrentRecovery()) return "unknown";
|
||
persistActiveRunId(tid, runId);
|
||
setStreamHoldOpen(true);
|
||
|
||
const streamAboutToEnd = reason === "finish" || reason === "error";
|
||
if (
|
||
threadStreamRef.current?.isLoading &&
|
||
!streamAboutToEnd &&
|
||
reason !== "conflict"
|
||
) {
|
||
if (
|
||
Date.now() - lastStreamActivityAtRef.current <
|
||
STREAM_RECOVERY_LIVE_IDLE_MS
|
||
) {
|
||
return "rejoined";
|
||
}
|
||
// Local SSE reader stalled while the backend run is still alive.
|
||
// SDK stop() cancels the server run if lg:stream is set — hide it
|
||
// first, abort only the browser reader, then join the live run.
|
||
if (reason === "poll" || reason === "idle") {
|
||
if (
|
||
streamReconnectAttemptsRef.current >= STREAM_RECONNECT_MAX_ATTEMPTS
|
||
) {
|
||
if (!streamReconnectFailureToastShownRef.current) {
|
||
streamReconnectFailureToastShownRef.current = true;
|
||
reportStreamIssue(
|
||
"回答仍在后台处理中,但页面连接暂未恢复;请稍后返回此会话查看结果,或点“停止”后重新提问。",
|
||
);
|
||
}
|
||
return "rejoined";
|
||
}
|
||
streamReconnectAttemptsRef.current += 1;
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
const stream = threadStreamRef.current;
|
||
if (!stream) {
|
||
return "unknown";
|
||
}
|
||
streamReaderRecycleRunIdRef.current = runId;
|
||
runMetadataStorageRef.current?.removeItem(`lg:stream:${tid}`);
|
||
void Promise.resolve(stream.stop())
|
||
.catch(() => undefined)
|
||
.finally(() => {
|
||
if (
|
||
threadIdRef.current !== tid ||
|
||
sendEpochRef.current !== epochAtStart ||
|
||
reactUiRecoveryRef.current.isPaused(uiRecoveryKey)
|
||
) {
|
||
if (streamReaderRecycleRunIdRef.current === runId) {
|
||
streamReaderRecycleRunIdRef.current = null;
|
||
}
|
||
return;
|
||
}
|
||
persistActiveRunId(tid, runId);
|
||
const rejoin = stream.joinStream(
|
||
runId,
|
||
streamClient.getResumeCursor(tid, runId),
|
||
);
|
||
if (streamReaderRecycleRunIdRef.current === runId) {
|
||
streamReaderRecycleRunIdRef.current = null;
|
||
}
|
||
if (reason === "idle") {
|
||
// This was a watchdog recycle of an otherwise healthy run.
|
||
// Once the new reader is started, return to the 90s window
|
||
// instead of probing every 12s as exception recovery does.
|
||
setStreamHoldOpen(false);
|
||
}
|
||
void rejoin.catch(() => undefined);
|
||
});
|
||
return "rejoined";
|
||
}
|
||
}
|
||
|
||
if (reason !== "conflict") {
|
||
if (
|
||
streamReconnectAttemptsRef.current >= STREAM_RECONNECT_MAX_ATTEMPTS
|
||
) {
|
||
if (!streamReconnectFailureToastShownRef.current) {
|
||
streamReconnectFailureToastShownRef.current = true;
|
||
reportStreamIssue(
|
||
"回答仍在后台处理中,但页面连接暂未恢复;请稍后返回此会话查看结果,或点“停止”后重新提问。",
|
||
);
|
||
}
|
||
return "rejoined";
|
||
}
|
||
streamReconnectAttemptsRef.current += 1;
|
||
}
|
||
lastStreamActivityAtRef.current = Date.now();
|
||
|
||
const stream = threadStreamRef.current;
|
||
if (!stream) {
|
||
return "unknown";
|
||
}
|
||
void stream.joinStream(runId, streamClient.getResumeCursor(tid, runId)).catch(() => {
|
||
/* poll retries while the run stays non-terminal */
|
||
});
|
||
return "rejoined";
|
||
};
|
||
return runStreamRecoverySingleFlight(
|
||
streamReconciliationFlightRef.current,
|
||
reconcile,
|
||
);
|
||
},
|
||
[
|
||
isMock,
|
||
onStreamThreadId,
|
||
queryClient,
|
||
streamClient,
|
||
backgroundHistory,
|
||
reportStreamIssue,
|
||
],
|
||
);
|
||
confirmOrRejoinRef.current = confirmOrRejoin;
|
||
|
||
useEffect(() => {
|
||
const activeThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
if (!activeThreadId || typeof window === "undefined") {
|
||
return;
|
||
}
|
||
|
||
let disposed = false;
|
||
const reconcileRun = async () => {
|
||
if (disposed) return;
|
||
const isLoading = Boolean(threadStreamRef.current?.isLoading);
|
||
const idleFor = Date.now() - lastStreamActivityAtRef.current;
|
||
const hasActiveRun = Boolean(
|
||
activeRunIdRef.current ?? readActiveRunId(activeThreadId),
|
||
);
|
||
if (
|
||
!shouldReconcileRunStream({
|
||
isLoading,
|
||
idleForMs: idleFor,
|
||
recoveryHeld: streamHoldOpen,
|
||
hasActiveRun,
|
||
})
|
||
) {
|
||
return;
|
||
}
|
||
await confirmOrRejoin(streamHoldOpen ? "poll" : "idle");
|
||
};
|
||
|
||
const interval = window.setInterval(
|
||
() => void reconcileRun(),
|
||
STREAM_RECONCILIATION_POLL_MS,
|
||
);
|
||
|
||
return () => {
|
||
disposed = true;
|
||
window.clearInterval(interval);
|
||
};
|
||
}, [confirmOrRejoin, onStreamThreadId, streamHoldOpen, thread.isLoading]);
|
||
|
||
// Reset thread-local pending UI state when the caller actually switches AWAY
|
||
// from a thread (threadId becomes nullish). This is the "click 新对话 / open
|
||
// a fresh chat" signal — abort the in-flight SSE and clear optimistic state.
|
||
//
|
||
// We deliberately do NOT reset on every threadId change. During a normal
|
||
// "user just sent the first message on /chats/new" flow, useThreadStream
|
||
// sees threadId transition from undefined (the landing state) to the
|
||
// server-assigned thread id once onCreated fires. Stopping the stream and
|
||
// clearing optimistic messages in that case is exactly what made submitted
|
||
// questions visually disappear — the live run that just started would be
|
||
// aborted by the very effect intended to reset stale state.
|
||
useEffect(() => {
|
||
if (threadId != null) {
|
||
// Forward direction: starting or continuing with a real thread.
|
||
// No reset needed; the upstream useStream will load history for this id.
|
||
if (createdThreadIdRef.current !== threadId) {
|
||
// Direct navigation to an existing conversation should render its full
|
||
// history. Only a server id created from the current /chats/new
|
||
// submission inherits the previous-message boundary.
|
||
setNewConversationBoundary(null);
|
||
activeRetrievalScopeRef.current = null;
|
||
}
|
||
setThreadValueOverrides({});
|
||
return;
|
||
}
|
||
const prevThread = threadStreamRef.current;
|
||
setNewConversationBoundary(
|
||
createNewConversationDisplayBoundary(prevThread?.messages),
|
||
);
|
||
const previousRetrievalScope = activeRetrievalScopeRef.current;
|
||
if (previousRetrievalScope) {
|
||
clearKnowledgeRetrievalProgress(previousRetrievalScope.threadId);
|
||
}
|
||
activeRetrievalScopeRef.current = null;
|
||
createdThreadIdRef.current = null;
|
||
if (prevThread?.isLoading) {
|
||
try {
|
||
prevThread.stop();
|
||
} catch {
|
||
// best-effort; nothing useful to do if the SDK fails to abort
|
||
}
|
||
}
|
||
startedRef.current = false;
|
||
sendInFlightRef.current = false;
|
||
sendEpochRef.current += 1;
|
||
prevMsgCountRef.current = 0;
|
||
optimisticKnownHumanIdsRef.current = new Set();
|
||
activeRunIdRef.current = null;
|
||
setStreamHoldOpen(false);
|
||
setOptimisticMessages([]);
|
||
setIsUploading(false);
|
||
setThreadValueOverrides({});
|
||
}, [threadId]);
|
||
|
||
useEffect(() => {
|
||
const activeThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
|
||
const effectiveTitleProvisional =
|
||
(threadValueOverrides.title_provisional ??
|
||
thread.values?.title_provisional) === true;
|
||
|
||
if (!activeThreadId || thread.isLoading || !effectiveTitleProvisional) {
|
||
return;
|
||
}
|
||
|
||
let cancelled = false;
|
||
let pollCount = 0;
|
||
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
||
const controller = new AbortController();
|
||
|
||
const poll = async () => {
|
||
while (!cancelled) {
|
||
try {
|
||
const nextState = await fetchThreadTitleRefreshState(
|
||
activeThreadId,
|
||
controller.signal,
|
||
);
|
||
if (cancelled || !nextState) {
|
||
return;
|
||
}
|
||
|
||
setThreadValueOverrides((prev) => ({
|
||
...prev,
|
||
title: nextState.title,
|
||
title_provisional: nextState.title_provisional ?? true,
|
||
}));
|
||
|
||
if (nextState.title) {
|
||
updateCachedThreadLists(queryClient, (threads) =>
|
||
threads.map((t) =>
|
||
t.thread_id === activeThreadId
|
||
? {
|
||
...t,
|
||
values: {
|
||
...t.values,
|
||
title: nextState.title,
|
||
title_provisional: nextState.title_provisional ?? true,
|
||
},
|
||
}
|
||
: t,
|
||
),
|
||
);
|
||
}
|
||
|
||
if (nextState.title_provisional === false) {
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
return;
|
||
}
|
||
} catch {
|
||
return;
|
||
}
|
||
|
||
await new Promise<void>((resolve) => {
|
||
timeoutId = setTimeout(resolve, 2000);
|
||
});
|
||
pollCount += 1;
|
||
if (pollCount >= 30) {
|
||
setThreadValueOverrides((prev) => ({ ...prev, title_provisional: false }));
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
return;
|
||
}
|
||
}
|
||
};
|
||
|
||
void poll();
|
||
|
||
return () => {
|
||
cancelled = true;
|
||
controller.abort();
|
||
if (timeoutId) {
|
||
clearTimeout(timeoutId);
|
||
}
|
||
};
|
||
}, [
|
||
onStreamThreadId,
|
||
queryClient,
|
||
thread.isLoading,
|
||
thread.values?.title_provisional,
|
||
threadValueOverrides.title_provisional,
|
||
]);
|
||
|
||
// Clear optimistic only when the server echoes a *new* human message.
|
||
// After 用户协助, a late checkpoint / tool result can bump length without
|
||
// the new answer yet — clearing then makes the bubble flash and vanish.
|
||
useEffect(() => {
|
||
if (optimisticMessages.length === 0) {
|
||
return;
|
||
}
|
||
if (
|
||
hasServerEchoedOptimisticHuman(
|
||
thread.messages,
|
||
optimisticKnownHumanIdsRef.current,
|
||
)
|
||
) {
|
||
setOptimisticMessages([]);
|
||
}
|
||
}, [thread.messages, optimisticMessages.length]);
|
||
|
||
// Bind a just-sent question's ask time to the server-assigned human message
|
||
// id once it appears. Persists to localStorage so the time shows on every
|
||
// question and survives reloads, independent of the backend echoing it back.
|
||
useEffect(() => {
|
||
const pending = pendingAskTimeRef.current;
|
||
if (!pending) return;
|
||
for (const message of thread.messages) {
|
||
if (
|
||
message.type === "human" &&
|
||
message.id &&
|
||
!message.id.startsWith("opt-") &&
|
||
!pending.known.has(message.id)
|
||
) {
|
||
rememberAskTime(message.id, pending.ts);
|
||
pendingAskTimeRef.current = null;
|
||
break;
|
||
}
|
||
}
|
||
}, [thread.messages]);
|
||
|
||
const sendMessage = useCallback(
|
||
async (
|
||
threadId: string,
|
||
message: PromptInputMessage,
|
||
extraContext?: Record<string, unknown>,
|
||
options?: SendMessageOptions,
|
||
) => {
|
||
if (sendInFlightRef.current) {
|
||
return;
|
||
}
|
||
sendInFlightRef.current = true;
|
||
sendEpochRef.current += 1;
|
||
backgroundHistory.select(threadId ?? null);
|
||
backgroundHistory.beginTurn();
|
||
// Custom retrieval progress is scoped to one user turn. Tool-call
|
||
// messages remain in the checkpoint and rebuild older traces after this
|
||
// live buffer is cleared.
|
||
if (threadId) {
|
||
const retrievalScope = {
|
||
scopeId: `${threadId}:${sendEpochRef.current}:${Date.now()}`,
|
||
threadId,
|
||
runId: null,
|
||
};
|
||
activeRetrievalScopeRef.current = retrievalScope;
|
||
beginKnowledgeRetrievalProgress(threadId, retrievalScope);
|
||
}
|
||
setStreamHoldOpen(false);
|
||
|
||
const text = message.text.trim();
|
||
// Wall-clock time the question was asked. Stored on the human message so
|
||
// the chat can show "几点提问" and have it survive a reload (it round-trips
|
||
// through the checkpoint inside additional_kwargs, same as `files`).
|
||
const clientTs = new Date().toISOString();
|
||
const knownHumanIds = collectHumanMessageIds(
|
||
thread.messages,
|
||
Array.isArray(thread.values?.messages)
|
||
? (thread.values.messages as Message[])
|
||
: undefined,
|
||
);
|
||
// Remember which human messages already exist so the reconciliation
|
||
// effect can bind ``clientTs`` to the new one once the server returns it.
|
||
pendingAskTimeRef.current = {
|
||
ts: clientTs,
|
||
known: knownHumanIds,
|
||
};
|
||
optimisticKnownHumanIdsRef.current = knownHumanIds;
|
||
|
||
// Capture current count before showing optimistic messages
|
||
prevMsgCountRef.current = thread.messages.length;
|
||
|
||
// Build optimistic files list with uploading status
|
||
const optimisticFiles: FileInMessage[] = (message.files ?? []).map(
|
||
(f) => ({
|
||
filename: f.filename ?? "",
|
||
size: 0,
|
||
status: "uploading" as const,
|
||
}),
|
||
);
|
||
|
||
const hideFromUI = options?.additionalKwargs?.hide_from_ui === true;
|
||
const optimisticAdditionalKwargs = {
|
||
...options?.additionalKwargs,
|
||
client_ts: clientTs,
|
||
...(optimisticFiles.length > 0 ? { files: optimisticFiles } : {}),
|
||
};
|
||
|
||
const newOptimistic: Message[] = [];
|
||
if (!hideFromUI) {
|
||
newOptimistic.push({
|
||
type: "human",
|
||
id: `opt-human-${Date.now()}`,
|
||
content: text ? [{ type: "text", text }] : "",
|
||
additional_kwargs: optimisticAdditionalKwargs,
|
||
});
|
||
}
|
||
|
||
if (optimisticFiles.length > 0 && !hideFromUI) {
|
||
// Mock AI message while files are being uploaded
|
||
newOptimistic.push({
|
||
type: "ai",
|
||
id: `opt-ai-${Date.now()}`,
|
||
content: t.uploads.uploadingFiles,
|
||
additional_kwargs: { element: "task" },
|
||
});
|
||
}
|
||
setOptimisticMessages(newOptimistic);
|
||
|
||
// Only fire onStart immediately for an existing persisted thread.
|
||
// Brand-new chats should wait for onCreated(meta.thread_id) so URL sync
|
||
// uses the real server-generated thread id.
|
||
if (threadIdRef.current) {
|
||
_handleOnStart(threadId);
|
||
}
|
||
|
||
let uploadedFileInfo: UploadedFileInfo[] = [];
|
||
|
||
try {
|
||
// Upload files first if any
|
||
if (message.files && message.files.length > 0) {
|
||
setIsUploading(true);
|
||
try {
|
||
const filePromises = message.files.map((fileUIPart) =>
|
||
promptInputFilePartToFile(fileUIPart),
|
||
);
|
||
|
||
const conversionResults = await Promise.all(filePromises);
|
||
const files = conversionResults.filter(
|
||
(file): file is File => file !== null,
|
||
);
|
||
const failedConversions = conversionResults.length - files.length;
|
||
|
||
if (failedConversions > 0) {
|
||
throw new Error(
|
||
`Failed to prepare ${failedConversions} attachment(s) for upload. Please retry.`,
|
||
);
|
||
}
|
||
|
||
if (!threadId) {
|
||
throw new Error("Thread is not ready for file upload.");
|
||
}
|
||
|
||
if (files.length > 0) {
|
||
const uploadResponse = await uploadFiles(threadId, files);
|
||
uploadedFileInfo = uploadResponse.files;
|
||
|
||
// Update optimistic human message with uploaded status + paths
|
||
const uploadedFiles: FileInMessage[] = uploadedFileInfo.map(
|
||
(info) => ({
|
||
filename: info.filename,
|
||
size: info.size,
|
||
path: info.virtual_path,
|
||
status: "uploaded" as const,
|
||
}),
|
||
);
|
||
setOptimisticMessages((messages) => {
|
||
if (messages.length > 1 && messages[0]) {
|
||
const humanMessage: Message = messages[0];
|
||
return [
|
||
{
|
||
...humanMessage,
|
||
additional_kwargs: {
|
||
...humanMessage.additional_kwargs,
|
||
files: uploadedFiles,
|
||
},
|
||
},
|
||
...messages.slice(1),
|
||
];
|
||
}
|
||
return messages;
|
||
});
|
||
}
|
||
} catch (error) {
|
||
const errorMessage =
|
||
error instanceof Error
|
||
? error.message
|
||
: "Failed to upload files.";
|
||
toast.error(errorMessage);
|
||
setOptimisticMessages([]);
|
||
throw error;
|
||
} finally {
|
||
setIsUploading(false);
|
||
}
|
||
}
|
||
|
||
// Build files metadata for submission (included in additional_kwargs)
|
||
const filesForSubmit: FileInMessage[] = uploadedFileInfo.map(
|
||
(info) => ({
|
||
filename: info.filename,
|
||
size: info.size,
|
||
path: info.virtual_path,
|
||
status: "uploaded" as const,
|
||
}),
|
||
);
|
||
|
||
const mergedContext = withExplicitKnowledgeRetrievalMode({
|
||
...context,
|
||
...extraContext,
|
||
});
|
||
// Mode changes are part of the conversation, so persist them before an
|
||
// existing thread starts its next run. The Gateway merges this patch
|
||
// with task/project/agent metadata, and the run request repeats the
|
||
// same value as a fallback if this best-effort PATCH is interrupted.
|
||
const persistedThreadId = threadIdRef.current;
|
||
if (persistedThreadId && !isMock) {
|
||
await getAPIClient().threads
|
||
.update(persistedThreadId, {
|
||
metadata: withKnowledgeRetrievalModeMetadata(
|
||
undefined,
|
||
mergedContext.knowledge_retrieval_mode,
|
||
),
|
||
})
|
||
.catch(() => undefined);
|
||
}
|
||
const selectedLlmWikiIds = Array.isArray(
|
||
mergedContext.llmwiki_knowledge_base_ids,
|
||
)
|
||
? mergedContext.llmwiki_knowledge_base_ids
|
||
: [];
|
||
const selectedAssistantKnowledgeIds = Array.isArray(
|
||
mergedContext.assistant_knowledge_base_ids,
|
||
)
|
||
? mergedContext.assistant_knowledge_base_ids
|
||
: [];
|
||
const ragModeEnabled = resolveKnowledgeRagModeEnabled({
|
||
knowledgeRetrievalMode: mergedContext.knowledge_retrieval_mode,
|
||
referenceModeEntryEnabled,
|
||
localRagModeEnabled: localSettings.display.ragModeEnabled,
|
||
threadRagModeLocked: isThreadRagModeLocked(threadId),
|
||
ordinaryKnowledgeBaseCount: selectedLlmWikiIds.length,
|
||
assistantKnowledgeBaseCount: selectedAssistantKnowledgeIds.length,
|
||
});
|
||
if (ragModeEnabled) {
|
||
lockThreadRagMode(threadId);
|
||
}
|
||
|
||
const contextCompressionEnabled =
|
||
localSettings.display.contextCompressionEnabled ?? false;
|
||
|
||
const hiddenContextMessages = normalizeHiddenContextMessages(options);
|
||
const submittedMessages: Message[] = [
|
||
...hiddenContextMessages.map((item) => ({
|
||
type: "human" as const,
|
||
...(item.name ? { name: item.name } : {}),
|
||
content: [
|
||
{
|
||
type: "text" as const,
|
||
text: item.text,
|
||
},
|
||
],
|
||
additional_kwargs: {
|
||
...item.additionalKwargs,
|
||
hide_from_ui: true,
|
||
},
|
||
})),
|
||
{
|
||
type: "human" as const,
|
||
content: [
|
||
{
|
||
type: "text" as const,
|
||
text,
|
||
},
|
||
],
|
||
additional_kwargs: {
|
||
...options?.additionalKwargs,
|
||
client_ts: clientTs,
|
||
...(filesForSubmit.length > 0
|
||
? { files: filesForSubmit }
|
||
: {}),
|
||
},
|
||
},
|
||
];
|
||
|
||
await thread.submit(
|
||
{
|
||
messages: submittedMessages,
|
||
},
|
||
{
|
||
threadId: threadId,
|
||
// A final history refresh may still be in flight. Continue from
|
||
// the server's head, never the prior render's implicit checkpoint.
|
||
checkpoint: null,
|
||
streamSubgraphs: true,
|
||
streamResumable: true,
|
||
onDisconnect: runOptions?.onDisconnect,
|
||
multitaskStrategy: runOptions?.multitaskStrategy,
|
||
config: {
|
||
recursion_limit: 1000,
|
||
},
|
||
context: {
|
||
...mergedContext,
|
||
thinking_enabled: mergedContext.mode !== "flash",
|
||
thinking_force_disabled: mergedContext.mode === "flash",
|
||
is_plan_mode:
|
||
mergedContext.mode === "pro" || mergedContext.mode === "ultra",
|
||
subagent_enabled: mergedContext.mode === "ultra",
|
||
reasoning_effort: reasoningEffortForRun(
|
||
mergedContext.mode,
|
||
mergedContext.reasoning_effort,
|
||
),
|
||
rag_mode_enabled: ragModeEnabled,
|
||
summarization_enabled: contextCompressionEnabled,
|
||
thread_id: threadId,
|
||
},
|
||
},
|
||
);
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
} catch (error) {
|
||
const message = getStreamErrorMessage(error);
|
||
// The SDK rejects submit after invoking onError. Without handling the
|
||
// same internal React exception here, callers using `void sendMessage`
|
||
// create an unhandled rejection while callers with a catch render #185
|
||
// inline. Keep the backend run alive and let the recovery path rejoin.
|
||
if (isReactMaximumUpdateDepthError(error)) {
|
||
handleReactUiStreamError(error, "submit_rejection");
|
||
return;
|
||
}
|
||
const friendly = friendlySendLimitMessage(message);
|
||
if (friendly) {
|
||
setIsUploading(false);
|
||
if (isActiveRunConflictError(message)) {
|
||
setOptimisticMessages([]);
|
||
setStreamHoldOpen(true);
|
||
const result = await confirmOrRejoin("conflict");
|
||
reportStreamIssue(
|
||
result === "rejoined"
|
||
? "上一轮回答仍在生成,已重新连接当前回复。请等待结束或点“停止”后再提问。"
|
||
: friendly,
|
||
"info",
|
||
);
|
||
return;
|
||
}
|
||
setOptimisticMessages((messages) => {
|
||
const human = messages.find((item) => item.type === "human");
|
||
const kept = human ? [human] : [];
|
||
return [
|
||
...kept,
|
||
{
|
||
type: "ai",
|
||
id: `opt-ai-limit-${Date.now()}`,
|
||
content: friendly,
|
||
additional_kwargs: { element: "task" },
|
||
} as Message,
|
||
];
|
||
});
|
||
return;
|
||
}
|
||
setOptimisticMessages([]);
|
||
setIsUploading(false);
|
||
throw error;
|
||
} finally {
|
||
sendInFlightRef.current = false;
|
||
}
|
||
},
|
||
[
|
||
thread,
|
||
_handleOnStart,
|
||
t.uploads.uploadingFiles,
|
||
context,
|
||
referenceModeEntryEnabled,
|
||
isMock,
|
||
localSettings.display.ragModeEnabled,
|
||
queryClient,
|
||
runOptions,
|
||
backgroundHistory,
|
||
confirmOrRejoin,
|
||
reportStreamIssue,
|
||
],
|
||
);
|
||
|
||
const handleThreadStop = useCallback(async () => {
|
||
const tid = threadIdRef.current;
|
||
const runId =
|
||
activeRunIdRef.current ?? (tid ? readActiveRunId(tid) : null);
|
||
setStreamHoldOpen(false);
|
||
activeRunIdRef.current = null;
|
||
if (tid) {
|
||
// 用户显式停止:深度研究报告流立即定格为中断。
|
||
finalizeResearchReportStream(tid);
|
||
if (runId) persistActiveRunId(tid, runId);
|
||
}
|
||
try {
|
||
await Promise.resolve(threadStreamRef.current?.stop());
|
||
} catch {
|
||
/* local abort is best-effort */
|
||
}
|
||
backgroundHistory.cancel();
|
||
if (tid && runId) {
|
||
try {
|
||
await getAPIClient(isMock).runs.cancel(tid, runId);
|
||
} catch {
|
||
/* already stopped / missing */
|
||
}
|
||
clearActiveRunId(tid);
|
||
}
|
||
}, [isMock, backgroundHistory]);
|
||
|
||
// Merge thread with optimistic messages for display. While a live SSE is
|
||
// open, never let a stale getState snapshot's `messages` win — that is what
|
||
// made 协助卡提交后「发送中」攒到结束才一口气出字。
|
||
const mergedValues =
|
||
mergeStreamDisplayValues(
|
||
thread.values as AgentThreadState | undefined,
|
||
threadValueOverrides,
|
||
thread.isLoading,
|
||
) ?? thread.values;
|
||
|
||
const unisolatedMergedMessages =
|
||
Array.isArray(mergedValues?.messages)
|
||
? (mergedValues.messages as Message[])
|
||
: thread.messages;
|
||
const mergedMessages = isolateNewConversationMessages(
|
||
unisolatedMergedMessages,
|
||
newConversationBoundary,
|
||
);
|
||
const displayMergedValues =
|
||
mergedValues && Array.isArray(mergedValues.messages)
|
||
? ({ ...mergedValues, messages: mergedMessages } as AgentThreadState)
|
||
: mergedValues;
|
||
|
||
const visibleThreadError =
|
||
thread.error &&
|
||
isReactMaximumUpdateDepthError(thread.error)
|
||
? undefined
|
||
: thread.error;
|
||
|
||
const mergedThread = {
|
||
...thread,
|
||
error: visibleThreadError,
|
||
values: displayMergedValues,
|
||
messages:
|
||
optimisticMessages.length > 0
|
||
? [...mergedMessages, ...optimisticMessages]
|
||
: mergedMessages,
|
||
isLoading: thread.isLoading || streamHoldOpen,
|
||
isStateSyncing: historyView.isRefreshing,
|
||
stop: handleThreadStop,
|
||
} as typeof thread & { isStateSyncing: boolean };
|
||
|
||
// 第 4 个返回值 `onStreamThreadId` = 底层 useStream 当前实际绑定的线程 id(新建/未保存时为 null)。
|
||
// 调用方据此判断「流是否已切到全新线程」,避免在切换会话的那一帧把消息发进上一个会话
|
||
// (submit 的 threadId 选项仅在 hook 线程为 null/undefined 时才生效)。
|
||
return [mergedThread, sendMessage, isUploading, onStreamThreadId] as const;
|
||
}
|
||
|
||
export function useThreads(
|
||
params: Parameters<ThreadsClient["search"]>[0] = {
|
||
limit: 50,
|
||
sortBy: "updated_at",
|
||
sortOrder: "desc",
|
||
select: ["thread_id", "updated_at", "values", "metadata"],
|
||
},
|
||
) {
|
||
const apiClient = getAPIClient();
|
||
return useQuery<AgentThread[]>({
|
||
queryKey: ["threads", "search", params],
|
||
queryFn: async () => {
|
||
const maxResults = params.limit;
|
||
const initialOffset = params.offset ?? 0;
|
||
const DEFAULT_PAGE_SIZE = 50;
|
||
|
||
// Preserve prior semantics: if a non-positive limit is explicitly provided,
|
||
// delegate to a single search call with the original parameters.
|
||
if (maxResults !== undefined && maxResults <= 0) {
|
||
const response =
|
||
await apiClient.threads.search<AgentThreadState>(params);
|
||
return response as AgentThread[];
|
||
}
|
||
|
||
const pageSize =
|
||
typeof maxResults === "number" && maxResults > 0
|
||
? Math.min(DEFAULT_PAGE_SIZE, maxResults)
|
||
: DEFAULT_PAGE_SIZE;
|
||
|
||
const threads: AgentThread[] = [];
|
||
let offset = initialOffset;
|
||
|
||
while (true) {
|
||
if (typeof maxResults === "number" && threads.length >= maxResults) {
|
||
break;
|
||
}
|
||
|
||
const currentLimit =
|
||
typeof maxResults === "number"
|
||
? Math.min(pageSize, maxResults - threads.length)
|
||
: pageSize;
|
||
|
||
if (typeof maxResults === "number" && currentLimit <= 0) {
|
||
break;
|
||
}
|
||
|
||
const response = (await apiClient.threads.search<AgentThreadState>({
|
||
...params,
|
||
limit: currentLimit,
|
||
offset,
|
||
})) as AgentThread[];
|
||
|
||
threads.push(...response);
|
||
|
||
if (response.length < currentLimit) {
|
||
break;
|
||
}
|
||
|
||
offset += response.length;
|
||
}
|
||
|
||
// Safety net on top of the backend's system-thread exclusion: drop
|
||
// machine-created / wizard threads (scheduled tasks, report-structure
|
||
// setup, writing setup, notebooks, …) in case an older backend still
|
||
// returns them.
|
||
return threads.filter((t) => !isHiddenFromRecentChats(t));
|
||
},
|
||
refetchOnWindowFocus: false,
|
||
});
|
||
}
|
||
|
||
export interface ThreadsPageResult {
|
||
threads: AgentThread[];
|
||
hasMore: boolean;
|
||
}
|
||
|
||
/**
|
||
* Apply ``transform`` to the thread array inside every cached
|
||
* ``["threads", "search"]`` entry. The sidebar queries cache a plain
|
||
* ``AgentThread[]`` while the paged chats list (`useThreadsPage`) caches a
|
||
* ``ThreadsPageResult`` object under the same key prefix, so fuzzy
|
||
* ``setQueriesData`` updaters must handle both shapes.
|
||
*/
|
||
function updateCachedThreadLists(
|
||
queryClient: QueryClient,
|
||
transform: (threads: AgentThread[]) => AgentThread[],
|
||
) {
|
||
queryClient.setQueriesData<AgentThread[] | ThreadsPageResult | undefined>(
|
||
{ queryKey: ["threads", "search"], exact: false },
|
||
(oldData) => {
|
||
if (Array.isArray(oldData)) {
|
||
return transform(oldData);
|
||
}
|
||
if (oldData && Array.isArray(oldData.threads)) {
|
||
return { ...oldData, threads: transform(oldData.threads) };
|
||
}
|
||
return oldData;
|
||
},
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Server-side paginated conversation list for the chats page. Unlike
|
||
* `useThreads` (which loads a bounded recent window for the sidebar), this
|
||
* fetches exactly one page per request so a long history is never pulled in
|
||
* one go. `search` matches thread titles on the backend; one extra row is
|
||
* over-fetched only to detect whether a next page exists. The query key stays
|
||
* under ["threads", "search"] so existing invalidations refresh pages too.
|
||
*/
|
||
export function useThreadsPage(options: {
|
||
page: number;
|
||
pageSize: number;
|
||
search?: string;
|
||
metadata?: Record<string, unknown>;
|
||
}) {
|
||
const { page, pageSize, search, metadata } = options;
|
||
const normalizedSearch = search?.trim() ?? "";
|
||
return useQuery<ThreadsPageResult>({
|
||
queryKey: [
|
||
"threads",
|
||
"search",
|
||
"paged",
|
||
page,
|
||
pageSize,
|
||
normalizedSearch,
|
||
metadata ?? null,
|
||
],
|
||
queryFn: async () => {
|
||
// Direct fetch instead of the LangGraph SDK: the SDK's threads.search
|
||
// drops fields it doesn't know about, and `query` (title search) is a
|
||
// gateway extension.
|
||
const response = await apiFetch(
|
||
`${getLangGraphBaseURL()}/threads/search`,
|
||
{
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
limit: pageSize + 1,
|
||
offset: (page - 1) * pageSize,
|
||
metadata: metadata ?? {},
|
||
query: normalizedSearch || undefined,
|
||
}),
|
||
},
|
||
);
|
||
if (!response.ok) {
|
||
throw new Error("Failed to load conversations");
|
||
}
|
||
const rows = (await response.json()) as AgentThread[];
|
||
// 与后端 exclude_system 对齐:普通列表再兜一层。调用方显式按
|
||
// thread_type / system 取数(笔记本等)时不滤,避免把目标会话藏掉。
|
||
const visible = shouldHideSystemThreadsFromList(metadata)
|
||
? rows.filter((thread) => !isHiddenFromRecentChats(thread))
|
||
: rows;
|
||
return {
|
||
threads: visible.slice(0, pageSize),
|
||
hasMore: rows.length > pageSize,
|
||
};
|
||
},
|
||
placeholderData: (previous) => previous,
|
||
refetchOnWindowFocus: false,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Total number of conversations matching the same filters as
|
||
* `useThreadsPage`, via the lightweight `/threads/count` endpoint — powers
|
||
* the "共 N 条 / X 页" display without fetching any rows. Depends only on the
|
||
* filters (not the page), so paging doesn't refire it.
|
||
*/
|
||
export function useThreadsCount(options: {
|
||
search?: string;
|
||
metadata?: Record<string, unknown>;
|
||
}) {
|
||
const normalizedSearch = options.search?.trim() ?? "";
|
||
return useQuery<number>({
|
||
queryKey: [
|
||
"threads",
|
||
"search",
|
||
"count",
|
||
normalizedSearch,
|
||
options.metadata ?? null,
|
||
],
|
||
queryFn: async () => {
|
||
const response = await apiFetch(
|
||
`${getLangGraphBaseURL()}/threads/count`,
|
||
{
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
metadata: options.metadata ?? {},
|
||
query: normalizedSearch || undefined,
|
||
}),
|
||
},
|
||
);
|
||
if (!response.ok) {
|
||
throw new Error("Failed to count conversations");
|
||
}
|
||
const data = (await response.json()) as { total: number };
|
||
return data.total;
|
||
},
|
||
refetchOnWindowFocus: false,
|
||
});
|
||
}
|
||
|
||
async function deleteThreadEverywhere(
|
||
apiClient: ReturnType<typeof getAPIClient>,
|
||
threadId: string,
|
||
) {
|
||
await apiClient.threads.delete(threadId);
|
||
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(threadId)}`,
|
||
{
|
||
method: "DELETE",
|
||
},
|
||
);
|
||
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "Failed to delete local thread data." }));
|
||
throw new Error(error.detail ?? "Failed to delete local thread data.");
|
||
}
|
||
}
|
||
|
||
export function useDeleteThread() {
|
||
const queryClient = useQueryClient();
|
||
const apiClient = getAPIClient();
|
||
return useMutation({
|
||
mutationFn: async ({ threadId }: { threadId: string }) => {
|
||
await deleteThreadEverywhere(apiClient, threadId);
|
||
},
|
||
onSuccess(_, { threadId }) {
|
||
updateCachedThreadLists(queryClient, (threads) =>
|
||
threads.filter((t) => t.thread_id !== threadId),
|
||
);
|
||
},
|
||
onSettled() {
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Delete every conversation owned by the current account, including ordinary
|
||
* Q&A and each agent's chat history. Both live in the same user-scoped thread
|
||
* list; system workers (roundtable, scheduler, notebooks) stay out of it.
|
||
*/
|
||
export function useClearUserChatThreads() {
|
||
const queryClient = useQueryClient();
|
||
return useMutation({
|
||
mutationFn: async () => {
|
||
const response = await apiFetch(`${getBackendBaseURL()}/api/threads/clear`, {
|
||
method: "POST",
|
||
});
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "清空聊天记录失败" }));
|
||
const detail = error.detail;
|
||
throw new Error(typeof detail === "string" ? detail : "清空聊天记录失败");
|
||
}
|
||
return (await response.json()) as { deleted: number };
|
||
},
|
||
onSuccess(result) {
|
||
if (result.deleted > 0) {
|
||
updateCachedThreadLists(queryClient, () => []);
|
||
}
|
||
},
|
||
onSettled() {
|
||
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Delete a conversation turn (a user question together with its answer) from a
|
||
* thread. Hits the Gateway endpoint that removes the question and every
|
||
* following message up to the next question from the latest checkpoint, and
|
||
* returns the ids that were actually removed. The live `useStream` cache is not
|
||
* auto-refreshed by this call — callers hide the returned ids locally (see
|
||
* `MessageList`) so the removal shows immediately; a reload then reads the
|
||
* persisted, already-trimmed state.
|
||
*/
|
||
export function useDeleteMessage() {
|
||
return useMutation({
|
||
mutationFn: async ({
|
||
threadId,
|
||
messageId,
|
||
}: {
|
||
threadId: string;
|
||
messageId: string;
|
||
}): Promise<string[]> => {
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||
threadId,
|
||
)}/messages/${encodeURIComponent(messageId)}`,
|
||
{
|
||
method: "DELETE",
|
||
},
|
||
);
|
||
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "删除消息失败。" }));
|
||
throw new Error(error.detail ?? "删除消息失败。");
|
||
}
|
||
|
||
const body = (await response.json().catch(() => ({}))) as {
|
||
deleted_ids?: string[];
|
||
};
|
||
// Fall back to the requested id so the caller can always hide something.
|
||
return body.deleted_ids?.length ? body.deleted_ids : [messageId];
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Clear all messages from a thread checkpoint. The caller should immediately
|
||
* hide the returned ids locally because the active stream cache may still hold
|
||
* the old message objects until a reload/refetch reads the trimmed checkpoint.
|
||
*/
|
||
export function useClearThreadMessages() {
|
||
return useMutation({
|
||
mutationFn: async ({
|
||
threadId,
|
||
}: {
|
||
threadId: string;
|
||
}): Promise<string[]> => {
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||
threadId,
|
||
)}/messages`,
|
||
{
|
||
method: "DELETE",
|
||
},
|
||
);
|
||
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "清空对话失败。" }));
|
||
throw new Error(error.detail ?? "清空对话失败。");
|
||
}
|
||
|
||
const body = (await response.json().catch(() => ({}))) as {
|
||
deleted_ids?: string[];
|
||
};
|
||
return body.deleted_ids ?? [];
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Persist an in-place message edit in the latest thread checkpoint.
|
||
*
|
||
* This is opt-in UI behaviour: most chat pages keep their existing
|
||
* "edit question and resubmit" affordance, while position roundtable can pass
|
||
* this mutation down to save the original message content itself.
|
||
*/
|
||
export function useEditMessage() {
|
||
return useMutation({
|
||
mutationFn: async ({
|
||
threadId,
|
||
messageId,
|
||
content,
|
||
}: {
|
||
threadId: string;
|
||
messageId: string;
|
||
content: string;
|
||
}): Promise<Message> => {
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(
|
||
threadId,
|
||
)}/messages/${encodeURIComponent(messageId)}`,
|
||
{
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ content }),
|
||
},
|
||
);
|
||
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "消息保存失败。" }));
|
||
throw new Error(error.detail ?? "消息保存失败。");
|
||
}
|
||
|
||
const body = (await response.json().catch(() => ({}))) as {
|
||
message?: Message;
|
||
};
|
||
return body.message ?? ({ id: messageId, type: "human", content } as Message);
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Merge metadata into a conversation's record via the Gateway
|
||
* `PATCH /api/threads/{id}` route. Used to persist per-conversation flags such
|
||
* as `is_pinned` (置顶) and `is_favorite` (收藏) — a conversation belongs to a
|
||
* single user, so these live directly on the thread metadata (no join table).
|
||
* Updates the `["threads", "search"]` cache optimistically so the UI reflects
|
||
* the toggle immediately, mirroring `useRenameThread`.
|
||
*/
|
||
export function useUpdateThreadMetadata() {
|
||
const queryClient = useQueryClient();
|
||
return useMutation({
|
||
mutationFn: async ({
|
||
threadId,
|
||
metadata,
|
||
}: {
|
||
threadId: string;
|
||
metadata: Record<string, unknown>;
|
||
}) => {
|
||
const response = await apiFetch(
|
||
`${getBackendBaseURL()}/api/threads/${encodeURIComponent(threadId)}`,
|
||
{
|
||
method: "PATCH",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ metadata }),
|
||
},
|
||
);
|
||
if (!response.ok) {
|
||
const error = await response
|
||
.json()
|
||
.catch(() => ({ detail: "更新对话失败。" }));
|
||
throw new Error(error.detail ?? "更新对话失败。");
|
||
}
|
||
},
|
||
onSuccess(_, { threadId, metadata }) {
|
||
updateCachedThreadLists(queryClient, (threads) =>
|
||
threads.map((t) =>
|
||
t.thread_id === threadId
|
||
? {
|
||
...t,
|
||
metadata: {
|
||
...(t.metadata as Record<string, unknown> | null),
|
||
...metadata,
|
||
},
|
||
}
|
||
: t,
|
||
),
|
||
);
|
||
},
|
||
});
|
||
}
|
||
|
||
/** Toggle a conversation's pinned (置顶) flag. */
|
||
export function useToggleThreadPin() {
|
||
const { mutate, ...rest } = useUpdateThreadMetadata();
|
||
return {
|
||
...rest,
|
||
toggle: (threadId: string, pinned: boolean) =>
|
||
mutate({ threadId, metadata: { is_pinned: pinned } }),
|
||
};
|
||
}
|
||
|
||
/** Toggle a conversation's favorite (收藏) flag. */
|
||
export function useToggleThreadFavorite() {
|
||
const { mutate, ...rest } = useUpdateThreadMetadata();
|
||
return {
|
||
...rest,
|
||
toggle: (threadId: string, favorite: boolean) =>
|
||
mutate({ threadId, metadata: { is_favorite: favorite } }),
|
||
};
|
||
}
|
||
|
||
export function useRenameThread() {
|
||
const queryClient = useQueryClient();
|
||
const apiClient = getAPIClient();
|
||
return useMutation({
|
||
mutationFn: async ({
|
||
threadId,
|
||
title,
|
||
}: {
|
||
threadId: string;
|
||
title: string;
|
||
}) => {
|
||
await apiClient.threads.updateState(threadId, {
|
||
values: { title, title_provisional: false },
|
||
});
|
||
},
|
||
onSuccess(_, { threadId, title }) {
|
||
updateCachedThreadLists(queryClient, (threads) =>
|
||
threads.map((t) =>
|
||
t.thread_id === threadId
|
||
? {
|
||
...t,
|
||
values: {
|
||
...t.values,
|
||
title,
|
||
title_provisional: false,
|
||
},
|
||
}
|
||
: t,
|
||
),
|
||
);
|
||
},
|
||
});
|
||
}
|