2026-09-06 02:11:19 +08:00
|
|
|
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
2026-10-16 11:38:05 +08:00
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
2026-08-22 19:33:22 +08:00
|
|
|
import { useTranslation } from "react-i18next";
|
2026-09-09 14:02:26 +08:00
|
|
|
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
2026-04-18 18:51:53 +00:00
|
|
|
|
|
|
|
|
import { useClient } from "@/providers/ClientProvider";
|
2026-09-07 15:12:39 +08:00
|
|
|
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
|
2026-06-12 00:54:32 +08:00
|
|
|
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
2026-04-21 10:29:47 +00:00
|
|
|
import type { StreamError } from "@/lib/nanobot-client";
|
2026-08-10 15:43:54 +08:00
|
|
|
import {
|
2026-09-20 13:52:43 +08:00
|
|
|
clearThreadProjectionActivity,
|
|
|
|
|
closeThreadProjectionAnswer,
|
|
|
|
|
createThreadProjectionState,
|
2026-08-10 15:43:54 +08:00
|
|
|
finalizeStreamedTurn,
|
2026-09-20 13:52:43 +08:00
|
|
|
projectThreadEvent,
|
|
|
|
|
resetThreadProjectionCursor,
|
2026-08-10 15:43:54 +08:00
|
|
|
turnFieldsFromEvent,
|
|
|
|
|
} from "@/lib/thread-event-projection";
|
2026-09-20 13:52:43 +08:00
|
|
|
import type {
|
|
|
|
|
ThreadProjectionEvent,
|
|
|
|
|
ThreadProjectionState,
|
|
|
|
|
UIMessageTurnFields,
|
|
|
|
|
} from "@/lib/thread-event-projection";
|
2026-07-24 14:19:33 +08:00
|
|
|
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
|
2026-08-22 19:33:22 +08:00
|
|
|
import { readLocalPreferences } from "@/lib/local-preferences";
|
2026-08-30 10:37:24 +08:00
|
|
|
import { playTurnCompleteSound } from "@/lib/notification-sound";
|
2026-04-21 10:29:47 +00:00
|
|
|
import type {
|
|
|
|
|
InboundEvent,
|
2026-05-22 22:25:12 +08:00
|
|
|
OutboundCliAppMention,
|
2026-05-24 13:38:37 +08:00
|
|
|
OutboundMcpPresetMention,
|
2026-04-21 10:29:47 +00:00
|
|
|
OutboundMedia,
|
2026-08-02 22:04:59 +08:00
|
|
|
SessionMention,
|
2026-05-16 01:14:11 +08:00
|
|
|
GoalStateWsPayload,
|
2026-07-29 23:15:45 +08:00
|
|
|
MessageDeliveryStatus,
|
2026-08-22 19:33:22 +08:00
|
|
|
RecoveryState,
|
2026-09-07 15:12:39 +08:00
|
|
|
RetryStatus,
|
2026-07-14 14:47:42 +08:00
|
|
|
UIMediaAttachment,
|
2026-04-21 10:29:47 +00:00
|
|
|
UIMessage,
|
2026-05-29 03:42:53 +08:00
|
|
|
WorkspaceScopePayload,
|
2026-04-21 10:29:47 +00:00
|
|
|
} from "@/lib/types";
|
2026-04-18 18:51:53 +00:00
|
|
|
|
2026-05-17 17:04:57 +08:00
|
|
|
type PendingStreamEvent =
|
2026-09-20 15:07:19 +08:00
|
|
|
| { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"] }
|
2026-06-06 19:49:33 +08:00
|
|
|
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields };
|
|
|
|
|
|
2026-07-22 22:35:39 +08:00
|
|
|
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
2026-09-11 13:10:18 +08:00
|
|
|
// Markdown and layout work must leave room for input between visible updates.
|
|
|
|
|
const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
|
2026-10-16 11:38:05 +08:00
|
|
|
const EMPTY_INITIAL_MESSAGES: UIMessage[] = [];
|
|
|
|
|
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
|
2026-05-29 03:42:53 +08:00
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
/**
|
|
|
|
|
* Subscribe to a chat by ID. Returns the in-memory message list for the chat,
|
|
|
|
|
* a streaming flag, and a ``send`` function. Initial history must be seeded
|
2026-05-16 01:14:11 +08:00
|
|
|
* separately (e.g. via ``fetchWebuiThread``) since the server only replays
|
2026-04-18 18:51:53 +00:00
|
|
|
* live events.
|
|
|
|
|
*/
|
2026-07-14 14:47:42 +08:00
|
|
|
/** Payload passed to ``send`` when the user attaches one or more files.
|
2026-04-21 10:29:47 +00:00
|
|
|
*
|
|
|
|
|
* ``media`` is handed to the wire client verbatim; ``preview`` powers the
|
2026-07-14 14:47:42 +08:00
|
|
|
* optimistic user bubble. Keeping the two separate lets the bubble re-use the
|
|
|
|
|
* local data URL even after the server persists the file under a different
|
|
|
|
|
* name. */
|
|
|
|
|
export interface SendAttachment {
|
2026-04-21 10:29:47 +00:00
|
|
|
media: OutboundMedia;
|
2026-07-14 14:47:42 +08:00
|
|
|
preview: UIMediaAttachment;
|
2026-04-21 10:29:47 +00:00
|
|
|
}
|
|
|
|
|
|
2026-05-08 09:40:15 +00:00
|
|
|
export interface SendOptions {
|
2026-09-13 05:20:26 +08:00
|
|
|
intent?: "create_automation";
|
2026-05-22 22:25:12 +08:00
|
|
|
cliApps?: OutboundCliAppMention[];
|
2026-05-24 13:38:37 +08:00
|
|
|
mcpPresets?: OutboundMcpPresetMention[];
|
2026-08-02 22:04:59 +08:00
|
|
|
sessionMentions?: SessionMention[];
|
2026-07-22 22:35:39 +08:00
|
|
|
quotedContext?: string;
|
2026-05-29 03:42:53 +08:00
|
|
|
workspaceScope?: WorkspaceScopePayload | null;
|
2026-07-06 10:56:52 +08:00
|
|
|
sideChannel?: boolean;
|
2026-07-06 18:23:51 +08:00
|
|
|
finalizeActiveTurn?: boolean;
|
2026-07-22 22:35:39 +08:00
|
|
|
/** Append guidance to the running turn without detaching its active answer segment. */
|
|
|
|
|
continueActiveTurn?: boolean;
|
2026-07-06 10:56:52 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-26 00:18:24 +08:00
|
|
|
export interface SubmittedTurn {
|
2026-10-08 11:55:13 +08:00
|
|
|
delivery?: Promise<void>;
|
2026-07-26 00:18:24 +08:00
|
|
|
turnId: string;
|
|
|
|
|
userMessageId: string;
|
|
|
|
|
sideChannel: boolean;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-06 10:56:52 +08:00
|
|
|
function eventTurnId(ev: InboundEvent): string | undefined {
|
|
|
|
|
return "turn_id" in ev && typeof ev.turn_id === "string" ? ev.turn_id : undefined;
|
2026-05-08 09:40:15 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-29 23:15:45 +08:00
|
|
|
function transitionTurnDelivery(
|
|
|
|
|
messages: UIMessage[],
|
|
|
|
|
turnId: string,
|
|
|
|
|
status: MessageDeliveryStatus,
|
|
|
|
|
): UIMessage[] {
|
|
|
|
|
let changed = false;
|
|
|
|
|
const next = messages.map((message) => {
|
|
|
|
|
if (
|
|
|
|
|
message.role !== "user"
|
|
|
|
|
|| message.turnId !== turnId
|
|
|
|
|
|| message.deliveryStatus === status
|
|
|
|
|
|| (status === "accepted" && message.deliveryStatus !== "sending")
|
|
|
|
|
) {
|
|
|
|
|
return message;
|
|
|
|
|
}
|
|
|
|
|
changed = true;
|
|
|
|
|
return { ...message, deliveryStatus: status };
|
|
|
|
|
});
|
|
|
|
|
return changed ? next : messages;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-18 18:28:19 +08:00
|
|
|
function appendProjectedSessionInput(
|
2026-08-18 09:53:55 +08:00
|
|
|
messages: UIMessage[],
|
2026-08-18 18:28:19 +08:00
|
|
|
event: Extract<InboundEvent, { event: "user_message" }>,
|
2026-08-18 09:53:55 +08:00
|
|
|
): UIMessage[] {
|
2026-08-18 18:28:19 +08:00
|
|
|
const sessionMessage = event.provenance?.session_message;
|
|
|
|
|
const messageId = sessionMessage?.message_id?.trim();
|
|
|
|
|
if (!sessionMessage || !messageId) return messages;
|
2026-08-18 09:53:55 +08:00
|
|
|
if (messages.some((message) => message.sessionMessage?.message_id === messageId)) return messages;
|
|
|
|
|
|
|
|
|
|
const row: UIMessage = {
|
|
|
|
|
id: `session-message:${messageId}`,
|
|
|
|
|
role: "user",
|
|
|
|
|
content: event.text,
|
2026-08-18 18:28:19 +08:00
|
|
|
createdAt: typeof event.created_at_ms === "number"
|
|
|
|
|
&& Number.isFinite(event.created_at_ms)
|
|
|
|
|
? event.created_at_ms
|
|
|
|
|
: Date.now(),
|
|
|
|
|
sessionMessage,
|
2026-08-18 09:53:55 +08:00
|
|
|
...turnFieldsFromEvent(event, "user"),
|
|
|
|
|
};
|
2026-08-18 18:28:19 +08:00
|
|
|
return [...messages, row];
|
2026-08-18 09:53:55 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
export function useNanobotStream(
|
|
|
|
|
chatId: string | null,
|
2026-10-16 11:38:05 +08:00
|
|
|
initialMessages: UIMessage[] = EMPTY_INITIAL_MESSAGES,
|
2026-05-01 12:38:22 -03:00
|
|
|
hasPendingToolCalls = false,
|
2026-05-06 14:15:36 +00:00
|
|
|
onTurnEnd?: () => void,
|
2026-09-21 00:41:00 +08:00
|
|
|
onStreamDetach?: (messages: UIMessage[]) => void,
|
2026-10-16 11:38:05 +08:00
|
|
|
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
|
2026-04-18 18:51:53 +00:00
|
|
|
): {
|
|
|
|
|
messages: UIMessage[];
|
2026-07-26 00:18:24 +08:00
|
|
|
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
|
|
|
|
|
messagesReady: boolean;
|
2026-04-18 18:51:53 +00:00
|
|
|
isStreaming: boolean;
|
2026-05-16 01:14:11 +08:00
|
|
|
/** Unix epoch seconds when the current user turn started (WebSocket ``goal_status``). */
|
|
|
|
|
runStartedAt: number | null;
|
2026-09-07 15:12:39 +08:00
|
|
|
/** Transient model retry state for the active turn. */
|
|
|
|
|
retryStatus: RetryStatus | null;
|
2026-05-16 01:14:11 +08:00
|
|
|
/** Latest sustained goal for this ``chatId`` (``goal_state`` WS events). */
|
|
|
|
|
goalState: GoalStateWsPayload | undefined;
|
2026-08-22 19:33:22 +08:00
|
|
|
recoveryState: RecoveryState | null;
|
|
|
|
|
continueRecovery: () => Promise<void>;
|
|
|
|
|
dismissRecovery: () => Promise<void>;
|
2026-07-26 00:18:24 +08:00
|
|
|
send: (
|
|
|
|
|
content: string,
|
|
|
|
|
images?: SendAttachment[],
|
|
|
|
|
options?: SendOptions,
|
|
|
|
|
) => SubmittedTurn | null;
|
2026-06-09 01:08:49 +08:00
|
|
|
transcribeAudio: (dataUrl: string, options?: { durationMs?: number }) => Promise<string>;
|
2026-05-08 09:40:15 +00:00
|
|
|
stop: () => void;
|
2026-07-28 11:40:01 +08:00
|
|
|
/** Mark an accepted canonical snapshot as the definitive end of the active turn. */
|
|
|
|
|
reconcileTurnComplete: () => void;
|
2026-04-18 18:51:53 +00:00
|
|
|
setMessages: React.Dispatch<React.SetStateAction<UIMessage[]>>;
|
2026-04-21 10:29:47 +00:00
|
|
|
/** Latest transport-level fault raised since the last ``dismissStreamError``.
|
|
|
|
|
* ``null`` when there is nothing to show. */
|
|
|
|
|
streamError: StreamError | null;
|
|
|
|
|
/** Clear the current ``streamError`` (e.g. after the user dismisses the
|
|
|
|
|
* notification or starts a fresh action). */
|
|
|
|
|
dismissStreamError: () => void;
|
2026-04-18 18:51:53 +00:00
|
|
|
} {
|
|
|
|
|
const { client } = useClient();
|
2026-09-09 14:02:26 +08:00
|
|
|
const threadVisible = useThreadVisibility();
|
|
|
|
|
const threadVisibleRef = useRef(threadVisible);
|
|
|
|
|
threadVisibleRef.current = threadVisible;
|
2026-08-22 19:33:22 +08:00
|
|
|
const { t } = useTranslation();
|
2026-07-26 00:18:24 +08:00
|
|
|
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
2026-09-21 01:04:31 +08:00
|
|
|
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialMessages);
|
|
|
|
|
const messagesRef = useRef(messages);
|
|
|
|
|
// Keep received state ahead of React's batched render: navigation can unmount
|
|
|
|
|
// this hook after a stream flush but before the queued render commits.
|
|
|
|
|
const setMessages = useCallback<React.Dispatch<React.SetStateAction<UIMessage[]>>>((update) => {
|
|
|
|
|
const next = typeof update === "function" ? update(messagesRef.current) : update;
|
|
|
|
|
messagesRef.current = next;
|
|
|
|
|
setRenderedMessages(next);
|
|
|
|
|
}, []);
|
2026-07-26 00:18:24 +08:00
|
|
|
const [messageOwnerChatId, setMessageOwnerChatId] = useState(chatId);
|
2026-06-12 00:54:32 +08:00
|
|
|
/** If history ends in unfinished agent activity, keep the loading spinner alive. */
|
2026-10-16 11:38:05 +08:00
|
|
|
const initialStreaming = useMemo(() => {
|
|
|
|
|
if (completedTurnIds.length === 0) return hasPendingAgentActivity(initialMessages);
|
|
|
|
|
const completedInitialTurns = new Set(completedTurnIds);
|
|
|
|
|
return hasPendingAgentActivity(initialMessages.filter((message) => (
|
|
|
|
|
!message.turnId || !completedInitialTurns.has(message.turnId)
|
|
|
|
|
)));
|
|
|
|
|
}, [completedTurnIds, initialMessages]);
|
2026-07-26 00:18:24 +08:00
|
|
|
const [isStreaming, setIsStreaming] = useState(
|
|
|
|
|
initialStreaming || hasPendingToolCalls || initialRunStartedAt !== null,
|
|
|
|
|
);
|
2026-05-16 01:14:11 +08:00
|
|
|
/** Unix epoch seconds when the current user turn started; cleared on ``idle``. */
|
2026-07-26 00:18:24 +08:00
|
|
|
const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt);
|
2026-09-07 15:12:39 +08:00
|
|
|
const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
|
2026-05-16 01:14:11 +08:00
|
|
|
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
|
2026-08-22 19:33:22 +08:00
|
|
|
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
|
2026-04-21 10:29:47 +00:00
|
|
|
const [streamError, setStreamError] = useState<StreamError | null>(null);
|
2026-09-20 13:52:43 +08:00
|
|
|
const projectionRef = useRef<ThreadProjectionState>(
|
|
|
|
|
createThreadProjectionState(initialMessages),
|
|
|
|
|
);
|
2026-05-17 17:04:57 +08:00
|
|
|
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
|
|
|
|
const streamFrameRef = useRef<number | null>(null);
|
2026-07-22 22:35:39 +08:00
|
|
|
const streamTimerRef = useRef<number | null>(null);
|
2026-09-11 13:10:18 +08:00
|
|
|
const lastStreamFlushRef = useRef(0);
|
2026-07-06 10:56:52 +08:00
|
|
|
const sideChannelTurnIdsRef = useRef<Set<string>>(new Set());
|
2026-04-18 18:51:53 +00:00
|
|
|
|
2026-04-21 10:29:47 +00:00
|
|
|
const dismissStreamError = useCallback(() => setStreamError(null), []);
|
|
|
|
|
|
2026-08-22 19:33:22 +08:00
|
|
|
const notifyInBackground = useCallback((body: string) => {
|
|
|
|
|
if (
|
|
|
|
|
typeof Notification === "undefined"
|
|
|
|
|
|| Notification.permission !== "granted"
|
|
|
|
|
|| document.visibilityState === "visible"
|
|
|
|
|
|| !readLocalPreferences().browserNotifications
|
|
|
|
|
) return;
|
|
|
|
|
new Notification("nanobot", { body });
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-05-17 17:04:57 +08:00
|
|
|
const clearPendingStreamWork = useCallback(() => {
|
|
|
|
|
if (streamFrameRef.current !== null) {
|
|
|
|
|
window.cancelAnimationFrame(streamFrameRef.current);
|
|
|
|
|
streamFrameRef.current = null;
|
|
|
|
|
}
|
2026-07-22 22:35:39 +08:00
|
|
|
if (streamTimerRef.current !== null) {
|
|
|
|
|
window.clearTimeout(streamTimerRef.current);
|
|
|
|
|
streamTimerRef.current = null;
|
|
|
|
|
}
|
2026-05-17 17:04:57 +08:00
|
|
|
pendingStreamEventsRef.current = [];
|
2026-09-11 13:10:18 +08:00
|
|
|
lastStreamFlushRef.current = 0;
|
2026-05-17 17:04:57 +08:00
|
|
|
}, []);
|
|
|
|
|
|
2026-07-06 10:56:52 +08:00
|
|
|
const isSideChannelEvent = useCallback((ev: InboundEvent) => {
|
|
|
|
|
const turnId = eventTurnId(ev);
|
|
|
|
|
return turnId !== undefined && sideChannelTurnIdsRef.current.has(turnId);
|
|
|
|
|
}, []);
|
|
|
|
|
|
2026-05-17 23:52:14 +08:00
|
|
|
const clearActivitySegment = useCallback(() => {
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = clearThreadProjectionActivity(projectionRef.current);
|
2026-05-17 23:52:14 +08:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const closeActiveAssistantStream = useCallback(() => {
|
2026-09-20 13:52:43 +08:00
|
|
|
const hadActiveAssistant = projectionRef.current.activeAssistantId !== null;
|
|
|
|
|
projectionRef.current = closeThreadProjectionAnswer(projectionRef.current);
|
|
|
|
|
return hadActiveAssistant;
|
2026-05-17 23:52:14 +08:00
|
|
|
}, []);
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
const applyStreamError = useCallback((err: StreamError) => {
|
|
|
|
|
// One multiplexed client serves every thread. A correlated send fault
|
|
|
|
|
// belongs only to its target chat. An uncorrelated transport close can
|
|
|
|
|
// still be shown in the mounted thread, but cannot roll back any turn.
|
|
|
|
|
if (!chatId || (err.chatId && err.chatId !== chatId)) return;
|
|
|
|
|
setStreamError(err);
|
2026-09-07 15:12:39 +08:00
|
|
|
if (err.kind === "model_request_failed") return;
|
2026-07-28 11:40:01 +08:00
|
|
|
if (!err.turnId) return;
|
|
|
|
|
|
|
|
|
|
const rejectedTurnId = err.turnId;
|
|
|
|
|
pendingStreamEventsRef.current = pendingStreamEventsRef.current.filter(
|
|
|
|
|
(event) => event.turn.turnId !== rejectedTurnId,
|
|
|
|
|
);
|
|
|
|
|
sideChannelTurnIdsRef.current.delete(rejectedTurnId);
|
|
|
|
|
setMessages((prev) => {
|
|
|
|
|
const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId);
|
|
|
|
|
if (rejectedRows.length === 0) return prev;
|
|
|
|
|
const rejectedIds = new Set(rejectedRows.map((message) => message.id));
|
|
|
|
|
const rejectedSegments = new Set(
|
|
|
|
|
rejectedRows
|
|
|
|
|
.map((message) => message.activitySegmentId)
|
|
|
|
|
.filter((segmentId): segmentId is string => typeof segmentId === "string"),
|
|
|
|
|
);
|
2026-09-20 13:52:43 +08:00
|
|
|
const projection = projectionRef.current;
|
|
|
|
|
const closedAssistantIds = new Set(projection.closedAssistantIds);
|
|
|
|
|
for (const id of rejectedIds) closedAssistantIds.delete(id);
|
|
|
|
|
const nextMessages = prev.flatMap<UIMessage>((message) => {
|
2026-07-29 23:15:45 +08:00
|
|
|
if (message.turnId !== rejectedTurnId) return [message];
|
|
|
|
|
if (message.role !== "user") return [];
|
|
|
|
|
return [{
|
|
|
|
|
...message,
|
2026-09-20 13:52:43 +08:00
|
|
|
deliveryStatus: "failed" as const,
|
2026-07-29 23:15:45 +08:00
|
|
|
deliveryErrorKind: err.kind,
|
|
|
|
|
}];
|
|
|
|
|
});
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = {
|
|
|
|
|
...projection,
|
|
|
|
|
messages: nextMessages,
|
|
|
|
|
activeAssistantId: projection.activeAssistantId
|
|
|
|
|
&& rejectedIds.has(projection.activeAssistantId)
|
|
|
|
|
? null
|
|
|
|
|
: projection.activeAssistantId,
|
|
|
|
|
closedAssistantIds,
|
|
|
|
|
activitySegmentId: projection.activitySegmentId
|
|
|
|
|
&& rejectedSegments.has(projection.activitySegmentId)
|
|
|
|
|
? null
|
|
|
|
|
: projection.activitySegmentId,
|
|
|
|
|
fileEditSegmentId: projection.fileEditSegmentId
|
|
|
|
|
&& rejectedSegments.has(projection.fileEditSegmentId)
|
|
|
|
|
? null
|
|
|
|
|
: projection.fileEditSegmentId,
|
|
|
|
|
};
|
|
|
|
|
return nextMessages;
|
2026-07-28 11:40:01 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const remainingStartedAt = client.getRunStartedAt(chatId);
|
|
|
|
|
const hasRemainingRun = (
|
|
|
|
|
remainingStartedAt !== null
|
|
|
|
|
|| client.hasUnsettledRun(chatId)
|
|
|
|
|
);
|
|
|
|
|
setRunStartedAt(remainingStartedAt);
|
|
|
|
|
setIsStreaming(hasRemainingRun);
|
2026-09-20 13:52:43 +08:00
|
|
|
if (!hasRemainingRun) {
|
|
|
|
|
projectionRef.current = {
|
|
|
|
|
...projectionRef.current,
|
|
|
|
|
suppressUntilTurnEnd: false,
|
|
|
|
|
};
|
|
|
|
|
}
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [chatId, client, setMessages]);
|
2026-07-28 11:40:01 +08:00
|
|
|
|
|
|
|
|
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
|
|
|
|
|
2026-05-17 17:04:57 +08:00
|
|
|
const applyPendingStreamEvents = useCallback(
|
|
|
|
|
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
|
2026-09-20 13:52:43 +08:00
|
|
|
let projection = { ...projectionRef.current, messages: prev };
|
2026-09-09 14:02:26 +08:00
|
|
|
for (let index = 0; index < events.length; index++) {
|
|
|
|
|
const event = events[index];
|
|
|
|
|
const chunks = [event.text];
|
|
|
|
|
let turn = event.turn;
|
|
|
|
|
while (index + 1 < events.length) {
|
|
|
|
|
const nextEvent = events[index + 1];
|
|
|
|
|
if (nextEvent.kind !== event.kind
|
|
|
|
|
|| nextEvent.turn.turnId !== event.turn.turnId
|
|
|
|
|
|| nextEvent.turn.turnPhase !== event.turn.turnPhase
|
2026-09-20 15:07:19 +08:00
|
|
|
|| (nextEvent.kind === "delta" && event.kind === "delta"
|
|
|
|
|
&& (nextEvent.source !== event.source
|
|
|
|
|
|| JSON.stringify(nextEvent.responseSources) !== JSON.stringify(event.responseSources)))) break;
|
2026-09-09 14:02:26 +08:00
|
|
|
chunks.push(nextEvent.text);
|
|
|
|
|
turn = { ...turn, ...nextEvent.turn };
|
|
|
|
|
index++;
|
|
|
|
|
}
|
|
|
|
|
const text = chunks.join("");
|
2026-09-20 13:52:43 +08:00
|
|
|
const projectedEvent: ThreadProjectionEvent = event.kind === "delta"
|
|
|
|
|
? {
|
|
|
|
|
event: "delta",
|
|
|
|
|
chat_id: chatId ?? "",
|
|
|
|
|
text,
|
|
|
|
|
turn_id: turn.turnId,
|
|
|
|
|
turn_phase: turn.turnPhase,
|
|
|
|
|
turn_seq: turn.turnSeq,
|
|
|
|
|
source: event.source,
|
2026-09-20 15:07:19 +08:00
|
|
|
response_sources: event.responseSources,
|
2026-09-20 13:52:43 +08:00
|
|
|
}
|
|
|
|
|
: {
|
|
|
|
|
event: "reasoning_delta",
|
|
|
|
|
chat_id: chatId ?? "",
|
|
|
|
|
text,
|
|
|
|
|
turn_id: turn.turnId,
|
|
|
|
|
turn_phase: turn.turnPhase,
|
|
|
|
|
turn_seq: turn.turnSeq,
|
|
|
|
|
};
|
|
|
|
|
projection = projectThreadEvent(projection, projectedEvent, {
|
|
|
|
|
createId: () => crypto.randomUUID(),
|
|
|
|
|
now: Date.now(),
|
|
|
|
|
});
|
2026-05-17 17:04:57 +08:00
|
|
|
}
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = projection;
|
|
|
|
|
return projection.messages;
|
2026-05-17 17:04:57 +08:00
|
|
|
},
|
2026-09-20 13:52:43 +08:00
|
|
|
[chatId],
|
2026-05-17 17:04:57 +08:00
|
|
|
);
|
|
|
|
|
|
2026-05-23 01:39:46 +08:00
|
|
|
const flushPendingStreamEvents = useCallback((options?: {
|
|
|
|
|
closeAnswerSegment?: boolean;
|
2026-09-09 14:02:26 +08:00
|
|
|
mergeReasoning?: boolean;
|
2026-05-23 01:39:46 +08:00
|
|
|
finalAnswerText?: string;
|
2026-06-06 19:49:33 +08:00
|
|
|
turn?: UIMessageTurnFields;
|
2026-07-07 10:17:23 +08:00
|
|
|
source?: UIMessage["source"];
|
2026-09-20 15:07:19 +08:00
|
|
|
responseSources?: UIMessage["responseSources"];
|
2026-05-23 01:39:46 +08:00
|
|
|
}) => {
|
2026-09-11 13:10:18 +08:00
|
|
|
lastStreamFlushRef.current = 0;
|
2026-05-17 17:04:57 +08:00
|
|
|
if (streamFrameRef.current !== null) {
|
|
|
|
|
window.cancelAnimationFrame(streamFrameRef.current);
|
|
|
|
|
streamFrameRef.current = null;
|
|
|
|
|
}
|
2026-07-22 22:35:39 +08:00
|
|
|
if (streamTimerRef.current !== null) {
|
|
|
|
|
window.clearTimeout(streamTimerRef.current);
|
|
|
|
|
streamTimerRef.current = null;
|
|
|
|
|
}
|
2026-05-17 17:04:57 +08:00
|
|
|
const events = pendingStreamEventsRef.current;
|
2026-05-23 01:39:46 +08:00
|
|
|
const finalAnswerText = options?.finalAnswerText;
|
2026-06-06 19:49:33 +08:00
|
|
|
const turn = options?.turn ?? {};
|
2026-07-07 10:17:23 +08:00
|
|
|
const source = options?.source;
|
2026-09-20 15:07:19 +08:00
|
|
|
const responseSources = options?.responseSources;
|
|
|
|
|
if (events.length === 0 && finalAnswerText === undefined && source === undefined && responseSources === undefined
|
2026-09-09 14:02:26 +08:00
|
|
|
&& !options?.mergeReasoning) {
|
2026-05-17 23:52:14 +08:00
|
|
|
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-05-17 17:04:57 +08:00
|
|
|
pendingStreamEventsRef.current = [];
|
2026-05-17 23:52:14 +08:00
|
|
|
setMessages((prev) => {
|
2026-09-20 13:52:43 +08:00
|
|
|
const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
|
|
|
|
|
let projection = { ...projectionRef.current, messages: nextMessages };
|
|
|
|
|
if (
|
|
|
|
|
finalAnswerText !== undefined
|
|
|
|
|
|| source !== undefined
|
2026-09-20 15:07:19 +08:00
|
|
|
|| responseSources !== undefined
|
2026-09-20 13:52:43 +08:00
|
|
|
|| options?.mergeReasoning
|
|
|
|
|
|| options?.closeAnswerSegment
|
|
|
|
|
) {
|
|
|
|
|
projection = projectThreadEvent(projection, {
|
|
|
|
|
event: "stream_end",
|
|
|
|
|
chat_id: chatId ?? "",
|
|
|
|
|
...(finalAnswerText !== undefined ? { text: finalAnswerText } : {}),
|
|
|
|
|
...(source ? { source } : {}),
|
2026-09-20 15:07:19 +08:00
|
|
|
...(responseSources !== undefined ? { response_sources: responseSources } : {}),
|
2026-09-20 13:52:43 +08:00
|
|
|
...(options?.mergeReasoning ? { resuming: true, merge_next: true } : {}),
|
|
|
|
|
turn_id: turn.turnId,
|
|
|
|
|
turn_phase: turn.turnPhase,
|
|
|
|
|
turn_seq: turn.turnSeq,
|
|
|
|
|
}, {
|
|
|
|
|
createId: () => crypto.randomUUID(),
|
|
|
|
|
now: Date.now(),
|
|
|
|
|
});
|
2026-07-22 22:35:39 +08:00
|
|
|
}
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = projection;
|
|
|
|
|
return projection.messages;
|
2026-05-17 23:52:14 +08:00
|
|
|
});
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [applyPendingStreamEvents, chatId, closeActiveAssistantStream, setMessages]);
|
2026-05-17 17:04:57 +08:00
|
|
|
|
2026-09-11 13:10:18 +08:00
|
|
|
const schedulePendingStreamFlush = useCallback(function schedule() {
|
2026-07-22 22:35:39 +08:00
|
|
|
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
2026-09-09 14:02:26 +08:00
|
|
|
if (document.visibilityState === "hidden" || !threadVisibleRef.current) {
|
2026-07-22 22:35:39 +08:00
|
|
|
streamTimerRef.current = window.setTimeout(() => {
|
|
|
|
|
streamTimerRef.current = null;
|
|
|
|
|
const events = pendingStreamEventsRef.current;
|
|
|
|
|
if (events.length === 0) return;
|
|
|
|
|
pendingStreamEventsRef.current = [];
|
|
|
|
|
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
|
|
|
|
}, BACKGROUND_STREAM_FLUSH_INTERVAL_MS);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-09-11 13:10:18 +08:00
|
|
|
const delay = VISIBLE_STREAM_FLUSH_INTERVAL_MS
|
|
|
|
|
- (performance.now() - lastStreamFlushRef.current);
|
|
|
|
|
if (delay > 0) {
|
|
|
|
|
streamTimerRef.current = window.setTimeout(() => {
|
|
|
|
|
streamTimerRef.current = null;
|
|
|
|
|
schedule();
|
|
|
|
|
}, delay);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-05-17 17:04:57 +08:00
|
|
|
streamFrameRef.current = window.requestAnimationFrame(() => {
|
|
|
|
|
streamFrameRef.current = null;
|
|
|
|
|
const events = pendingStreamEventsRef.current;
|
|
|
|
|
if (events.length === 0) return;
|
|
|
|
|
pendingStreamEventsRef.current = [];
|
2026-09-11 13:10:18 +08:00
|
|
|
lastStreamFlushRef.current = performance.now();
|
2026-05-17 17:04:57 +08:00
|
|
|
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
|
|
|
|
});
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [applyPendingStreamEvents, setMessages]);
|
2026-05-17 17:04:57 +08:00
|
|
|
|
2026-09-09 14:02:26 +08:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (threadVisible) {
|
|
|
|
|
flushPendingStreamEvents();
|
2026-09-11 13:10:18 +08:00
|
|
|
} else if (streamFrameRef.current !== null || streamTimerRef.current !== null) {
|
|
|
|
|
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
2026-09-09 14:02:26 +08:00
|
|
|
streamFrameRef.current = null;
|
2026-09-11 13:10:18 +08:00
|
|
|
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
|
|
|
|
streamTimerRef.current = null;
|
2026-09-09 14:02:26 +08:00
|
|
|
schedulePendingStreamFlush();
|
|
|
|
|
}
|
|
|
|
|
}, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);
|
|
|
|
|
|
2026-07-22 22:35:39 +08:00
|
|
|
useEffect(() => {
|
2026-09-11 13:10:18 +08:00
|
|
|
const onVisibilityChange = () => {
|
2026-07-22 22:35:39 +08:00
|
|
|
if (pendingStreamEventsRef.current.length === 0) return;
|
2026-09-11 13:10:18 +08:00
|
|
|
if (document.visibilityState === "visible" && threadVisibleRef.current) {
|
|
|
|
|
flushPendingStreamEvents();
|
|
|
|
|
} else {
|
|
|
|
|
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
|
|
|
|
streamFrameRef.current = null;
|
|
|
|
|
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
|
|
|
|
streamTimerRef.current = null;
|
|
|
|
|
schedulePendingStreamFlush();
|
|
|
|
|
}
|
2026-07-22 22:35:39 +08:00
|
|
|
};
|
2026-09-11 13:10:18 +08:00
|
|
|
document.addEventListener("visibilitychange", onVisibilityChange);
|
|
|
|
|
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
|
|
|
|
|
}, [flushPendingStreamEvents, schedulePendingStreamFlush]);
|
2026-07-22 22:35:39 +08:00
|
|
|
|
2026-08-24 23:29:49 +08:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (!chatId) return;
|
|
|
|
|
return client.onRunStatus((runChatId, startedAt) => {
|
|
|
|
|
if (runChatId !== chatId) return;
|
|
|
|
|
if (startedAt !== null) {
|
|
|
|
|
setRunStartedAt(startedAt);
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
flushPendingStreamEvents();
|
2026-09-20 13:52:43 +08:00
|
|
|
setMessages((prev) => {
|
|
|
|
|
const settled = prev.map((message) => (
|
|
|
|
|
message.isStreaming ? { ...message, isStreaming: false } : message
|
|
|
|
|
));
|
|
|
|
|
projectionRef.current = resetThreadProjectionCursor(
|
|
|
|
|
projectionRef.current,
|
|
|
|
|
settled,
|
|
|
|
|
);
|
|
|
|
|
return settled;
|
|
|
|
|
});
|
2026-08-24 23:29:49 +08:00
|
|
|
setRunStartedAt(null);
|
|
|
|
|
setIsStreaming(false);
|
|
|
|
|
});
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [chatId, client, clearActivitySegment, flushPendingStreamEvents, setMessages]);
|
2026-08-24 23:29:49 +08:00
|
|
|
|
2026-05-08 09:40:15 +00:00
|
|
|
// Reset local state when switching chats. Do not reset on every
|
|
|
|
|
// ``initialMessages`` update: a brand-new chat can receive an empty/404
|
|
|
|
|
// history response after the optimistic first message has already rendered.
|
|
|
|
|
useEffect(() => {
|
2026-07-26 00:18:24 +08:00
|
|
|
const restoredRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
2026-05-08 09:40:15 +00:00
|
|
|
setMessages(initialMessages);
|
2026-07-26 00:18:24 +08:00
|
|
|
setMessageOwnerChatId(chatId);
|
2026-05-08 09:40:15 +00:00
|
|
|
setIsStreaming(
|
2026-10-16 11:38:05 +08:00
|
|
|
initialStreaming
|
2026-07-26 00:18:24 +08:00
|
|
|
|| hasPendingToolCalls
|
|
|
|
|
|| restoredRunStartedAt !== null,
|
2026-05-08 09:40:15 +00:00
|
|
|
);
|
|
|
|
|
setStreamError(null);
|
2026-07-26 00:18:24 +08:00
|
|
|
setRunStartedAt(restoredRunStartedAt);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-05-16 01:14:11 +08:00
|
|
|
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
|
2026-08-22 19:33:22 +08:00
|
|
|
setRecoveryState(null);
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = createThreadProjectionState(initialMessages);
|
2026-05-17 17:04:57 +08:00
|
|
|
clearPendingStreamWork();
|
2026-07-06 10:56:52 +08:00
|
|
|
sideChannelTurnIdsRef.current.clear();
|
2026-05-08 09:40:15 +00:00
|
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [chatId, client, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
2026-05-08 09:40:15 +00:00
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
if (hasPendingToolCalls) setIsStreaming(true);
|
|
|
|
|
}, [hasPendingToolCalls]);
|
2026-04-18 18:51:53 +00:00
|
|
|
|
2026-09-20 13:52:43 +08:00
|
|
|
const applyProjectionEvent = useCallback((
|
|
|
|
|
event: ThreadProjectionEvent,
|
|
|
|
|
options?: { sideChannel?: boolean },
|
|
|
|
|
) => {
|
|
|
|
|
setMessages((prev) => {
|
|
|
|
|
const projection = projectThreadEvent(
|
|
|
|
|
{ ...projectionRef.current, messages: prev },
|
|
|
|
|
event,
|
|
|
|
|
{
|
|
|
|
|
createId: () => crypto.randomUUID(),
|
|
|
|
|
now: Date.now(),
|
|
|
|
|
sideChannel: options?.sideChannel,
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
projectionRef.current = projection;
|
|
|
|
|
return projection.messages;
|
|
|
|
|
});
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [setMessages]);
|
2026-09-20 13:52:43 +08:00
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
useEffect(() => {
|
|
|
|
|
if (!chatId) return;
|
|
|
|
|
|
|
|
|
|
const handle = (ev: InboundEvent) => {
|
2026-07-28 11:40:01 +08:00
|
|
|
if (ev.event === "error") {
|
|
|
|
|
if (ev.detail === "message_too_big") {
|
|
|
|
|
applyStreamError({
|
|
|
|
|
kind: "message_too_big",
|
|
|
|
|
chatId,
|
|
|
|
|
turnId: ev.turn_id,
|
|
|
|
|
});
|
|
|
|
|
} else if (ev.detail === "workspace_scope_rejected") {
|
|
|
|
|
applyStreamError({
|
|
|
|
|
kind: "workspace_scope_rejected",
|
|
|
|
|
reason: ev.reason,
|
|
|
|
|
chatId,
|
|
|
|
|
turnId: ev.turn_id,
|
|
|
|
|
});
|
|
|
|
|
} else if (ev.turn_id) {
|
|
|
|
|
applyStreamError({
|
|
|
|
|
kind: "turn_rejected",
|
|
|
|
|
detail: ev.detail,
|
|
|
|
|
reason: ev.reason,
|
|
|
|
|
chatId,
|
|
|
|
|
turnId: ev.turn_id,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-07-29 23:15:45 +08:00
|
|
|
const turnId = eventTurnId(ev);
|
|
|
|
|
if (turnId) {
|
|
|
|
|
setMessages((prev) => transitionTurnDelivery(prev, turnId, "accepted"));
|
|
|
|
|
}
|
|
|
|
|
if (ev.event === "message_accepted") return;
|
2026-08-16 19:36:34 +08:00
|
|
|
if (ev.event === "user_message") {
|
2026-08-18 18:28:19 +08:00
|
|
|
if (ev.provenance?.session_message) {
|
|
|
|
|
flushPendingStreamEvents({ closeAnswerSegment: true });
|
|
|
|
|
clearActivitySegment();
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
setMessages((prev) => appendProjectedSessionInput(prev, ev));
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-08-16 19:36:34 +08:00
|
|
|
setMessages((prev) => {
|
|
|
|
|
if (ev.turn_id && prev.some((message) => (
|
|
|
|
|
message.role === "user" && message.turnId === ev.turn_id
|
|
|
|
|
))) return prev;
|
|
|
|
|
return [
|
|
|
|
|
...prev,
|
|
|
|
|
{
|
|
|
|
|
id: crypto.randomUUID(),
|
|
|
|
|
role: "user",
|
|
|
|
|
content: ev.text,
|
|
|
|
|
...(ev.turn_id ? { turnId: ev.turn_id } : {}),
|
|
|
|
|
turnPhase: "user",
|
|
|
|
|
turnSeq: 0,
|
|
|
|
|
deliveryStatus: "accepted",
|
2026-08-18 18:28:19 +08:00
|
|
|
createdAt: typeof ev.created_at_ms === "number"
|
|
|
|
|
&& Number.isFinite(ev.created_at_ms)
|
|
|
|
|
? ev.created_at_ms
|
|
|
|
|
: Date.now(),
|
2026-08-16 19:36:34 +08:00
|
|
|
...(ev.media_urls?.length ? { media: ev.media_urls } : {}),
|
|
|
|
|
...(ev.cli_apps?.length ? { cliApps: ev.cli_apps } : {}),
|
|
|
|
|
...(ev.mcp_presets?.length ? { mcpPresets: ev.mcp_presets } : {}),
|
|
|
|
|
...(ev.session_mentions?.length
|
|
|
|
|
? { sessionMentions: ev.session_mentions }
|
|
|
|
|
: {}),
|
|
|
|
|
},
|
|
|
|
|
];
|
|
|
|
|
});
|
|
|
|
|
if (ev.active_turn_id || ev.starts_turn) {
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
if (typeof ev.started_at === "number") setRunStartedAt(ev.started_at);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-07-06 10:56:52 +08:00
|
|
|
const sideChannelEvent = isSideChannelEvent(ev);
|
2026-09-05 20:21:54 +08:00
|
|
|
if (ev.event === "context_compaction") {
|
|
|
|
|
flushPendingStreamEvents({ closeAnswerSegment: true });
|
|
|
|
|
clearActivitySegment();
|
|
|
|
|
const compaction = {
|
|
|
|
|
id: ev.compaction_id,
|
|
|
|
|
phase: ev.phase,
|
|
|
|
|
announce: true,
|
|
|
|
|
};
|
|
|
|
|
setMessages((prev) => {
|
|
|
|
|
const id = `compaction-${ev.compaction_id}`;
|
|
|
|
|
const existing = prev.findIndex((message) => message.id === id);
|
2026-09-06 02:11:19 +08:00
|
|
|
if (!acceptsCompactionPhase(prev[existing]?.compaction?.phase, ev.phase)) return prev;
|
2026-09-05 20:21:54 +08:00
|
|
|
const next = {
|
|
|
|
|
id,
|
|
|
|
|
role: "assistant" as const,
|
|
|
|
|
content: "",
|
|
|
|
|
kind: "compaction" as const,
|
|
|
|
|
createdAt: Date.now(),
|
|
|
|
|
compaction,
|
|
|
|
|
...turnFieldsFromEvent(ev, "activity"),
|
|
|
|
|
};
|
|
|
|
|
if (existing < 0) return [...prev, next];
|
|
|
|
|
return prev.map((message, index) => (
|
|
|
|
|
index === existing
|
|
|
|
|
? { ...next, createdAt: message.createdAt }
|
|
|
|
|
: message
|
|
|
|
|
));
|
|
|
|
|
});
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-09-07 15:12:39 +08:00
|
|
|
if (
|
|
|
|
|
ev.event === "delta"
|
|
|
|
|
|| ev.event === "message"
|
|
|
|
|
|| ev.event === "file_edit"
|
|
|
|
|
|| ev.event === "reasoning_delta"
|
|
|
|
|
|| ev.event === "stream_end"
|
|
|
|
|
) setRetryStatus(null);
|
2026-04-18 18:51:53 +00:00
|
|
|
if (ev.event === "delta") {
|
2026-09-20 13:52:43 +08:00
|
|
|
if (projectionRef.current.suppressUntilTurnEnd) return;
|
2026-05-16 08:33:15 +00:00
|
|
|
const chunk = typeof ev.text === "string" ? ev.text : "";
|
2026-05-17 17:04:57 +08:00
|
|
|
if (!chunk) return;
|
2026-05-13 07:13:43 +00:00
|
|
|
setIsStreaming(true);
|
2026-06-06 19:49:33 +08:00
|
|
|
pendingStreamEventsRef.current.push({
|
|
|
|
|
kind: "delta",
|
|
|
|
|
text: chunk,
|
|
|
|
|
turn: turnFieldsFromEvent(ev, "answer"),
|
2026-07-07 10:17:23 +08:00
|
|
|
source: ev.source,
|
2026-09-20 15:07:19 +08:00
|
|
|
responseSources: ev.response_sources,
|
2026-06-06 19:49:33 +08:00
|
|
|
});
|
2026-05-17 17:04:57 +08:00
|
|
|
schedulePendingStreamFlush();
|
2026-04-18 18:51:53 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-17 17:04:57 +08:00
|
|
|
if (ev.event === "reasoning_delta") {
|
2026-09-20 13:52:43 +08:00
|
|
|
if (projectionRef.current.suppressUntilTurnEnd) return;
|
2026-05-17 17:04:57 +08:00
|
|
|
const chunk = ev.text;
|
|
|
|
|
if (!chunk) return;
|
|
|
|
|
setIsStreaming(true);
|
2026-06-06 19:49:33 +08:00
|
|
|
pendingStreamEventsRef.current.push({
|
|
|
|
|
kind: "reasoning",
|
|
|
|
|
text: chunk,
|
|
|
|
|
turn: turnFieldsFromEvent(ev, "reasoning"),
|
|
|
|
|
});
|
2026-05-17 17:04:57 +08:00
|
|
|
schedulePendingStreamFlush();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
if (ev.event === "stream_end") {
|
2026-07-06 10:56:52 +08:00
|
|
|
const turn = turnFieldsFromEvent(ev, "answer");
|
2026-07-23 18:35:41 +08:00
|
|
|
const mergeNext = ev.resuming === true && ev.merge_next === true;
|
2026-05-23 01:39:46 +08:00
|
|
|
flushPendingStreamEvents({
|
2026-07-23 18:35:41 +08:00
|
|
|
closeAnswerSegment: !mergeNext,
|
2026-09-09 14:02:26 +08:00
|
|
|
mergeReasoning: mergeNext,
|
2026-05-23 01:39:46 +08:00
|
|
|
...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}),
|
2026-07-06 10:56:52 +08:00
|
|
|
turn,
|
2026-07-07 10:17:23 +08:00
|
|
|
source: ev.source,
|
2026-09-20 15:07:19 +08:00
|
|
|
responseSources: ev.response_sources,
|
2026-05-23 01:39:46 +08:00
|
|
|
});
|
2026-09-20 13:52:43 +08:00
|
|
|
if (projectionRef.current.suppressUntilTurnEnd) return;
|
2026-07-22 22:35:39 +08:00
|
|
|
if (ev.resuming) {
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-08-22 19:41:37 +08:00
|
|
|
// ``stream_end`` closes the current answer segment, not the turn.
|
|
|
|
|
// Tools and follow-up model segments may still arrive before the
|
|
|
|
|
// definitive ``turn_end`` event.
|
|
|
|
|
setIsStreaming(true);
|
2026-05-01 12:38:22 -03:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-20 13:52:43 +08:00
|
|
|
flushPendingStreamEvents();
|
2026-05-17 23:52:14 +08:00
|
|
|
|
2026-05-13 07:13:43 +00:00
|
|
|
if (ev.event === "reasoning_end") {
|
2026-09-20 13:52:43 +08:00
|
|
|
if (projectionRef.current.suppressUntilTurnEnd) return;
|
|
|
|
|
applyProjectionEvent(ev);
|
2026-05-13 07:13:43 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-16 01:14:11 +08:00
|
|
|
if (ev.event === "goal_state") {
|
|
|
|
|
setGoalState(ev.goal_state);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (ev.event === "goal_status") {
|
|
|
|
|
if (ev.status === "running" && typeof ev.started_at === "number") {
|
2026-09-07 15:12:39 +08:00
|
|
|
setStreamError(null);
|
2026-05-16 01:14:11 +08:00
|
|
|
setRunStartedAt(ev.started_at);
|
2026-07-26 00:18:24 +08:00
|
|
|
setIsStreaming(true);
|
2026-05-16 01:14:11 +08:00
|
|
|
} else {
|
|
|
|
|
setRunStartedAt(null);
|
2026-07-26 00:18:24 +08:00
|
|
|
setIsStreaming(false);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (ev.event === "retry_status") {
|
|
|
|
|
const activeTurnId = client.getRunTurnId(chatId);
|
|
|
|
|
if (ev.turn_id && activeTurnId && ev.turn_id !== activeTurnId) return;
|
|
|
|
|
if (ev.state === "recovered" || ev.state === "cleared") {
|
|
|
|
|
setRetryStatus(null);
|
|
|
|
|
} else {
|
|
|
|
|
const retryAfterSeconds =
|
|
|
|
|
typeof ev.retry_after_s === "number" &&
|
|
|
|
|
Number.isFinite(ev.retry_after_s) &&
|
|
|
|
|
ev.retry_after_s >= 0
|
|
|
|
|
? ev.retry_after_s
|
|
|
|
|
: undefined;
|
|
|
|
|
setRetryStatus({
|
|
|
|
|
state: ev.state,
|
|
|
|
|
attempt: ev.attempt,
|
|
|
|
|
error_kind: ev.error_kind,
|
|
|
|
|
...(typeof ev.max_attempts === "number"
|
|
|
|
|
? { max_attempts: ev.max_attempts }
|
|
|
|
|
: {}),
|
|
|
|
|
...(retryAfterSeconds !== undefined
|
|
|
|
|
? { next_retry_at: Date.now() / 1000 + retryAfterSeconds }
|
|
|
|
|
: {}),
|
|
|
|
|
...(ev.turn_id ? { turn_id: ev.turn_id } : {}),
|
|
|
|
|
});
|
|
|
|
|
setIsStreaming(true);
|
2026-05-16 01:14:11 +08:00
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-01 12:38:22 -03:00
|
|
|
if (ev.event === "turn_end") {
|
2026-09-05 20:21:54 +08:00
|
|
|
if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id);
|
2026-05-16 01:14:11 +08:00
|
|
|
if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") {
|
|
|
|
|
setGoalState(ev.goal_state);
|
|
|
|
|
}
|
2026-05-29 03:42:53 +08:00
|
|
|
setRunStartedAt(null);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-08-22 19:41:37 +08:00
|
|
|
// Definitive signal that the turn is fully complete, so stop the
|
|
|
|
|
// loading indicator immediately.
|
2026-04-18 18:51:53 +00:00
|
|
|
setIsStreaming(false);
|
2026-09-07 15:12:39 +08:00
|
|
|
const modelRequestFailed = ev.outcome === "failed" && ev.failure_kind === "model";
|
|
|
|
|
const failureAttempts =
|
|
|
|
|
typeof ev.failure_attempts === "number"
|
|
|
|
|
&& Number.isInteger(ev.failure_attempts)
|
|
|
|
|
&& ev.failure_attempts > 0
|
|
|
|
|
? ev.failure_attempts
|
|
|
|
|
: undefined;
|
|
|
|
|
const modelFailure = modelRequestFailed
|
|
|
|
|
? {
|
|
|
|
|
kind: "model_request_failed" as const,
|
|
|
|
|
chatId,
|
|
|
|
|
...(ev.turn_id ? { turnId: ev.turn_id } : {}),
|
|
|
|
|
...(typeof ev.failure_error_kind === "string"
|
|
|
|
|
? { errorKind: ev.failure_error_kind }
|
|
|
|
|
: {}),
|
|
|
|
|
...(failureAttempts !== undefined ? { attempts: failureAttempts } : {}),
|
|
|
|
|
}
|
|
|
|
|
: null;
|
|
|
|
|
if (modelFailure) setStreamError(modelFailure);
|
2026-09-20 13:52:43 +08:00
|
|
|
applyProjectionEvent(ev);
|
2026-09-07 15:12:39 +08:00
|
|
|
notifyInBackground(
|
|
|
|
|
modelFailure
|
|
|
|
|
? resolveModelRequestFailureCopy(modelFailure, t).body
|
|
|
|
|
: ev.outcome === "failed"
|
|
|
|
|
? ev.failure_message || "This turn failed and has ended."
|
|
|
|
|
: t("recovery.completed", { defaultValue: "Task completed" }),
|
|
|
|
|
);
|
2026-08-30 10:37:24 +08:00
|
|
|
playTurnCompleteSound();
|
2026-05-06 14:15:36 +00:00
|
|
|
onTurnEnd?.();
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-22 19:33:22 +08:00
|
|
|
if (ev.event === "recovery_state") {
|
|
|
|
|
const next: RecoveryState = {
|
|
|
|
|
status: ev.status,
|
|
|
|
|
recovery_id: ev.recovery_id,
|
|
|
|
|
...(ev.reason ? { reason: ev.reason } : {}),
|
|
|
|
|
...(typeof ev.attempts === "number" ? { attempts: ev.attempts } : {}),
|
|
|
|
|
...(typeof ev.can_continue === "boolean"
|
|
|
|
|
? { can_continue: ev.can_continue }
|
|
|
|
|
: {}),
|
|
|
|
|
};
|
|
|
|
|
setRecoveryState(next);
|
|
|
|
|
if (ev.status === "resuming") {
|
|
|
|
|
setRunStartedAt((current) => current ?? Date.now() / 1000);
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
}
|
|
|
|
|
if (
|
|
|
|
|
ev.status === "awaiting_user"
|
|
|
|
|
|| ev.status === "recovered"
|
|
|
|
|
|| ev.status === "failed"
|
|
|
|
|
) {
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-08-22 19:33:22 +08:00
|
|
|
// Recovery is an explicit boundary. The interrupted turn is no
|
|
|
|
|
// longer running, so do not let the stale start time keep the
|
|
|
|
|
// activity clock (or composer stop state) alive underneath the
|
|
|
|
|
// recovery notice.
|
|
|
|
|
setRunStartedAt(null);
|
|
|
|
|
setIsStreaming(false);
|
|
|
|
|
client.finishRunLocally(chatId);
|
|
|
|
|
clearPendingStreamWork();
|
|
|
|
|
closeActiveAssistantStream();
|
|
|
|
|
clearActivitySegment();
|
|
|
|
|
if (ev.status !== "recovered") {
|
|
|
|
|
notifyInBackground(
|
|
|
|
|
ev.status === "failed"
|
|
|
|
|
? t("recovery.failed", { defaultValue: "Task recovery failed" })
|
|
|
|
|
: t("recovery.interrupted", { defaultValue: "Task interrupted" }),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (ev.event === "attached") {
|
|
|
|
|
setRecoveryState(ev.recovery_state ?? null);
|
|
|
|
|
if (ev.recovery_state?.status === "resuming") {
|
|
|
|
|
setRunStartedAt((current) => current ?? Date.now() / 1000);
|
|
|
|
|
setIsStreaming(true);
|
|
|
|
|
} else if (
|
|
|
|
|
ev.recovery_state?.status === "awaiting_user"
|
|
|
|
|
|| ev.recovery_state?.status === "failed"
|
|
|
|
|
) {
|
|
|
|
|
setRunStartedAt(null);
|
|
|
|
|
setIsStreaming(false);
|
|
|
|
|
client.finishRunLocally(chatId);
|
|
|
|
|
clearPendingStreamWork();
|
|
|
|
|
closeActiveAssistantStream();
|
|
|
|
|
clearActivitySegment();
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
if (ev.event === "message") {
|
2026-09-20 13:52:43 +08:00
|
|
|
applyProjectionEvent(ev, { sideChannel: sideChannelEvent });
|
|
|
|
|
if (sideChannelEvent && typeof ev.turn_id === "string") {
|
|
|
|
|
sideChannelTurnIdsRef.current.delete(ev.turn_id);
|
2026-05-08 09:40:15 +00:00
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
return;
|
|
|
|
|
}
|
2026-05-17 23:52:14 +08:00
|
|
|
if (ev.event === "file_edit") {
|
2026-09-20 13:52:43 +08:00
|
|
|
applyProjectionEvent(ev);
|
2026-05-17 23:52:14 +08:00
|
|
|
return;
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const unsub = client.onChat(chatId, handle);
|
|
|
|
|
return () => {
|
|
|
|
|
unsub();
|
2026-09-21 00:41:00 +08:00
|
|
|
// Navigation may happen before the throttled paint. Snapshot the pending
|
|
|
|
|
// deltas synchronously while they still belong to this subscription.
|
|
|
|
|
const pending = pendingStreamEventsRef.current;
|
|
|
|
|
const snapshot = pending.length > 0
|
2026-09-21 01:04:31 +08:00
|
|
|
? applyPendingStreamEvents(messagesRef.current, pending)
|
|
|
|
|
: messagesRef.current;
|
2026-09-21 00:41:00 +08:00
|
|
|
onStreamDetach?.(snapshot);
|
|
|
|
|
if (pending.length > 0) setMessages(snapshot);
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
2026-05-17 17:04:57 +08:00
|
|
|
clearPendingStreamWork();
|
2026-04-18 18:51:53 +00:00
|
|
|
};
|
2026-05-17 17:04:57 +08:00
|
|
|
}, [
|
2026-09-20 13:52:43 +08:00
|
|
|
applyProjectionEvent,
|
2026-09-21 00:41:00 +08:00
|
|
|
applyPendingStreamEvents,
|
2026-07-28 11:40:01 +08:00
|
|
|
applyStreamError,
|
2026-05-17 17:04:57 +08:00
|
|
|
chatId,
|
2026-08-22 19:41:37 +08:00
|
|
|
closeActiveAssistantStream,
|
2026-05-17 17:04:57 +08:00
|
|
|
client,
|
2026-05-17 23:52:14 +08:00
|
|
|
clearActivitySegment,
|
2026-05-17 17:04:57 +08:00
|
|
|
clearPendingStreamWork,
|
|
|
|
|
flushPendingStreamEvents,
|
2026-07-06 10:56:52 +08:00
|
|
|
isSideChannelEvent,
|
2026-08-22 19:33:22 +08:00
|
|
|
notifyInBackground,
|
2026-05-17 17:04:57 +08:00
|
|
|
onTurnEnd,
|
2026-09-21 00:41:00 +08:00
|
|
|
onStreamDetach,
|
2026-05-17 17:04:57 +08:00
|
|
|
schedulePendingStreamFlush,
|
2026-09-21 01:04:31 +08:00
|
|
|
setMessages,
|
2026-08-22 19:33:22 +08:00
|
|
|
t,
|
2026-05-17 17:04:57 +08:00
|
|
|
]);
|
2026-04-18 18:51:53 +00:00
|
|
|
|
|
|
|
|
const send = useCallback(
|
2026-07-14 14:47:42 +08:00
|
|
|
(content: string, images?: SendAttachment[], options?: SendOptions) => {
|
2026-07-26 00:18:24 +08:00
|
|
|
if (!chatId) return null;
|
2026-07-14 14:47:42 +08:00
|
|
|
const hasAttachments = !!images && images.length > 0;
|
|
|
|
|
// Text is optional when files are attached — the agent will still see
|
|
|
|
|
// them via ``media`` paths.
|
2026-07-26 00:18:24 +08:00
|
|
|
if (!hasAttachments && !content.trim()) return null;
|
2026-04-21 10:29:47 +00:00
|
|
|
|
2026-09-07 15:12:39 +08:00
|
|
|
setStreamError(null);
|
2026-07-06 10:56:52 +08:00
|
|
|
const sideChannel = options?.sideChannel === true;
|
2026-07-06 18:23:51 +08:00
|
|
|
const finalizeActiveTurn = options?.finalizeActiveTurn === true;
|
2026-07-22 22:35:39 +08:00
|
|
|
const continueActiveTurn = options?.continueActiveTurn === true;
|
2026-07-24 14:19:33 +08:00
|
|
|
const outboundContent = options?.quotedContext
|
|
|
|
|
? formatQuotedUserMessage(content, options.quotedContext)
|
|
|
|
|
: content;
|
2026-05-17 17:04:57 +08:00
|
|
|
flushPendingStreamEvents();
|
2026-07-06 18:23:51 +08:00
|
|
|
if (finalizeActiveTurn) {
|
|
|
|
|
setIsStreaming(false);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-07-06 18:23:51 +08:00
|
|
|
}
|
2026-06-06 19:49:33 +08:00
|
|
|
const turnId = crypto.randomUUID();
|
2026-07-26 00:18:24 +08:00
|
|
|
const userMessageId = crypto.randomUUID();
|
2026-07-06 10:56:52 +08:00
|
|
|
if (sideChannel) sideChannelTurnIdsRef.current.add(turnId);
|
2026-07-14 14:47:42 +08:00
|
|
|
const previews = hasAttachments ? images!.map((i) => i.preview) : undefined;
|
2026-05-17 17:04:57 +08:00
|
|
|
setMessages((prev) => {
|
2026-09-20 13:52:43 +08:00
|
|
|
let projection = { ...projectionRef.current, messages: prev };
|
2026-07-22 22:35:39 +08:00
|
|
|
if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) {
|
2026-09-20 13:52:43 +08:00
|
|
|
projection = resetThreadProjectionCursor(projection, prev);
|
2026-07-22 22:35:39 +08:00
|
|
|
} else if (continueActiveTurn) {
|
|
|
|
|
// Guidance belongs to the active backend turn. Preserve the answer
|
|
|
|
|
// cursor so its resuming stream_end can finalize the text already
|
|
|
|
|
// shown before the new user row, while starting fresh activity after it.
|
2026-09-20 13:52:43 +08:00
|
|
|
projection = clearThreadProjectionActivity(projection);
|
2026-07-06 10:56:52 +08:00
|
|
|
}
|
2026-07-06 18:23:51 +08:00
|
|
|
const base = finalizeActiveTurn ? finalizeStreamedTurn(prev) : prev;
|
2026-09-20 13:52:43 +08:00
|
|
|
const next: UIMessage[] = [
|
2026-08-24 15:08:22 +08:00
|
|
|
...base,
|
2026-05-17 17:04:57 +08:00
|
|
|
{
|
2026-07-26 00:18:24 +08:00
|
|
|
id: userMessageId,
|
2026-09-20 13:52:43 +08:00
|
|
|
role: "user" as const,
|
2026-07-24 14:19:33 +08:00
|
|
|
content: outboundContent,
|
2026-06-06 19:49:33 +08:00
|
|
|
turnId,
|
|
|
|
|
turnPhase: "user",
|
|
|
|
|
turnSeq: 0,
|
2026-09-20 13:52:43 +08:00
|
|
|
deliveryStatus: "sending" as const,
|
2026-05-17 17:04:57 +08:00
|
|
|
createdAt: Date.now(),
|
2026-07-14 14:47:42 +08:00
|
|
|
...(previews ? { media: previews } : {}),
|
2026-05-22 22:25:12 +08:00
|
|
|
...(options?.cliApps?.length ? { cliApps: options.cliApps } : {}),
|
2026-05-24 13:38:37 +08:00
|
|
|
...(options?.mcpPresets?.length ? { mcpPresets: options.mcpPresets } : {}),
|
2026-08-02 22:04:59 +08:00
|
|
|
...(options?.sessionMentions?.length
|
|
|
|
|
? { sessionMentions: options.sessionMentions }
|
|
|
|
|
: {}),
|
2026-09-20 13:52:43 +08:00
|
|
|
},
|
2026-05-17 17:04:57 +08:00
|
|
|
];
|
2026-09-20 13:52:43 +08:00
|
|
|
projectionRef.current = { ...projection, messages: next };
|
|
|
|
|
return next;
|
2026-05-17 17:04:57 +08:00
|
|
|
});
|
2026-07-06 10:56:52 +08:00
|
|
|
if (!sideChannel) setIsStreaming(true);
|
2026-07-14 14:47:42 +08:00
|
|
|
const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined;
|
2026-07-28 11:40:01 +08:00
|
|
|
const clientOptions = {
|
|
|
|
|
...options,
|
|
|
|
|
turnId,
|
|
|
|
|
...((sideChannel || continueActiveTurn) ? { startsNewRun: false } : {}),
|
|
|
|
|
};
|
|
|
|
|
delete clientOptions.quotedContext;
|
|
|
|
|
delete clientOptions.sideChannel;
|
|
|
|
|
delete clientOptions.finalizeActiveTurn;
|
|
|
|
|
delete clientOptions.continueActiveTurn;
|
2026-10-08 11:55:13 +08:00
|
|
|
const delivery = wireMedia?.length
|
|
|
|
|
? client.sendAttachments(chatId, outboundContent, wireMedia, clientOptions)
|
|
|
|
|
: undefined;
|
|
|
|
|
if (!delivery) client.sendMessage(chatId, outboundContent, undefined, clientOptions);
|
|
|
|
|
// Every caller may keep this promise to retain its draft until accepted.
|
|
|
|
|
// Also observe it here for queued/landing sends without an active composer.
|
|
|
|
|
void delivery?.catch(() => {});
|
|
|
|
|
return { turnId, userMessageId, sideChannel, delivery };
|
2026-04-18 18:51:53 +00:00
|
|
|
},
|
2026-09-21 01:04:31 +08:00
|
|
|
[chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages],
|
2026-04-18 18:51:53 +00:00
|
|
|
);
|
|
|
|
|
|
2026-05-08 09:40:15 +00:00
|
|
|
const stop = useCallback(() => {
|
|
|
|
|
if (!chatId) return;
|
2026-05-17 17:04:57 +08:00
|
|
|
flushPendingStreamEvents();
|
2026-05-08 09:40:15 +00:00
|
|
|
setIsStreaming(false);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-05-17 17:04:57 +08:00
|
|
|
setMessages((prev) => {
|
2026-09-20 13:52:43 +08:00
|
|
|
const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
|
|
|
|
|
projectionRef.current = resetThreadProjectionCursor(projectionRef.current, settled);
|
|
|
|
|
return settled;
|
2026-05-17 17:04:57 +08:00
|
|
|
});
|
2026-08-06 18:29:04 +08:00
|
|
|
setRunStartedAt(null);
|
|
|
|
|
client.finishRunLocally(chatId);
|
2026-05-08 09:40:15 +00:00
|
|
|
client.sendMessage(chatId, "/stop");
|
2026-09-21 01:04:31 +08:00
|
|
|
}, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]);
|
2026-05-08 09:40:15 +00:00
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
const reconcileTurnComplete = useCallback(() => {
|
|
|
|
|
clearPendingStreamWork();
|
2026-10-16 11:38:05 +08:00
|
|
|
projectionRef.current = resetThreadProjectionCursor(projectionRef.current, messagesRef.current);
|
2026-07-28 11:40:01 +08:00
|
|
|
setRunStartedAt(null);
|
2026-09-07 15:12:39 +08:00
|
|
|
setRetryStatus(null);
|
2026-07-28 11:40:01 +08:00
|
|
|
setIsStreaming(false);
|
2026-08-22 19:41:37 +08:00
|
|
|
}, [clearActivitySegment, clearPendingStreamWork]);
|
2026-07-28 11:40:01 +08:00
|
|
|
|
2026-06-09 01:08:49 +08:00
|
|
|
const transcribeAudio = useCallback(
|
|
|
|
|
(dataUrl: string, options?: { durationMs?: number }) =>
|
|
|
|
|
client.transcribeAudio(dataUrl, options),
|
|
|
|
|
[client],
|
|
|
|
|
);
|
|
|
|
|
|
2026-08-22 19:33:22 +08:00
|
|
|
const recoveryAction = useCallback(async (action: "continue" | "dismiss") => {
|
|
|
|
|
if (!chatId || !recoveryState) return;
|
|
|
|
|
await client.requestMutation(`recovery.${action}`, {
|
|
|
|
|
chat_id: chatId,
|
|
|
|
|
recovery_id: recoveryState.recovery_id,
|
|
|
|
|
});
|
|
|
|
|
}, [chatId, client, recoveryState]);
|
|
|
|
|
|
|
|
|
|
const continueRecovery = useCallback(
|
|
|
|
|
() => recoveryAction("continue"),
|
|
|
|
|
[recoveryAction],
|
|
|
|
|
);
|
|
|
|
|
const dismissRecovery = useCallback(
|
|
|
|
|
() => recoveryAction("dismiss"),
|
|
|
|
|
[recoveryAction],
|
|
|
|
|
);
|
|
|
|
|
|
2026-04-21 10:29:47 +00:00
|
|
|
return {
|
|
|
|
|
messages,
|
2026-07-26 00:18:24 +08:00
|
|
|
messagesReady: messageOwnerChatId === chatId,
|
2026-04-21 10:29:47 +00:00
|
|
|
isStreaming,
|
2026-05-16 01:14:11 +08:00
|
|
|
runStartedAt,
|
2026-09-07 15:12:39 +08:00
|
|
|
retryStatus,
|
2026-05-16 01:14:11 +08:00
|
|
|
goalState,
|
2026-08-22 19:33:22 +08:00
|
|
|
recoveryState,
|
|
|
|
|
continueRecovery,
|
|
|
|
|
dismissRecovery,
|
2026-04-21 10:29:47 +00:00
|
|
|
send,
|
2026-06-09 01:08:49 +08:00
|
|
|
transcribeAudio,
|
2026-05-08 09:40:15 +00:00
|
|
|
stop,
|
2026-07-28 11:40:01 +08:00
|
|
|
reconcileTurnComplete,
|
2026-04-21 10:29:47 +00:00
|
|
|
setMessages,
|
|
|
|
|
streamError,
|
|
|
|
|
dismissStreamError,
|
|
|
|
|
};
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|