sync update from LAN repo (source dhk-1 @ 3e87be55)

This commit is contained in:
gozeros committed 2026-10-21 15:06:08 +08:00
1 parent ab6068a7c1
commit 42f2a26fa8
1482 files changed
+227759 -9584

No files matched your search

+363 -187
View File
@@ -3,32 +3,34 @@ 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, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "sonner";
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
import { getAPIClient } from "../api";
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 type { FileInMessage } from "../messages/utils";
import type { LocalSettings } from "../settings";
import {
isThreadRagModeLocked,
lockThreadRagMode,
useLocalSettings,
} from "../settings";
import { useCitationDisplaySettings } from "../system-settings/hooks";
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 { STREAM_RENDER_BATCHING } from "./stream-batching";
import { createReactStreamRecoveryBudget, reportReactUiError } from "./react-ui-error";
import {
finalizeResearchReportStream,
ingestResearchReportEvent,
@@ -41,7 +43,19 @@ import {
shouldDiscardTerminalOverlay,
} from "./stream-display";
import {
STREAM_RECOVERY_LIVE_IDLE_MS,
runStreamRecoverySingleFlight,
stopRecoveredRunReader,
shouldReconcileRunStream,
shouldIgnoreReaderRecycleFinish,
shouldVerifyCleanStreamFinish,
type StreamRecoveryResult,
type StreamRecoverySingleFlight,
} from "./stream-recovery";
import {
getStreamErrorMessage,
isAbortLikeError,
isReactMaximumUpdateDepthError,
isTransientStreamTransportError,
} from "./thread-access-error";
import { isHiddenFromRecentChats, shouldHideSystemThreadsFromList } from "./utils";
@@ -69,7 +83,7 @@ export type ThreadStreamOptions = {
multitaskStrategy?: "reject" | "rollback" | "interrupt" | "enqueue";
};
/** 额外写到新建 thread 的 metadata(与 agent_id 合并)。
* 任务深链用 `{ taskId }` 把对话挂到任务下(1:N),列表按 metadata.taskId 过滤。 */
* 任务深链会写 taskId + taskRecordId + taskGoPath,供专用历史索引登记。 */
threadMetadata?: Record<string, unknown>;
onStart?: (threadId: string) => void;
onFinish?: (state: AgentThreadState) => void;
@@ -306,42 +320,6 @@ export async function stopActiveThreadBeforeClarificationReply(
await new Promise((resolve) => setTimeout(resolve, 120));
}
function getStreamErrorMessage(error: unknown): string {
if (typeof error === "string" && error.trim()) {
return error;
}
if (error instanceof Error && error.message.trim()) {
return error.message;
}
if (typeof error === "object" && error !== null) {
const message = Reflect.get(error, "message");
if (typeof message === "string" && message.trim()) {
return message;
}
const nestedError = Reflect.get(error, "error");
if (nestedError instanceof Error && nestedError.message.trim()) {
return nestedError.message;
}
if (typeof nestedError === "string" && nestedError.trim()) {
return nestedError;
}
}
return "Request failed.";
}
/**
* React production error #185 is the minified form of "Maximum update depth
* exceeded". It is a client render-loop guard, not a backend/model failure,
* so it must never be surfaced as the answer's stream error.
*/
function isReactMaximumUpdateDepthError(message: string): boolean {
return (
/maximum update depth exceeded/i.test(message) ||
/minified react error\s*#185\b/i.test(message) ||
/react\.dev\/errors\/185\b/i.test(message)
);
}
const TERMINAL_RUN_STATUSES = new Set([
"success",
"error",
@@ -349,15 +327,10 @@ const TERMINAL_RUN_STATUSES = new Set([
"interrupted",
]);
// Only probe /runs after an *exception* path has already set streamHoldOpen
// (dropped SSE, 409, React #185). Normal Q&A must not GET /runs on finish or
// every 5s — that made every send wait for a status round-trip.
const STREAM_RECONCILIATION_IDLE_MS = 12_000;
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_IDLE_MS = 90_000;
const STREAM_RECONNECT_MAX_ATTEMPTS = 3;
async function fetchThreadTitleRefreshState(
@@ -571,39 +544,47 @@ export function useThreadStream({
onToolStart,
onToolEnd,
}: ThreadStreamOptions) {
const { t } = useI18n();
const [localSettings] = useLocalSettings();
const { data: citationDisplay } = useCitationDisplaySettings();
const referenceModeEntryEnabled =
citationDisplay?.reference_mode_enabled ?? false;
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 streamReconciliationInFlightRef = useRef(false);
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" | "conflict") => Promise<
"terminal" | "rejoined" | "unknown"
>
(
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 reactUiRecoveryRef = useRef(createReactStreamRecoveryBudget());
// Filled after useStream; onFinish/onError may read it asynchronously.
const threadStreamRef = useRef<{
isLoading: boolean;
stop: () => void | Promise<void>;
joinStream: (runId: string) => Promise<unknown>;
joinStream: (runId: string, lastEventId?: string) => Promise<unknown>;
messages: Message[];
values?: AgentThreadState;
} | null>(null);
@@ -628,6 +609,10 @@ export function useThreadStream({
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;
@@ -636,7 +621,7 @@ export function useThreadStream({
setOnStreamThreadId(normalizedThreadId);
}
threadIdRef.current = normalizedThreadId;
}, [threadId]);
}, [threadId, streamClient]);
const _handleOnStart = useCallback((id: string) => {
if (!startedRef.current) {
@@ -668,21 +653,53 @@ export function useThreadStream({
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: getAPIClient(isMock),
client: streamClient.client,
assistantId: assistantId ?? "lead_agent",
threadId: onStreamThreadId,
// The SDK's current implementation falls back to synchronous external-
// store notifications when this option is omitted. A network chunk can
// contain dozens of token events, causing nested React renders and the
// intermittent production-only React #185 error. Coalesce notifications
// to one visual update per frame; stream data itself is not dropped.
throttle: 16,
// Batch asynchronously; a numeric delay can hide fast continuous streams.
throttle: STREAM_RENDER_BATCHING,
reconnectOnMount: runMetadataStorageRef.current
? () => runMetadataStorageRef.current!
: false,
fetchStateHistory: { limit: 1 },
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;
handleStreamStart(meta.thread_id);
setOnStreamThreadId(meta.thread_id);
if (meta.run_id) {
@@ -699,6 +716,16 @@ export function useThreadStream({
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(() => ({}));
}
},
@@ -826,34 +853,27 @@ export function useThreadStream({
return;
}
// Context compression about to run a (blocking) summarization LLM call —
// surface a transient hint so the wait before the answer streams isn't a
// silent dead air. Emitted by DeerFlowSummarizationMiddleware.
// Background compaction stays silent, including events from older backends.
if (
typeof event === "object" &&
event !== null &&
"type" in event &&
event.type === "context_compacting" &&
"message" in event &&
typeof event.message === "string" &&
event.message.trim()
event.type === "context_compacting"
) {
const e = event as { type: "context_compacting"; message: string };
toast(e.message);
return;
}
},
onError(error) {
markStreamActivity();
// 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(message)) {
window.setTimeout(() => {
setStreamHoldOpen(true);
void confirmOrRejoinRef.current("error");
}, 0);
if (isReactMaximumUpdateDepthError(error)) {
handleReactUiStreamError(error, "stream_on_error");
return;
}
// Replacing a stalled local SSE reader aborts the in-flight fetch. That
@@ -887,6 +907,19 @@ export function useThreadStream({
// 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";
toast.info("当前项目对话不存在或无权访问,已返回我的项目。");
navigate(`/page/strategy/qa/projects?type=${category}`, { replace: true });
return;
}
const userLabel = buildCurrentUserLabel();
toast.info(
`当前登录用户为 ${userLabel},原对话不存在或无权访问,已为你打开新对话。`,
@@ -925,29 +958,67 @@ export function useThreadStream({
toast.error(message);
},
onFinish(state, runMeta) {
lastStreamActivityAtRef.current = Date.now();
// Trust a clean SSE close. Querying /runs here blocked every send for
// ~5s to paper over a rare premature disconnect; that case is handled
// when the next send hits 409 (or onError for a dropped stream).
const finishingRunId = runMeta?.run_id;
if (
isStaleStreamFinish({
finishingRunId: runMeta?.run_id,
currentRunId: activeRunIdRef.current,
shouldIgnoreReaderRecycleFinish({
recyclingRunId: streamReaderRecycleRunIdRef.current,
finishingRunId,
})
) {
return;
}
const finThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
if (finThreadId) {
clearActiveRunId(finThreadId);
finalizeResearchReportStream(finThreadId);
const idleForMs =
lastStreamActivityAtRef.current > 0
? Date.now() - lastStreamActivityAtRef.current
: 0;
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);
if (state?.values) {
listeners.current.onFinish?.(state.values);
}
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
};
if (
shouldVerifyCleanStreamFinish({
idleForMs,
hasActiveRun: Boolean(
activeRunIdRef.current &&
(!finishingRunId || activeRunIdRef.current === finishingRunId),
),
})
) {
// A clean EOF after a long business-frame silence can be a proxy that
// closed the socket while the resumable backend run is still alive.
// Verify this rare case; ordinary successful turns still finish with
// no extra /runs request.
setStreamHoldOpen(true);
void confirmOrRejoinRef
.current("finish")
.then((result) => {
if (result === "unknown") finalizeCleanStream();
})
.catch(finalizeCleanStream);
return;
}
activeRunIdRef.current = null;
setStreamHoldOpen(false);
if (state?.values) {
listeners.current.onFinish?.(state.values);
}
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
finalizeCleanStream();
},
});
@@ -972,22 +1043,37 @@ export function useThreadStream({
threadStreamRef.current = thread;
const confirmOrRejoin = useCallback(
async (
reason: "finish" | "error" | "poll" | "conflict",
): Promise<"terminal" | "rejoined" | "unknown"> => {
const tid = threadIdRef.current ?? onStreamThreadId ?? null;
if (!tid) {
setStreamHoldOpen(false);
return "unknown";
}
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]);
if (streamReconciliationInFlightRef.current && reason === "poll") {
return "unknown";
}
streamReconciliationInFlightRef.current = true;
const epochAtStart = sendEpochRef.current;
try {
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;
@@ -995,17 +1081,26 @@ export function useThreadStream({
const applyTerminalState = async (status: string) => {
const finalState = await client.threads.getState(tid);
if (
!isCurrentRecovery() ||
shouldDiscardTerminalOverlay({
epochAtStart,
currentEpoch: sendEpochRef.current,
sendInFlight: sendInFlightRef.current,
terminalRunId,
currentRunId: activeRunIdRef.current,
})
) {
return;
return false;
}
clearActiveRunId(tid);
// 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;
@@ -1013,38 +1108,79 @@ export function useThreadStream({
setThreadValueOverrides(
finalState.values as Partial<AgentThreadState>,
);
finalizeResearchReportStream(tid);
if (status === "success") {
setOptimisticMessages([]);
if (reason !== "finish") {
listeners.current.onFinish?.(
finalState.values as AgentThreadState,
);
void queryClient.invalidateQueries({
queryKey: ["threads", "search"],
});
}
} else if (reason !== "finish") {
listeners.current.onFinish?.(
finalState.values as AgentThreadState,
);
void queryClient.invalidateQueries({
queryKey: ["threads", "search"],
});
} else {
toast.error(
"本轮生成未能完成,已同步当前对话内容,可重新发起请求。",
);
}
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)) {
await applyTerminalState(run.status);
return "terminal";
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 {
// A failed checkpoint fetch does not erase the known terminal
// run. Keep recovery alive so the next probe can sync its result.
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),
);
@@ -1053,7 +1189,13 @@ export function useThreadStream({
activeRunIdRef.current = runId;
}
} catch {
runId = null;
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";
}
}
@@ -1063,6 +1205,8 @@ export function useThreadStream({
return "unknown";
}
// A second UI failure can pause recovery while /runs is in flight.
if (!isCurrentRecovery()) return "unknown";
persistActiveRunId(tid, runId);
setStreamHoldOpen(true);
@@ -1074,14 +1218,14 @@ export function useThreadStream({
) {
if (
Date.now() - lastStreamActivityAtRef.current <
STREAM_RECONNECT_IDLE_MS
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") {
if (reason === "poll" || reason === "idle") {
if (
streamReconnectAttemptsRef.current >= STREAM_RECONNECT_MAX_ATTEMPTS
) {
@@ -1099,13 +1243,36 @@ export function useThreadStream({
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) return;
if (
threadIdRef.current !== tid ||
sendEpochRef.current !== epochAtStart ||
reactUiRecoveryRef.current.isPaused(uiRecoveryKey)
) {
if (streamReaderRecycleRunIdRef.current === runId) {
streamReaderRecycleRunIdRef.current = null;
}
return;
}
persistActiveRunId(tid, runId);
void stream.joinStream(runId).catch(() => undefined);
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";
}
@@ -1131,15 +1298,17 @@ export function useThreadStream({
if (!stream) {
return "unknown";
}
void stream.joinStream(runId).catch(() => {
void stream.joinStream(runId, streamClient.getResumeCursor(tid, runId)).catch(() => {
/* poll retries while the run stays non-terminal */
});
return "rejoined";
} finally {
streamReconciliationInFlightRef.current = false;
}
};
return runStreamRecoverySingleFlight(
streamReconciliationFlightRef.current,
reconcile,
);
},
[isMock, onStreamThreadId, queryClient],
[isMock, onStreamThreadId, queryClient, streamClient],
);
confirmOrRejoinRef.current = confirmOrRejoin;
@@ -1152,21 +1321,22 @@ export function useThreadStream({
let disposed = false;
const reconcileRun = async () => {
if (disposed) return;
const dropped = !threadStreamRef.current?.isLoading;
const isLoading = Boolean(threadStreamRef.current?.isLoading);
const idleFor = Date.now() - lastStreamActivityAtRef.current;
if (!dropped && idleFor < STREAM_RECONCILIATION_IDLE_MS) {
const hasActiveRun = Boolean(
activeRunIdRef.current ?? readActiveRunId(activeThreadId),
);
if (
!shouldReconcileRunStream({
isLoading,
idleForMs: idleFor,
recoveryHeld: streamHoldOpen,
hasActiveRun,
})
) {
return;
}
if (dropped && idleFor < 800) {
return;
}
// Do not probe just because a run id is stored. Only the exception
// path sets streamHoldOpen; polling otherwise made every turn wait
// on GET /runs before the user could send again.
if (!streamHoldOpen) {
return;
}
await confirmOrRejoin("poll");
await confirmOrRejoin(streamHoldOpen ? "poll" : "idle");
};
const interval = window.setInterval(
@@ -1507,21 +1677,21 @@ export function useThreadStream({
...context,
...extraContext,
};
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 =
(referenceModeEntryEnabled && localSettings.display.ragModeEnabled) ||
isThreadRagModeLocked(threadId) ||
selectedLlmWikiIds.length > 0 ||
selectedAssistantKnowledgeIds.length > 0;
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 =
(referenceModeEntryEnabled && localSettings.display.ragModeEnabled) ||
isThreadRagModeLocked(threadId) ||
selectedLlmWikiIds.length > 0 ||
selectedAssistantKnowledgeIds.length > 0;
if (ragModeEnabled) {
lockThreadRagMode(threadId);
}
@@ -1579,6 +1749,7 @@ export function useThreadStream({
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",
@@ -1591,8 +1762,6 @@ export function useThreadStream({
: mergedContext.mode === "thinking"
? "low"
: undefined),
memory_injection_enabled:
mergedContext.memory_injection_enabled ?? true,
rag_mode_enabled: ragModeEnabled,
summarization_enabled: contextCompressionEnabled,
thread_id: threadId,
@@ -1601,8 +1770,15 @@ export function useThreadStream({
);
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
} catch (error) {
const message =
error instanceof Error ? error.message : String(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);
@@ -1639,18 +1815,18 @@ export function useThreadStream({
sendInFlightRef.current = false;
}
},
[
thread,
_handleOnStart,
t.uploads.uploadingFiles,
context,
referenceModeEntryEnabled,
localSettings.display.ragModeEnabled,
queryClient,
runOptions,
confirmOrRejoin,
],
);
[
thread,
_handleOnStart,
t.uploads.uploadingFiles,
context,
referenceModeEntryEnabled,
localSettings.display.ragModeEnabled,
queryClient,
runOptions,
confirmOrRejoin,
],
);
const handleThreadStop = useCallback(async () => {
const tid = threadIdRef.current;
@@ -1695,11 +1871,11 @@ export function useThreadStream({
const visibleThreadError =
thread.error &&
isReactMaximumUpdateDepthError(getStreamErrorMessage(thread.error))
isReactMaximumUpdateDepthError(thread.error)
? undefined
: thread.error;
const mergedThread = {
const mergedThread = {
...thread,
error: visibleThreadError,
values: mergedValues,
@@ -1709,7 +1885,7 @@ export function useThreadStream({
: mergedMessages,
isLoading: thread.isLoading || streamHoldOpen,
stop: handleThreadStop,
} as typeof thread;
} as typeof thread;
// 第 4 个返回值 `onStreamThreadId` = 底层 useStream 当前实际绑定的线程 id(新建/未保存时为 null)。
// 调用方据此判断「流是否已切到全新线程」,避免在切换会话的那一帧把消息发进上一个会话