perf(webui): reduce repeated work and bound history rendering (#5703)
* perf(webui): reduce repeated work and bound history rendering * fix(webui): keep continuation reasoning with its answer * refactor(webui): reuse answer buffers and prepared copy text * perf(webui): restore conditional replay buffer initialization * fix(webui): remove code block pagination
This commit is contained in:
1 parent
1c451b5b5f
commit
1469d4811c
32 files changed
+1156
-361
No files matched your search
@@ -1720,6 +1720,7 @@ def replay_transcript_to_ui_messages(
|
|||||||
messages: list[dict[str, Any]] = []
|
messages: list[dict[str, Any]] = []
|
||||||
buffer_message_id: str | None = None
|
buffer_message_id: str | None = None
|
||||||
buffer_parts: list[str] = []
|
buffer_parts: list[str] = []
|
||||||
|
merge_reasoning_message_id: str | None = None
|
||||||
suppress_until_turn_end = False
|
suppress_until_turn_end = False
|
||||||
active_activity_segment_id: str | None = None
|
active_activity_segment_id: str | None = None
|
||||||
active_file_edit_segment_id: str | None = None
|
active_file_edit_segment_id: str | None = None
|
||||||
@@ -1816,6 +1817,26 @@ def replay_transcript_to_ui_messages(
|
|||||||
created_at_ms: int | None = None,
|
created_at_ms: int | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
turn_fields = turn_fields or {}
|
turn_fields = turn_fields or {}
|
||||||
|
if buffer_message_id is not None and buffer_message_id == merge_reasoning_message_id:
|
||||||
|
for i in range(len(prev) - 1, -1, -1):
|
||||||
|
candidate = prev[i]
|
||||||
|
if candidate.get("id") != buffer_message_id:
|
||||||
|
continue
|
||||||
|
if _same_turn(candidate, turn_fields):
|
||||||
|
# A length continuation shares the same Markdown answer.
|
||||||
|
# Keep its reasoning with that answer, including on replay.
|
||||||
|
reasoning = str(candidate.get("reasoning") or "")
|
||||||
|
separator = "\n\n" if reasoning and not candidate.get("reasoningStreaming") else ""
|
||||||
|
prev[i] = {
|
||||||
|
**candidate,
|
||||||
|
"reasoning": reasoning + separator + chunk,
|
||||||
|
"reasoningStreaming": True,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
break
|
||||||
|
if buffer_message_id is not None:
|
||||||
|
close_interrupted_assistant()
|
||||||
|
close_activity_for_answer()
|
||||||
for i in range(len(prev) - 1, -1, -1):
|
for i in range(len(prev) - 1, -1, -1):
|
||||||
candidate = prev[i]
|
candidate = prev[i]
|
||||||
if candidate.get("role") == "user":
|
if candidate.get("role") == "user":
|
||||||
@@ -1882,7 +1903,7 @@ def replay_transcript_to_ui_messages(
|
|||||||
return str(last.get("id"))
|
return str(last.get("id"))
|
||||||
|
|
||||||
def close_interrupted_assistant() -> None:
|
def close_interrupted_assistant() -> None:
|
||||||
"""Close an answer segment before tool activity without changing its semantics.
|
"""Close an answer before a new activity phase without changing its semantics.
|
||||||
|
|
||||||
The wire protocol already marks answer, reasoning, and activity phases.
|
The wire protocol already marks answer, reasoning, and activity phases.
|
||||||
A later tool event does not turn previously emitted answer text into
|
A later tool event does not turn previously emitted answer text into
|
||||||
@@ -1910,6 +1931,20 @@ def replay_transcript_to_ui_messages(
|
|||||||
buffer_parts = []
|
buffer_parts = []
|
||||||
return
|
return
|
||||||
|
|
||||||
|
def close_buffer_from_other_turn(turn_fields: dict[str, Any]) -> None:
|
||||||
|
nonlocal buffer_message_id, buffer_parts
|
||||||
|
if buffer_message_id is None:
|
||||||
|
return
|
||||||
|
for message in reversed(messages):
|
||||||
|
if message.get("id") != buffer_message_id:
|
||||||
|
continue
|
||||||
|
if not _same_turn(message, turn_fields):
|
||||||
|
message["isStreaming"] = False
|
||||||
|
buffer_message_id = None
|
||||||
|
buffer_parts = []
|
||||||
|
close_activity_for_answer()
|
||||||
|
return
|
||||||
|
|
||||||
def close_reasoning(prev: list[dict[str, Any]]) -> None:
|
def close_reasoning(prev: list[dict[str, Any]]) -> None:
|
||||||
for i in range(len(prev) - 1, -1, -1):
|
for i in range(len(prev) - 1, -1, -1):
|
||||||
if prev[i].get("reasoningStreaming"):
|
if prev[i].get("reasoningStreaming"):
|
||||||
@@ -2211,6 +2246,7 @@ def replay_transcript_to_ui_messages(
|
|||||||
close_activity_for_answer()
|
close_activity_for_answer()
|
||||||
turn_fields = _turn_fields(rec, "answer")
|
turn_fields = _turn_fields(rec, "answer")
|
||||||
source_fields = _source_fields(rec)
|
source_fields = _source_fields(rec)
|
||||||
|
close_buffer_from_other_turn(turn_fields)
|
||||||
adopted = find_active_placeholder(messages, turn_fields) if buffer_message_id is None else None
|
adopted = find_active_placeholder(messages, turn_fields) if buffer_message_id is None else None
|
||||||
if buffer_message_id is None:
|
if buffer_message_id is None:
|
||||||
if adopted:
|
if adopted:
|
||||||
@@ -2251,6 +2287,7 @@ def replay_transcript_to_ui_messages(
|
|||||||
final_text = rec.get("text")
|
final_text = rec.get("text")
|
||||||
turn_fields = _turn_fields(rec, "answer")
|
turn_fields = _turn_fields(rec, "answer")
|
||||||
source_fields = _source_fields(rec)
|
source_fields = _source_fields(rec)
|
||||||
|
close_buffer_from_other_turn(turn_fields)
|
||||||
if isinstance(final_text, str):
|
if isinstance(final_text, str):
|
||||||
if buffer_message_id is None:
|
if buffer_message_id is None:
|
||||||
buffer_message_id = find_active_placeholder(messages, turn_fields)
|
buffer_message_id = find_active_placeholder(messages, turn_fields)
|
||||||
@@ -2287,6 +2324,7 @@ def replay_transcript_to_ui_messages(
|
|||||||
if not merge_next:
|
if not merge_next:
|
||||||
buffer_message_id = None
|
buffer_message_id = None
|
||||||
buffer_parts = []
|
buffer_parts = []
|
||||||
|
merge_reasoning_message_id = buffer_message_id if merge_next else None
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if ev == "reasoning_delta":
|
if ev == "reasoning_delta":
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
import nanobot.webui.transcript as transcript_module
|
import nanobot.webui.transcript as transcript_module
|
||||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||||
from nanobot.webui.transcript import (
|
from nanobot.webui.transcript import (
|
||||||
@@ -1700,6 +1702,34 @@ def test_replay_merges_length_recovery_segments_into_one_assistant_message() ->
|
|||||||
assert msgs[0]["content"] == "first second"
|
assert msgs[0]["content"] == "first second"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("event", ["delta", "stream_end"])
|
||||||
|
def test_replay_recovery_answer_does_not_overwrite_an_unfinished_turn(event: str) -> None:
|
||||||
|
msgs = replay_transcript_to_ui_messages([
|
||||||
|
{
|
||||||
|
"event": "stream_end", "text": "Original answer", "turn_id": "original",
|
||||||
|
"resuming": True, "merge_next": True,
|
||||||
|
},
|
||||||
|
{"event": event, "text": "Recovered answer", "turn_id": "recovery"},
|
||||||
|
{"event": "turn_end", "turn_id": "recovery"},
|
||||||
|
])
|
||||||
|
|
||||||
|
assert [(m["turnId"], m["content"]) for m in msgs] == [
|
||||||
|
("original", "Original answer"), ("recovery", "Recovered answer"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_replay_reasoning_after_an_ordinary_answer_preserves_the_answer_boundary() -> None:
|
||||||
|
msgs = replay_transcript_to_ui_messages([
|
||||||
|
{"event": "delta", "text": "First answer"},
|
||||||
|
{"event": "reasoning_end", "text": "Consider the next answer"},
|
||||||
|
{"event": "stream_end", "text": "Next answer"},
|
||||||
|
{"event": "turn_end"},
|
||||||
|
])
|
||||||
|
|
||||||
|
assert [m["content"] for m in msgs] == ["First answer", "Next answer"]
|
||||||
|
assert msgs[1]["reasoning"] == "Consider the next answer"
|
||||||
|
|
||||||
|
|
||||||
def test_replay_tool_events_dedupes_finish_after_start() -> None:
|
def test_replay_tool_events_dedupes_finish_after_start() -> None:
|
||||||
msgs = replay_transcript_to_ui_messages([
|
msgs = replay_transcript_to_ui_messages([
|
||||||
{
|
{
|
||||||
|
|||||||
+136
-129
@@ -14,7 +14,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry";
|
|||||||
import { Sidebar } from "@/components/Sidebar";
|
import { Sidebar } from "@/components/Sidebar";
|
||||||
import type { SidebarDeleteItem } from "@/components/ChatList";
|
import type { SidebarDeleteItem } from "@/components/ChatList";
|
||||||
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
|
||||||
import { ThreadShell } from "@/components/thread/ThreadShell";
|
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||||
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
|
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
|
||||||
import {
|
import {
|
||||||
MAX_WORKBENCH_PANES,
|
MAX_WORKBENCH_PANES,
|
||||||
@@ -123,6 +123,9 @@ type ShellRoute = {
|
|||||||
settingsSection: SettingsSectionKey;
|
settingsSection: SettingsSectionKey;
|
||||||
temporary?: boolean;
|
temporary?: boolean;
|
||||||
};
|
};
|
||||||
|
const ThreadShell = lazy(() => import("@/components/thread/ThreadShell").then(
|
||||||
|
(module) => ({ default: module.ThreadShell }),
|
||||||
|
));
|
||||||
const loadSettingsView = () => import("@/components/settings/SettingsView");
|
const loadSettingsView = () => import("@/components/settings/SettingsView");
|
||||||
const SettingsView = lazy(async () => {
|
const SettingsView = lazy(async () => {
|
||||||
const module = await loadSettingsView();
|
const module = await loadSettingsView();
|
||||||
@@ -141,14 +144,14 @@ const RenameChatDialog = lazy(async () => {
|
|||||||
return { default: module.RenameChatDialog };
|
return { default: module.RenameChatDialog };
|
||||||
});
|
});
|
||||||
|
|
||||||
function SurfaceLoadingFallback() {
|
function SurfaceLoadingFallback({ label }: { label?: string }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
aria-busy="true"
|
aria-busy="true"
|
||||||
className="flex h-full w-full flex-col gap-5 px-5 py-8 sm:px-8 lg:px-12"
|
className="flex h-full w-full flex-col gap-5 px-5 py-8 sm:px-8 lg:px-12"
|
||||||
>
|
>
|
||||||
<span className="sr-only">{t("settings.status.loading")}</span>
|
<span className="sr-only">{label ?? t("settings.status.loading")}</span>
|
||||||
<div className="h-4 w-20 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
|
<div className="h-4 w-20 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
|
||||||
<div className="h-9 w-48 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
|
<div className="h-9 w-48 animate-pulse rounded bg-muted/70 motion-reduce:animate-none" />
|
||||||
<div className="mt-4 h-12 w-full max-w-3xl animate-pulse rounded-md bg-muted/55 motion-reduce:animate-none" />
|
<div className="mt-4 h-12 w-full max-w-3xl animate-pulse rounded-md bg-muted/55 motion-reduce:animate-none" />
|
||||||
@@ -2617,133 +2620,137 @@ function Shell({
|
|||||||
view !== "chat" && "hidden",
|
view !== "chat" && "hidden",
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<PaneWorkbench
|
<ThreadVisibilityContext.Provider value={view === "chat"}>
|
||||||
panes={renderedWorkbenchPanes}
|
<Suspense fallback={<SurfaceLoadingFallback label={t("chat.loading")} />}>
|
||||||
activePaneKey={renderedActivePaneKey}
|
<PaneWorkbench
|
||||||
layout={renderedWorkbenchLayout}
|
panes={renderedWorkbenchPanes}
|
||||||
splitRatios={renderedWorkbenchSplitRatios}
|
activePaneKey={renderedActivePaneKey}
|
||||||
chrome={paneChromeEnabled}
|
layout={renderedWorkbenchLayout}
|
||||||
showLayoutControl={activeTabVisible}
|
splitRatios={renderedWorkbenchSplitRatios}
|
||||||
addPaneDisabled={creatingPane || activePaneLimitReached}
|
chrome={paneChromeEnabled}
|
||||||
addPaneDisabledLabel={activePaneLimitReached
|
showLayoutControl={activeTabVisible}
|
||||||
? t("workbench.paneLimit", {
|
addPaneDisabled={creatingPane || activePaneLimitReached}
|
||||||
count: MAX_WORKBENCH_PANES,
|
addPaneDisabledLabel={activePaneLimitReached
|
||||||
})
|
? t("workbench.paneLimit", {
|
||||||
: undefined}
|
count: MAX_WORKBENCH_PANES,
|
||||||
onActivatePane={onActivateWorkbenchPane}
|
})
|
||||||
onAddPane={onAddPane}
|
: undefined}
|
||||||
onLayoutChange={(layout) => {
|
onActivatePane={onActivateWorkbenchPane}
|
||||||
if (!activeTabKey) return;
|
onAddPane={onAddPane}
|
||||||
updateWorkbenchState((current) => (
|
onLayoutChange={(layout) => {
|
||||||
setWorkbenchLayout(current, activeTabKey, layout)
|
if (!activeTabKey) return;
|
||||||
));
|
updateWorkbenchState((current) => (
|
||||||
}}
|
setWorkbenchLayout(current, activeTabKey, layout)
|
||||||
onPaneOrderChange={(paneKeys) => {
|
));
|
||||||
if (!activeTabKey) return;
|
}}
|
||||||
updateWorkbenchState((current) => (
|
onPaneOrderChange={(paneKeys) => {
|
||||||
setWorkbenchPaneLayoutOrder(current, activeTabKey, paneKeys)
|
if (!activeTabKey) return;
|
||||||
));
|
updateWorkbenchState((current) => (
|
||||||
}}
|
setWorkbenchPaneLayoutOrder(current, activeTabKey, paneKeys)
|
||||||
onSplitRatiosChange={(splitRatios) => {
|
));
|
||||||
if (!activeTabKey) return;
|
}}
|
||||||
updateWorkbenchState((current) => (
|
onSplitRatiosChange={(splitRatios) => {
|
||||||
setWorkbenchSplitRatios(current, activeTabKey, splitRatios)
|
if (!activeTabKey) return;
|
||||||
));
|
updateWorkbenchState((current) => (
|
||||||
}}
|
setWorkbenchSplitRatios(current, activeTabKey, splitRatios)
|
||||||
renderPane={(pane, context) => {
|
));
|
||||||
if (!paneChromeEnabled) {
|
}}
|
||||||
return (
|
renderPane={(pane, context) => {
|
||||||
<ThreadShell
|
if (!paneChromeEnabled) {
|
||||||
session={activeSession}
|
return (
|
||||||
sessions={sessions}
|
<ThreadShell
|
||||||
title={headerTitle}
|
session={activeSession}
|
||||||
temporary={temporaryChatRequested}
|
sessions={sessions}
|
||||||
temporaryChatIds={temporaryChatIds}
|
title={headerTitle}
|
||||||
temporaryChatEnabled={temporaryChatEnabled}
|
temporary={temporaryChatRequested}
|
||||||
onTemporaryChatEnabledChange={
|
temporaryChatIds={temporaryChatIds}
|
||||||
!activeKey ? onTemporaryChatEnabledChange : undefined
|
temporaryChatEnabled={temporaryChatEnabled}
|
||||||
}
|
onTemporaryChatEnabledChange={
|
||||||
onToggleSidebar={toggleSidebar}
|
!activeKey ? onTemporaryChatEnabledChange : undefined
|
||||||
onNewChat={onNewChat}
|
}
|
||||||
onCreateChat={
|
onToggleSidebar={toggleSidebar}
|
||||||
temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat
|
onNewChat={onNewChat}
|
||||||
}
|
onCreateChat={
|
||||||
onForkChat={temporaryChatActive ? undefined : onForkChat}
|
temporaryChatEnabled ? onCreateTemporaryChat : onCreateChat
|
||||||
onTurnEnd={onTurnEnd}
|
}
|
||||||
theme={theme}
|
onForkChat={temporaryChatActive ? undefined : onForkChat}
|
||||||
onToggleTheme={toggle}
|
onTurnEnd={onTurnEnd}
|
||||||
hideSidebarToggleForHostChrome
|
theme={theme}
|
||||||
hideHeader={false}
|
onToggleTheme={toggle}
|
||||||
workspaceScope={activeWorkspaceScope}
|
hideSidebarToggleForHostChrome
|
||||||
workspaceDefaultScope={workspaces?.default_scope ?? null}
|
hideHeader={false}
|
||||||
workspaceControls={workspaces?.controls ?? null}
|
workspaceScope={activeWorkspaceScope}
|
||||||
workspaceScopeDisabled={activeChatRunning}
|
workspaceDefaultScope={workspaces?.default_scope ?? null}
|
||||||
workspaceError={workspaceError}
|
workspaceControls={workspaces?.controls ?? null}
|
||||||
onWorkspaceScopeChange={applyWorkspaceScope}
|
workspaceScopeDisabled={activeChatRunning}
|
||||||
settingsSnapshot={settingsSnapshot}
|
workspaceError={workspaceError}
|
||||||
onOpenModelSettings={onOpenModelSettings}
|
onWorkspaceScopeChange={applyWorkspaceScope}
|
||||||
skills={skills}
|
settingsSnapshot={settingsSnapshot}
|
||||||
/>
|
onOpenModelSettings={onOpenModelSettings}
|
||||||
);
|
skills={skills}
|
||||||
}
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const paneSession = workbenchPaneSessions.find(
|
const paneSession = workbenchPaneSessions.find(
|
||||||
(session) => session.key === pane.key,
|
(session) => session.key === pane.key,
|
||||||
);
|
);
|
||||||
if (!paneSession) return null;
|
if (!paneSession) return null;
|
||||||
const paneScope = workspaceOverrides[paneSession.chatId]
|
const paneScope = workspaceOverrides[paneSession.chatId]
|
||||||
?? paneSession.workspaceScope
|
?? paneSession.workspaceScope
|
||||||
?? workspaces?.default_scope
|
?? workspaces?.default_scope
|
||||||
?? null;
|
?? null;
|
||||||
const paneRunning = runningChatIds.has(paneSession.chatId);
|
const paneRunning = runningChatIds.has(paneSession.chatId);
|
||||||
return (
|
return (
|
||||||
<ThreadShell
|
<ThreadShell
|
||||||
session={paneSession}
|
session={paneSession}
|
||||||
sessions={sessions}
|
sessions={sessions}
|
||||||
title={pane.title}
|
title={pane.title}
|
||||||
onToggleSidebar={toggleSidebar}
|
onToggleSidebar={toggleSidebar}
|
||||||
onNewChat={onNewChat}
|
onNewChat={onNewChat}
|
||||||
onCreateChat={onCreateChat}
|
onCreateChat={onCreateChat}
|
||||||
onForkChat={onForkChat}
|
onForkChat={onForkChat}
|
||||||
onTurnEnd={context.active ? onTurnEnd : () => void refresh()}
|
onTurnEnd={context.active ? onTurnEnd : () => void refresh()}
|
||||||
theme={theme}
|
theme={theme}
|
||||||
onToggleTheme={toggle}
|
onToggleTheme={toggle}
|
||||||
hideSidebarToggle={!context.active}
|
hideSidebarToggle={!context.active}
|
||||||
hideSidebarToggleForHostChrome={context.active}
|
hideSidebarToggleForHostChrome={context.active}
|
||||||
hideThemeButton={!context.active}
|
hideThemeButton={!context.active}
|
||||||
hideHeaderTitle
|
hideHeaderTitle
|
||||||
inlineHandle={workbenchPaneSessions.length > 1}
|
inlineHandle={workbenchPaneSessions.length > 1}
|
||||||
headerActions={context.headerActions}
|
headerActions={context.headerActions}
|
||||||
headerPortalTarget={context.headerPortalTarget}
|
headerPortalTarget={context.headerPortalTarget}
|
||||||
headerActive={context.active}
|
headerActive={context.active}
|
||||||
composerPortalTarget={context.composerPortalTarget}
|
composerPortalTarget={context.composerPortalTarget}
|
||||||
composerActive={context.active}
|
composerActive={context.active}
|
||||||
composerInputAriaLabel={t("workbench.composerAria", {
|
composerInputAriaLabel={t("workbench.composerAria", {
|
||||||
title: pane.title,
|
title: pane.title,
|
||||||
})}
|
})}
|
||||||
emptyComposerVariant="thread"
|
emptyComposerVariant="thread"
|
||||||
workspaceScope={paneScope}
|
workspaceScope={paneScope}
|
||||||
workspaceDefaultScope={workspaces?.default_scope ?? null}
|
workspaceDefaultScope={workspaces?.default_scope ?? null}
|
||||||
workspaceControls={workspaces?.controls ?? null}
|
workspaceControls={workspaces?.controls ?? null}
|
||||||
workspaceScopeDisabled={paneRunning}
|
workspaceScopeDisabled={paneRunning}
|
||||||
workspaceError={context.active ? workspaceError : null}
|
workspaceError={context.active ? workspaceError : null}
|
||||||
onWorkspaceScopeChange={(scope) => {
|
onWorkspaceScopeChange={(scope) => {
|
||||||
if (paneRunning) return;
|
if (paneRunning) return;
|
||||||
const next = normalizeWorkspaceScope(scope);
|
const next = normalizeWorkspaceScope(scope);
|
||||||
setWorkspaceError(null);
|
setWorkspaceError(null);
|
||||||
setWorkspaceOverrides((current) => ({
|
setWorkspaceOverrides((current) => ({
|
||||||
...current,
|
...current,
|
||||||
[paneSession.chatId]: next,
|
[paneSession.chatId]: next,
|
||||||
}));
|
}));
|
||||||
client.setWorkspaceScope(paneSession.chatId, next);
|
client.setWorkspaceScope(paneSession.chatId, next);
|
||||||
}}
|
}}
|
||||||
settingsSnapshot={settingsSnapshot}
|
settingsSnapshot={settingsSnapshot}
|
||||||
onOpenModelSettings={onOpenModelSettings}
|
onOpenModelSettings={onOpenModelSettings}
|
||||||
skills={skills}
|
skills={skills}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
</Suspense>
|
||||||
|
</ThreadVisibilityContext.Provider>
|
||||||
</div>
|
</div>
|
||||||
{view !== "chat" && (
|
{view !== "chat" && (
|
||||||
<div className="absolute inset-0 flex flex-col">
|
<div className="absolute inset-0 flex flex-col">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Suspense, lazy, useCallback, useState, type ReactNode } from "react";
|
import { Suspense, lazy, useCallback, useMemo, useState, type ReactNode } from "react";
|
||||||
import { Check, Copy } from "lucide-react";
|
import { Check, Copy } from "lucide-react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -138,7 +138,7 @@ function CodeTextBlock({
|
|||||||
className?: string;
|
className?: string;
|
||||||
renderText?: (value: string) => ReactNode;
|
renderText?: (value: string) => ReactNode;
|
||||||
}) {
|
}) {
|
||||||
const lines = code.split("\n");
|
const lines = showLineNumbers ? code.split("\n") : [];
|
||||||
return (
|
return (
|
||||||
<pre
|
<pre
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -184,19 +184,20 @@ export function CodeBlock({
|
|||||||
}: CodeBlockProps) {
|
}: CodeBlockProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
|
const renderAnsi = useMemo(() => shouldRenderAnsi(language, code), [language, code]);
|
||||||
|
const plainCode = useMemo(() => renderAnsi ? stripAnsi(code) : code, [renderAnsi, code]);
|
||||||
const isDark = useThemeValue() === "dark";
|
const isDark = useThemeValue() === "dark";
|
||||||
const hasChrome = chrome === "default";
|
const hasChrome = chrome === "default";
|
||||||
const renderAnsi = shouldRenderAnsi(language, code);
|
|
||||||
const syntaxLanguage = normalizeCodeLanguage(language);
|
const syntaxLanguage = normalizeCodeLanguage(language);
|
||||||
const copyLabel = copied ? t("code.copied") : t("code.copyAria");
|
const copyLabel = copied ? t("code.copied") : t("code.copyAria");
|
||||||
|
|
||||||
const onCopy = useCallback(() => {
|
const onCopy = useCallback(() => {
|
||||||
void copyTextToClipboard(renderAnsi ? stripAnsi(code) : code).then((ok) => {
|
void copyTextToClipboard(plainCode).then((ok) => {
|
||||||
if (!ok) return;
|
if (!ok) return;
|
||||||
setCopied(true);
|
setCopied(true);
|
||||||
setTimeout(() => setCopied(false), 1_500);
|
setTimeout(() => setCopied(false), 1_500);
|
||||||
});
|
});
|
||||||
}, [code, renderAnsi]);
|
}, [plainCode]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
type ReactNode,
|
type ReactNode,
|
||||||
} from "react";
|
} from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import rehypeKatex from "rehype-katex";
|
|
||||||
import { Check, Globe2 } from "lucide-react";
|
import { Check, Globe2 } from "lucide-react";
|
||||||
import remarkBreaks from "remark-breaks";
|
import remarkBreaks from "remark-breaks";
|
||||||
import remarkGfm from "remark-gfm";
|
import remarkGfm from "remark-gfm";
|
||||||
@@ -35,7 +34,6 @@ import { browserSafeFaviconUrls } from "@/lib/provider-brand";
|
|||||||
import { remarkTexMath } from "@/lib/remark-tex-math";
|
import { remarkTexMath } from "@/lib/remark-tex-math";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
import "katex/dist/katex.min.css";
|
|
||||||
import "streamdown/styles.css";
|
import "streamdown/styles.css";
|
||||||
|
|
||||||
interface MarkdownTextRendererProps {
|
interface MarkdownTextRendererProps {
|
||||||
@@ -285,7 +283,19 @@ const remarkPlugins: NonNullable<StreamdownProps["remarkPlugins"]> = [
|
|||||||
remarkCjkStrongBoundaries,
|
remarkCjkStrongBoundaries,
|
||||||
remarkSafeHtmlSubset,
|
remarkSafeHtmlSubset,
|
||||||
];
|
];
|
||||||
const rehypePlugins: NonNullable<StreamdownProps["rehypePlugins"]> = [rehypeKatex];
|
type MathPlugin = typeof import("@/lib/markdown-math").default;
|
||||||
|
let loadedMathPlugin: MathPlugin | undefined;
|
||||||
|
let mathPluginPromise: Promise<MathPlugin> | undefined;
|
||||||
|
|
||||||
|
function loadMathPlugin(): Promise<MathPlugin> {
|
||||||
|
return mathPluginPromise ??= import("@/lib/markdown-math").then((module) => {
|
||||||
|
loadedMathPlugin = module.default;
|
||||||
|
return module.default;
|
||||||
|
}).catch((error) => {
|
||||||
|
mathPluginPromise = undefined;
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Remend mistakes math comparisons like `j<i` for incomplete HTML and truncates
|
// Remend mistakes math comparisons like `j<i` for incomplete HTML and truncates
|
||||||
// the remaining text. HTML is handled by remarkSafeHtmlSubset, not raw rendering.
|
// the remaining text. HTML is handled by remarkSafeHtmlSubset, not raw rendering.
|
||||||
@@ -522,6 +532,20 @@ export default function MarkdownTextRenderer({
|
|||||||
onOpenFilePreview,
|
onOpenFilePreview,
|
||||||
}: MarkdownTextRendererProps) {
|
}: MarkdownTextRendererProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const [mathPlugin, setMathPlugin] = useState(() => loadedMathPlugin);
|
||||||
|
const needsMath = /\$|\\[([]/.test(children);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!needsMath || mathPlugin) return;
|
||||||
|
let cancelled = false;
|
||||||
|
void loadMathPlugin().then((plugin) => {
|
||||||
|
if (!cancelled) setMathPlugin(() => plugin);
|
||||||
|
}).catch(() => {});
|
||||||
|
return () => { cancelled = true; };
|
||||||
|
}, [needsMath, mathPlugin]);
|
||||||
|
const rehypePlugins = useMemo<NonNullable<StreamdownProps["rehypePlugins"]>>(
|
||||||
|
() => needsMath && mathPlugin ? [mathPlugin] : [],
|
||||||
|
[needsMath, mathPlugin],
|
||||||
|
);
|
||||||
const components = useMemo<Components>(
|
const components = useMemo<Components>(
|
||||||
() => ({
|
() => ({
|
||||||
code({ className: cls, children: kids, node: _node, ...props }) {
|
code({ className: cls, children: kids, node: _node, ...props }) {
|
||||||
@@ -798,6 +822,7 @@ export default function MarkdownTextRenderer({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<Streamdown
|
<Streamdown
|
||||||
|
key={needsMath && mathPlugin ? "math" : "text"}
|
||||||
mode={streaming ? "streaming" : "static"}
|
mode={streaming ? "streaming" : "static"}
|
||||||
parseIncompleteMarkdown
|
parseIncompleteMarkdown
|
||||||
remend={REMEND_OPTIONS}
|
remend={REMEND_OPTIONS}
|
||||||
|
|||||||
@@ -22,31 +22,42 @@ interface SessionSearchDialogProps {
|
|||||||
onSelect: (key: string) => void;
|
onSelect: (key: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};
|
||||||
|
|
||||||
export function SessionSearchDialog({
|
export function SessionSearchDialog({
|
||||||
open,
|
open,
|
||||||
sessions,
|
sessions,
|
||||||
activeKey,
|
activeKey,
|
||||||
loading,
|
loading,
|
||||||
titleOverrides = {},
|
titleOverrides = EMPTY_TITLE_OVERRIDES,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
onSelect,
|
onSelect,
|
||||||
}: SessionSearchDialogProps) {
|
}: SessionSearchDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const scrollRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [scrollTop, setScrollTop] = useState(0);
|
||||||
const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const [highlightedIndex, setHighlightedIndex] = useState(0);
|
const [highlightedIndex, setHighlightedIndex] = useState(0);
|
||||||
|
|
||||||
const normalizedQuery = query.trim().toLowerCase();
|
const normalizedQuery = query.trim().toLowerCase();
|
||||||
|
const searchableSessions = useMemo(() => sessions.map((session) => ({
|
||||||
|
session,
|
||||||
|
text: [titleOverrides[session.key], session.title, visibleSessionPreview(session.preview)]
|
||||||
|
.filter(Boolean).join(" ").toLowerCase(),
|
||||||
|
})), [sessions, titleOverrides]);
|
||||||
const sessionResults = useMemo(() => {
|
const sessionResults = useMemo(() => {
|
||||||
if (!open) return [];
|
if (!open) return [];
|
||||||
if (!normalizedQuery) return sessions;
|
if (!normalizedQuery) return sessions;
|
||||||
const terms = normalizedQuery.split(/\s+/).filter(Boolean);
|
const terms = normalizedQuery.split(/\s+/).filter(Boolean);
|
||||||
return sessions.filter((session) =>
|
return searchableSessions.filter(({ text }) => terms.every((term) => text.includes(term)))
|
||||||
sessionMatchesTerms(session, terms, titleOverrides[session.key]),
|
.map(({ session }) => session);
|
||||||
);
|
}, [normalizedQuery, open, sessions, searchableSessions]);
|
||||||
}, [normalizedQuery, open, sessions, titleOverrides]);
|
|
||||||
const itemCount = sessionResults.length;
|
const itemCount = sessionResults.length;
|
||||||
|
const rowHeight = 64;
|
||||||
|
const windowStart = Math.max(0, Math.min(itemCount - 1, Math.floor(scrollTop / rowHeight) - 4));
|
||||||
|
const windowEnd = Math.min(itemCount, windowStart + 24);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
@@ -57,6 +68,8 @@ export function SessionSearchDialog({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setHighlightedIndex(0);
|
setHighlightedIndex(0);
|
||||||
|
setScrollTop(0);
|
||||||
|
if (scrollRef.current) scrollRef.current.scrollTop = 0;
|
||||||
}, [normalizedQuery]);
|
}, [normalizedQuery]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -71,6 +84,14 @@ export function SessionSearchDialog({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!open) return;
|
if (!open) return;
|
||||||
|
const scroller = scrollRef.current;
|
||||||
|
if (scroller) {
|
||||||
|
const top = highlightedIndex * rowHeight;
|
||||||
|
if (top < scroller.scrollTop || top + rowHeight > scroller.scrollTop + scroller.clientHeight) {
|
||||||
|
scroller.scrollTop = top;
|
||||||
|
setScrollTop(top);
|
||||||
|
}
|
||||||
|
}
|
||||||
itemRefs.current[highlightedIndex]?.scrollIntoView({
|
itemRefs.current[highlightedIndex]?.scrollIntoView({
|
||||||
block: "nearest",
|
block: "nearest",
|
||||||
inline: "nearest",
|
inline: "nearest",
|
||||||
@@ -143,6 +164,8 @@ export function SessionSearchDialog({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
|
ref={scrollRef}
|
||||||
|
onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
|
||||||
data-testid="session-search-scroll"
|
data-testid="session-search-scroll"
|
||||||
className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
|
className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"
|
||||||
>
|
>
|
||||||
@@ -160,8 +183,10 @@ export function SessionSearchDialog({
|
|||||||
{emptyLabel}
|
{emptyLabel}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<ul className="space-y-0.5">
|
<ul>
|
||||||
{sessionResults.map((session, index) => {
|
<li aria-hidden style={{ height: windowStart * rowHeight }} />
|
||||||
|
{sessionResults.slice(windowStart, windowEnd).map((session, offset) => {
|
||||||
|
const index = windowStart + offset;
|
||||||
const title = titleOverrides[session.key]?.trim() ||
|
const title = titleOverrides[session.key]?.trim() ||
|
||||||
session.title?.trim() ||
|
session.title?.trim() ||
|
||||||
deriveTitle(session.preview, t("chat.newChat"));
|
deriveTitle(session.preview, t("chat.newChat"));
|
||||||
@@ -172,7 +197,7 @@ export function SessionSearchDialog({
|
|||||||
const highlighted = index === highlightedIndex;
|
const highlighted = index === highlightedIndex;
|
||||||
const active = session.key === activeKey;
|
const active = session.key === activeKey;
|
||||||
return (
|
return (
|
||||||
<li key={session.key}>
|
<li key={session.key} style={{ height: rowHeight }}>
|
||||||
<button
|
<button
|
||||||
ref={(node) => {
|
ref={(node) => {
|
||||||
itemRefs.current[index] = node;
|
itemRefs.current[index] = node;
|
||||||
@@ -182,7 +207,7 @@ export function SessionSearchDialog({
|
|||||||
onMouseEnter={() => setHighlightedIndex(index)}
|
onMouseEnter={() => setHighlightedIndex(index)}
|
||||||
aria-current={active ? "page" : undefined}
|
aria-current={active ? "page" : undefined}
|
||||||
className={cn(
|
className={cn(
|
||||||
"grid min-h-[54px] w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-control px-3 py-2 text-left transition-colors",
|
"grid h-full w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-control px-3 py-2 text-left transition-colors",
|
||||||
highlighted
|
highlighted
|
||||||
? "bg-muted text-foreground"
|
? "bg-muted text-foreground"
|
||||||
: "text-foreground hover:bg-muted",
|
: "text-foreground hover:bg-muted",
|
||||||
@@ -209,6 +234,7 @@ export function SessionSearchDialog({
|
|||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
<li aria-hidden style={{ height: (itemCount - windowEnd) * rowHeight }} />
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
@@ -217,20 +243,3 @@ export function SessionSearchDialog({
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function sessionMatchesTerms(
|
|
||||||
session: ChatSummary,
|
|
||||||
terms: string[],
|
|
||||||
titleOverride?: string,
|
|
||||||
) {
|
|
||||||
const haystack = [
|
|
||||||
titleOverride,
|
|
||||||
session.title,
|
|
||||||
visibleSessionPreview(session.preview),
|
|
||||||
]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(" ")
|
|
||||||
.toLowerCase();
|
|
||||||
|
|
||||||
return terms.every((term) => haystack.includes(term));
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
Fragment,
|
Fragment,
|
||||||
|
memo,
|
||||||
useCallback,
|
useCallback,
|
||||||
useEffect,
|
useEffect,
|
||||||
useLayoutEffect,
|
useLayoutEffect,
|
||||||
@@ -53,6 +54,7 @@ import {
|
|||||||
import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";
|
import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";
|
||||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||||
|
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||||
import type { FileEditDisplayMode } from "@/lib/local-preferences";
|
import type { FileEditDisplayMode } from "@/lib/local-preferences";
|
||||||
import { logoFallbackUrls } from "@/lib/provider-brand";
|
import { logoFallbackUrls } from "@/lib/provider-brand";
|
||||||
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
|
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
|
||||||
@@ -67,6 +69,8 @@ import type {
|
|||||||
} from "@/lib/types";
|
} from "@/lib/types";
|
||||||
|
|
||||||
const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
|
const ACTIVITY_SCROLL_NEAR_BOTTOM_PX = 24;
|
||||||
|
const EMPTY_CLI_APPS: CliAppInfo[] = [];
|
||||||
|
const EMPTY_MCP_PRESETS: McpPresetInfo[] = [];
|
||||||
|
|
||||||
export { isAgentActivityMember };
|
export { isAgentActivityMember };
|
||||||
|
|
||||||
@@ -222,13 +226,14 @@ function FoldedAgentActivity({
|
|||||||
turnLatencyMs,
|
turnLatencyMs,
|
||||||
startedAtMs,
|
startedAtMs,
|
||||||
retryStatus = null,
|
retryStatus = null,
|
||||||
cliApps = [],
|
cliApps = EMPTY_CLI_APPS,
|
||||||
mcpPresets = [],
|
mcpPresets = EMPTY_MCP_PRESETS,
|
||||||
onOpenFilePreview,
|
onOpenFilePreview,
|
||||||
}: AgentActivityClusterProps) {
|
}: AgentActivityClusterProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const fileEditDisplayMode = useFileEditDisplayMode();
|
const fileEditDisplayMode = useFileEditDisplayMode();
|
||||||
const pageVisible = usePageVisibility();
|
const pageVisible = usePageVisibility();
|
||||||
|
const threadVisible = useThreadVisibility();
|
||||||
const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);
|
const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);
|
||||||
const fileEditsByMessage = useMemo(
|
const fileEditsByMessage = useMemo(
|
||||||
() => summarizeFileEditsByMessage(activityMessages, isTurnStreaming),
|
() => summarizeFileEditsByMessage(activityMessages, isTurnStreaming),
|
||||||
@@ -393,11 +398,11 @@ function FoldedAgentActivity({
|
|||||||
useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);
|
useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isTurnStreaming || !pageVisible) return undefined;
|
if (!isTurnStreaming || !pageVisible || !threadVisible) return undefined;
|
||||||
setNow(Date.now());
|
setNow(Date.now());
|
||||||
const interval = window.setInterval(() => setNow(Date.now()), 1_000);
|
const interval = window.setInterval(() => setNow(Date.now()), 1_000);
|
||||||
return () => window.clearInterval(interval);
|
return () => window.clearInterval(interval);
|
||||||
}, [isTurnStreaming, pageVisible]);
|
}, [isTurnStreaming, pageVisible, threadVisible]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const wasStreaming = wasTurnStreamingRef.current;
|
const wasStreaming = wasTurnStreamingRef.current;
|
||||||
@@ -509,7 +514,7 @@ function traceLines(message: UIMessage): string[] {
|
|||||||
return message.content.trim() ? [message.content] : [];
|
return message.content.trim() ? [message.content] : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
function ActivityMessageTimeline({
|
const ActivityMessageTimeline = memo(function ActivityMessageTimeline({
|
||||||
messages,
|
messages,
|
||||||
active,
|
active,
|
||||||
cliAppsByName,
|
cliAppsByName,
|
||||||
@@ -570,7 +575,7 @@ function ActivityMessageTimeline({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
return <>{items}</>;
|
return <>{items}</>;
|
||||||
}
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Keep an intermediate assistant segment as normal Markdown. The activity
|
* Keep an intermediate assistant segment as normal Markdown. The activity
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surf
|
|||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { UIMessage } from "@/lib/types";
|
import type { UIMessage } from "@/lib/types";
|
||||||
import {
|
import {
|
||||||
findPromptElement,
|
|
||||||
type PromptAnchor,
|
type PromptAnchor,
|
||||||
promptTop,
|
promptTop,
|
||||||
userPromptAnchors,
|
userPromptAnchors,
|
||||||
@@ -51,7 +50,6 @@ const MARKER_MIN_GAP_PX = 9;
|
|||||||
const MARKER_BASE_WIDTH_PX = 9;
|
const MARKER_BASE_WIDTH_PX = 9;
|
||||||
const MARKER_STACK_GAP_PX = 16;
|
const MARKER_STACK_GAP_PX = 16;
|
||||||
const RAIL_FALLBACK_HEIGHT_PX = 300;
|
const RAIL_FALLBACK_HEIGHT_PX = 300;
|
||||||
const MEASURE_RETRY_FRAMES = 4;
|
|
||||||
const HOVER_MARKER_WIDTHS_PX = [28, 22, 16, 11];
|
const HOVER_MARKER_WIDTHS_PX = [28, 22, 16, 11];
|
||||||
|
|
||||||
export function PromptRail({
|
export function PromptRail({
|
||||||
@@ -101,20 +99,7 @@ export function PromptRail({
|
|||||||
setActivePromptId((current) => current === next ? current : next);
|
setActivePromptId((current) => current === next ? current : next);
|
||||||
}, [scrollRef]);
|
}, [scrollRef]);
|
||||||
|
|
||||||
useEffect(() => {
|
const railVisible = markers.length > 0;
|
||||||
let frame = 0;
|
|
||||||
let remainingFrames = MEASURE_RETRY_FRAMES;
|
|
||||||
const measure = () => {
|
|
||||||
updateMarkers();
|
|
||||||
remainingFrames -= 1;
|
|
||||||
if (remainingFrames > 0) {
|
|
||||||
frame = window.requestAnimationFrame(measure);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
measure();
|
|
||||||
return () => window.cancelAnimationFrame(frame);
|
|
||||||
}, [bottomOffset, updateMarkers]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const scrollEl = scrollRef.current;
|
const scrollEl = scrollRef.current;
|
||||||
if (!scrollEl) return undefined;
|
if (!scrollEl) return undefined;
|
||||||
@@ -126,28 +111,30 @@ export function PromptRail({
|
|||||||
scrollFrame = window.requestAnimationFrame(updateActivePrompt);
|
scrollFrame = window.requestAnimationFrame(updateActivePrompt);
|
||||||
};
|
};
|
||||||
const scheduleMeasurement = () => {
|
const scheduleMeasurement = () => {
|
||||||
window.cancelAnimationFrame(resizeFrame);
|
if (resizeFrame) return;
|
||||||
resizeFrame = window.requestAnimationFrame(updateMarkers);
|
resizeFrame = window.requestAnimationFrame(() => {
|
||||||
|
resizeFrame = 0;
|
||||||
|
updateMarkers();
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
scheduleMeasurement();
|
||||||
|
const observer = typeof ResizeObserver === "undefined"
|
||||||
|
? null
|
||||||
|
: new ResizeObserver(scheduleMeasurement);
|
||||||
|
observer?.observe(scrollEl);
|
||||||
|
if (scrollEl.firstElementChild) observer?.observe(scrollEl.firstElementChild);
|
||||||
|
if (railRef.current) observer?.observe(railRef.current);
|
||||||
scrollEl.addEventListener("scroll", scheduleActivePrompt, { passive: true });
|
scrollEl.addEventListener("scroll", scheduleActivePrompt, { passive: true });
|
||||||
window.addEventListener("resize", scheduleMeasurement);
|
window.addEventListener("resize", scheduleMeasurement);
|
||||||
return () => {
|
return () => {
|
||||||
window.cancelAnimationFrame(scrollFrame);
|
window.cancelAnimationFrame(scrollFrame);
|
||||||
window.cancelAnimationFrame(resizeFrame);
|
window.cancelAnimationFrame(resizeFrame);
|
||||||
|
observer?.disconnect();
|
||||||
scrollEl.removeEventListener("scroll", scheduleActivePrompt);
|
scrollEl.removeEventListener("scroll", scheduleActivePrompt);
|
||||||
window.removeEventListener("resize", scheduleMeasurement);
|
window.removeEventListener("resize", scheduleMeasurement);
|
||||||
};
|
};
|
||||||
}, [scrollRef, updateActivePrompt, updateMarkers]);
|
}, [bottomOffset, railVisible, scrollRef, updateActivePrompt, updateMarkers]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const scrollEl = scrollRef.current;
|
|
||||||
if (!scrollEl || typeof ResizeObserver === "undefined") return undefined;
|
|
||||||
const observer = new ResizeObserver(() => updateMarkers());
|
|
||||||
observer.observe(scrollEl);
|
|
||||||
if (scrollEl.firstElementChild) observer.observe(scrollEl.firstElementChild);
|
|
||||||
return () => observer.disconnect();
|
|
||||||
}, [scrollRef, updateMarkers]);
|
|
||||||
|
|
||||||
if (markers.length === 0) return null;
|
if (markers.length === 0) return null;
|
||||||
|
|
||||||
@@ -250,8 +237,13 @@ function measurePrompts(
|
|||||||
anchors: PromptAnchor[],
|
anchors: PromptAnchor[],
|
||||||
scrollRange: number,
|
scrollRange: number,
|
||||||
): MeasuredPrompt[] {
|
): MeasuredPrompt[] {
|
||||||
|
const elements = new Map<string, HTMLElement>();
|
||||||
|
for (const element of scrollEl.querySelectorAll<HTMLElement>("[data-user-prompt-id]")) {
|
||||||
|
const id = element.dataset.userPromptId;
|
||||||
|
if (id !== undefined && !elements.has(id)) elements.set(id, element);
|
||||||
|
}
|
||||||
return anchors.flatMap((anchor) => {
|
return anchors.flatMap((anchor) => {
|
||||||
const target = findPromptElement(scrollEl, anchor.id);
|
const target = elements.get(anchor.id);
|
||||||
if (!target) return [];
|
if (!target) return [];
|
||||||
const top = Math.max(0, Math.min(scrollRange, promptTop(scrollEl, target) - 16));
|
const top = Math.max(0, Math.min(scrollRange, promptTop(scrollEl, target) - 16));
|
||||||
return [{
|
return [{
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { memo, useCallback, useMemo, useRef } from "react";
|
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import { MessageBubble } from "@/components/MessageBubble";
|
import { MessageBubble } from "@/components/MessageBubble";
|
||||||
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
|
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
|
||||||
@@ -281,24 +281,41 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
|||||||
onOpenFilePreview,
|
onOpenFilePreview,
|
||||||
onForkFromMessage,
|
onForkFromMessage,
|
||||||
}: ThreadDisplayUnitProps) {
|
}: ThreadDisplayUnitProps) {
|
||||||
// Introducing content-visibility after a unit has painted can move the
|
const elementRef = useRef<HTMLDivElement>(null);
|
||||||
// browser's scroll anchor. Only units deferred on their first render may
|
const heightRef = useRef(0);
|
||||||
// remain deferred.
|
const [nearViewport, setNearViewport] = useState(true);
|
||||||
const hasRenderedEagerlyRef = useRef(!deferOffscreenRender);
|
const [interacted, setInteracted] = useState(false);
|
||||||
if (!deferOffscreenRender) hasRenderedEagerlyRef.current = true;
|
const retainContent = !deferOffscreenRender || interacted || nearViewport;
|
||||||
const stableDeferOffscreenRender =
|
useEffect(() => {
|
||||||
deferOffscreenRender && !hasRenderedEagerlyRef.current;
|
const element = elementRef.current;
|
||||||
|
if (!element || !deferOffscreenRender || interacted || typeof IntersectionObserver === "undefined") return;
|
||||||
|
const observer = new IntersectionObserver(([entry]) => {
|
||||||
|
if (!entry) return;
|
||||||
|
if (!entry.isIntersecting) {
|
||||||
|
const height = element.getBoundingClientRect().height;
|
||||||
|
if (height <= 0) return;
|
||||||
|
heightRef.current = height;
|
||||||
|
}
|
||||||
|
setNearViewport(entry.isIntersecting);
|
||||||
|
}, { rootMargin: "1000px 0px" });
|
||||||
|
observer.observe(element);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [deferOffscreenRender, interacted]);
|
||||||
const onForkFromHere = useCallback(() => {
|
const onForkFromHere = useCallback(() => {
|
||||||
if (forkIndex !== undefined) onForkFromMessage?.(forkIndex);
|
if (forkIndex !== undefined) onForkFromMessage?.(forkIndex);
|
||||||
}, [forkIndex, onForkFromMessage]);
|
}, [forkIndex, onForkFromMessage]);
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div
|
<div
|
||||||
className={`${marginTop}${stableDeferOffscreenRender ? " thread-render-unit" : ""}`}
|
ref={elementRef}
|
||||||
|
className={marginTop}
|
||||||
|
style={retainContent ? undefined : { height: heightRef.current }}
|
||||||
|
onPointerDownCapture={() => setInteracted(true)}
|
||||||
|
onFocusCapture={() => setInteracted(true)}
|
||||||
data-thread-display-unit={unitKey}
|
data-thread-display-unit={unitKey}
|
||||||
data-user-prompt-id={userPromptId}
|
data-user-prompt-id={userPromptId}
|
||||||
>
|
>
|
||||||
{unit.type === "activity" ? (
|
{retainContent ? unit.type === "activity" ? (
|
||||||
<AgentActivityCluster
|
<AgentActivityCluster
|
||||||
messages={unit.messages}
|
messages={unit.messages}
|
||||||
isTurnStreaming={isTurnStreaming}
|
isTurnStreaming={isTurnStreaming}
|
||||||
@@ -321,7 +338,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
|||||||
onOpenFilePreview={onOpenFilePreview}
|
onOpenFilePreview={onOpenFilePreview}
|
||||||
onForkFromHere={forkIndex !== undefined ? onForkFromHere : undefined}
|
onForkFromHere={forkIndex !== undefined ? onForkFromHere : undefined}
|
||||||
/>
|
/>
|
||||||
)}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
{showForkBoundary ? <ForkBoundaryDivider label={forkBoundaryLabel} /> : null}
|
{showForkBoundary ? <ForkBoundaryDivider label={forkBoundaryLabel} /> : null}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -51,6 +51,7 @@ import type {
|
|||||||
WorkspacesPayload,
|
WorkspacesPayload,
|
||||||
} from "@/lib/types";
|
} from "@/lib/types";
|
||||||
import { projectWebuiThreadMessages } from "@/lib/thread-display-compat";
|
import { projectWebuiThreadMessages } from "@/lib/thread-display-compat";
|
||||||
|
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||||
import { useClient } from "@/providers/ClientProvider";
|
import { useClient } from "@/providers/ClientProvider";
|
||||||
|
|
||||||
type MessageShape = Pick<UIMessage, "role" | "kind" | "content" | "isStreaming" | "turnId">;
|
type MessageShape = Pick<UIMessage, "role" | "kind" | "content" | "isStreaming" | "turnId">;
|
||||||
@@ -789,8 +790,10 @@ export function ThreadShell({
|
|||||||
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
|
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
|
||||||
const viewportRef = useRef<ThreadViewportHandle | null>(null);
|
const viewportRef = useRef<ThreadViewportHandle | null>(null);
|
||||||
const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());
|
const activeViewportTurnByChatIdRef = useRef<Map<string, string>>(new Map());
|
||||||
const messageCacheRef = useRef<Map<string, UIMessage[]>>(new Map());
|
|
||||||
const knownTemporaryChatIdsRef = useRef(new Set<string>());
|
const knownTemporaryChatIdsRef = useRef(new Set<string>());
|
||||||
|
const messageCacheRef = useRef(new ThreadMessageCache(
|
||||||
|
(key) => knownTemporaryChatIdsRef.current.has(key),
|
||||||
|
));
|
||||||
/** Last chatId we associated with the in-memory thread (for cache-on-switch). */
|
/** Last chatId we associated with the in-memory thread (for cache-on-switch). */
|
||||||
const prevChatIdForCacheRef = useRef<string | null>(null);
|
const prevChatIdForCacheRef = useRef<string | null>(null);
|
||||||
/** Skip one message-cache write right after chatId changes (messages may not match yet). */
|
/** Skip one message-cache write right after chatId changes (messages may not match yet). */
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ChevronDown } from "lucide-react";
|
import { ChevronDown } from "lucide-react";
|
||||||
import type { ReactNode, Ref } from "react";
|
import { useState, type ReactNode, type Ref } from "react";
|
||||||
|
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
@@ -30,6 +30,8 @@ export function ThinkingReasoningShell({
|
|||||||
onToggle,
|
onToggle,
|
||||||
onScroll,
|
onScroll,
|
||||||
}: ThinkingReasoningShellProps) {
|
}: ThinkingReasoningShellProps) {
|
||||||
|
const [hasExpanded, setHasExpanded] = useState(expanded);
|
||||||
|
if (expanded && !hasExpanded) setHasExpanded(true);
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="flex w-full max-w-[45rem] animate-in flex-col fade-in duration-300 motion-reduce:animate-none"
|
className="flex w-full max-w-[45rem] animate-in flex-col fade-in duration-300 motion-reduce:animate-none"
|
||||||
@@ -109,7 +111,7 @@ export function ThinkingReasoningShell({
|
|||||||
className="mt-1.5 max-h-[180px] overflow-y-auto pr-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
className="mt-1.5 max-h-[180px] overflow-y-auto pr-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||||
>
|
>
|
||||||
<div ref={contentRef} className="flex flex-col gap-0.5">
|
<div ref={contentRef} className="flex flex-col gap-0.5">
|
||||||
{children}
|
{hasExpanded ? children : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{fadeTop ? (
|
{fadeTop ? (
|
||||||
|
|||||||
@@ -13,33 +13,48 @@ import type { UIMediaAttachment, UIMessage } from "@/lib/types";
|
|||||||
*/
|
*/
|
||||||
export function coalesceActivityMessages(messages: UIMessage[]): UIMessage[] {
|
export function coalesceActivityMessages(messages: UIMessage[]): UIMessage[] {
|
||||||
const normalized: UIMessage[] = [];
|
const normalized: UIMessage[] = [];
|
||||||
|
const calls = new Map<string, { latest: number; byTurn: Map<string, number> }>();
|
||||||
|
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
const targetIndex = findMergeTarget(normalized, message);
|
let targetIndex = -1;
|
||||||
|
if (message.kind === "trace") {
|
||||||
|
for (const event of message.toolEvents ?? []) {
|
||||||
|
if (!event.call_id) continue;
|
||||||
|
const call = calls.get(event.call_id);
|
||||||
|
if (!call) continue;
|
||||||
|
const index = message.turnId
|
||||||
|
? Math.max(call.byTurn.get(message.turnId) ?? -1, call.byTurn.get("") ?? -1)
|
||||||
|
: call.latest;
|
||||||
|
targetIndex = Math.max(targetIndex, index);
|
||||||
|
}
|
||||||
|
if (targetIndex < 0 && canMergeAdjacentProgress(normalized.at(-1), message)) {
|
||||||
|
targetIndex = normalized.length - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
if (targetIndex < 0) {
|
if (targetIndex < 0) {
|
||||||
|
targetIndex = normalized.length;
|
||||||
normalized.push(message);
|
normalized.push(message);
|
||||||
continue;
|
} else {
|
||||||
|
normalized[targetIndex] = mergeTraceMessages(normalized[targetIndex], message);
|
||||||
|
}
|
||||||
|
if (message.kind !== "trace") continue;
|
||||||
|
// Merging preserves the target's turn. Legacy rows without a turn match any turn.
|
||||||
|
const turn = normalized[targetIndex].turnId || "";
|
||||||
|
for (const event of message.toolEvents ?? []) {
|
||||||
|
if (!event.call_id) continue;
|
||||||
|
let call = calls.get(event.call_id);
|
||||||
|
if (!call) {
|
||||||
|
call = { latest: targetIndex, byTurn: new Map() };
|
||||||
|
calls.set(event.call_id, call);
|
||||||
|
}
|
||||||
|
call.latest = Math.max(call.latest, targetIndex);
|
||||||
|
call.byTurn.set(turn, Math.max(call.byTurn.get(turn) ?? -1, targetIndex));
|
||||||
}
|
}
|
||||||
normalized[targetIndex] = mergeTraceMessages(normalized[targetIndex], message);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return normalized;
|
return normalized;
|
||||||
}
|
}
|
||||||
|
|
||||||
function findMergeTarget(messages: UIMessage[], incoming: UIMessage): number {
|
|
||||||
if (incoming.kind !== "trace") return -1;
|
|
||||||
|
|
||||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
||||||
const previous = messages[index];
|
|
||||||
if (previous.kind !== "trace") continue;
|
|
||||||
if (hasSharedToolCall(previous, incoming) && sameTurn(previous, incoming)) return index;
|
|
||||||
}
|
|
||||||
|
|
||||||
const adjacentIndex = messages.length - 1;
|
|
||||||
const adjacent = messages[adjacentIndex];
|
|
||||||
return canMergeAdjacentProgress(adjacent, incoming) ? adjacentIndex : -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
function canMergeAdjacentProgress(
|
function canMergeAdjacentProgress(
|
||||||
previous: UIMessage | undefined,
|
previous: UIMessage | undefined,
|
||||||
incoming: UIMessage,
|
incoming: UIMessage,
|
||||||
@@ -87,15 +102,6 @@ function messageTraces(message: UIMessage): string[] {
|
|||||||
return message.content.trim() ? [message.content] : [];
|
return message.content.trim() ? [message.content] : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
function hasSharedToolCall(previous: UIMessage, incoming: UIMessage): boolean {
|
|
||||||
const previousCallIds = new Set(
|
|
||||||
(previous.toolEvents ?? []).map((event) => event.call_id).filter(Boolean),
|
|
||||||
);
|
|
||||||
return (incoming.toolEvents ?? []).some((event) => (
|
|
||||||
!!event.call_id && previousCallIds.has(event.call_id)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasSharedTrace(previous: UIMessage, incoming: UIMessage): boolean {
|
function hasSharedTrace(previous: UIMessage, incoming: UIMessage): boolean {
|
||||||
const previousTraces = new Set(messageTraces(previous).map(canonicalToolTrace));
|
const previousTraces = new Set(messageTraces(previous).map(canonicalToolTrace));
|
||||||
return messageTraces(incoming).some((trace) => previousTraces.has(canonicalToolTrace(trace)));
|
return messageTraces(incoming).some((trace) => previousTraces.has(canonicalToolTrace(trace)));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||||
|
|
||||||
import { useClient } from "@/providers/ClientProvider";
|
import { useClient } from "@/providers/ClientProvider";
|
||||||
import { toMediaAttachment } from "@/lib/media";
|
import { toMediaAttachment } from "@/lib/media";
|
||||||
@@ -49,6 +50,7 @@ import type {
|
|||||||
interface StreamBuffer {
|
interface StreamBuffer {
|
||||||
/** ID of the assistant message currently receiving deltas (cleared when its segment closes). */
|
/** ID of the assistant message currently receiving deltas (cleared when its segment closes). */
|
||||||
messageId: string;
|
messageId: string;
|
||||||
|
mergeReasoning?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ActiveAssistantCursor {
|
interface ActiveAssistantCursor {
|
||||||
@@ -274,6 +276,9 @@ export function useNanobotStream(
|
|||||||
dismissStreamError: () => void;
|
dismissStreamError: () => void;
|
||||||
} {
|
} {
|
||||||
const { client } = useClient();
|
const { client } = useClient();
|
||||||
|
const threadVisible = useThreadVisibility();
|
||||||
|
const threadVisibleRef = useRef(threadVisible);
|
||||||
|
threadVisibleRef.current = threadVisible;
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
|
||||||
const [messages, setMessages] = useState<UIMessage[]>(initialMessages);
|
const [messages, setMessages] = useState<UIMessage[]>(initialMessages);
|
||||||
@@ -509,7 +514,7 @@ export function useNanobotStream(
|
|||||||
};
|
};
|
||||||
closedAssistantStreamIdsRef.current.delete(merged.id);
|
closedAssistantStreamIdsRef.current.delete(merged.id);
|
||||||
activeAssistantRef.current = { id: merged.id, index: targetIndex };
|
activeAssistantRef.current = { id: merged.id, index: targetIndex };
|
||||||
buffer.current = { messageId: merged.id };
|
if (buffer.current?.messageId !== merged.id) buffer.current = { messageId: merged.id };
|
||||||
return replaceMessageAt(next, targetIndex, merged);
|
return replaceMessageAt(next, targetIndex, merged);
|
||||||
},
|
},
|
||||||
[resolveActiveAssistantIndex],
|
[resolveActiveAssistantIndex],
|
||||||
@@ -518,26 +523,59 @@ export function useNanobotStream(
|
|||||||
const applyPendingStreamEvents = useCallback(
|
const applyPendingStreamEvents = useCallback(
|
||||||
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
|
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
|
||||||
let next = prev;
|
let next = prev;
|
||||||
for (const event of events) {
|
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
|
||||||
|
|| (nextEvent.kind === "delta" && event.kind === "delta" && nextEvent.source !== event.source)) break;
|
||||||
|
chunks.push(nextEvent.text);
|
||||||
|
turn = { ...turn, ...nextEvent.turn };
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
const text = chunks.join("");
|
||||||
if (event.kind === "delta") {
|
if (event.kind === "delta") {
|
||||||
next = appendAnswerChunk(next, event.text, event.turn, event.source);
|
next = appendAnswerChunk(next, text, turn, event.source);
|
||||||
} else {
|
} else {
|
||||||
|
const continuationIndex = buffer.current?.mergeReasoning
|
||||||
|
? resolveActiveAssistantIndex(next, turn)
|
||||||
|
: null;
|
||||||
|
if (continuationIndex !== null) {
|
||||||
|
// Length continuation keeps one Markdown answer and its reasoning
|
||||||
|
// together. Ordinary reasoning still opens a new activity surface.
|
||||||
|
const target = next[continuationIndex];
|
||||||
|
const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : "";
|
||||||
|
next = replaceMessageAt(next, continuationIndex, {
|
||||||
|
...target,
|
||||||
|
reasoning: (target.reasoning ?? "") + separator + text,
|
||||||
|
reasoningStreaming: true,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (closeActiveAssistantStream()) clearActivitySegment();
|
if (closeActiveAssistantStream()) clearActivitySegment();
|
||||||
next = attachReasoningChunk(
|
next = attachReasoningChunk(
|
||||||
next,
|
next,
|
||||||
event.text,
|
text,
|
||||||
{ ensure: ensureActivitySegmentId },
|
{ ensure: ensureActivitySegmentId },
|
||||||
event.turn,
|
turn,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return next;
|
return next;
|
||||||
},
|
},
|
||||||
[appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream, ensureActivitySegmentId],
|
[
|
||||||
|
appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream,
|
||||||
|
ensureActivitySegmentId, resolveActiveAssistantIndex,
|
||||||
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
const flushPendingStreamEvents = useCallback((options?: {
|
const flushPendingStreamEvents = useCallback((options?: {
|
||||||
closeAnswerSegment?: boolean;
|
closeAnswerSegment?: boolean;
|
||||||
|
mergeReasoning?: boolean;
|
||||||
finalAnswerText?: string;
|
finalAnswerText?: string;
|
||||||
turn?: UIMessageTurnFields;
|
turn?: UIMessageTurnFields;
|
||||||
source?: UIMessage["source"];
|
source?: UIMessage["source"];
|
||||||
@@ -554,7 +592,8 @@ export function useNanobotStream(
|
|||||||
const finalAnswerText = options?.finalAnswerText;
|
const finalAnswerText = options?.finalAnswerText;
|
||||||
const turn = options?.turn ?? {};
|
const turn = options?.turn ?? {};
|
||||||
const source = options?.source;
|
const source = options?.source;
|
||||||
if (events.length === 0 && finalAnswerText === undefined && source === undefined) {
|
if (events.length === 0 && finalAnswerText === undefined && source === undefined
|
||||||
|
&& !options?.mergeReasoning) {
|
||||||
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -614,6 +653,7 @@ export function useNanobotStream(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (options?.mergeReasoning && buffer.current) buffer.current.mergeReasoning = true;
|
||||||
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
@@ -621,7 +661,7 @@ export function useNanobotStream(
|
|||||||
|
|
||||||
const schedulePendingStreamFlush = useCallback(() => {
|
const schedulePendingStreamFlush = useCallback(() => {
|
||||||
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
||||||
if (document.visibilityState === "hidden") {
|
if (document.visibilityState === "hidden" || !threadVisibleRef.current) {
|
||||||
streamTimerRef.current = window.setTimeout(() => {
|
streamTimerRef.current = window.setTimeout(() => {
|
||||||
streamTimerRef.current = null;
|
streamTimerRef.current = null;
|
||||||
const events = pendingStreamEventsRef.current;
|
const events = pendingStreamEventsRef.current;
|
||||||
@@ -640,9 +680,19 @@ export function useNanobotStream(
|
|||||||
});
|
});
|
||||||
}, [applyPendingStreamEvents]);
|
}, [applyPendingStreamEvents]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (threadVisible) {
|
||||||
|
flushPendingStreamEvents();
|
||||||
|
} else if (streamFrameRef.current !== null) {
|
||||||
|
window.cancelAnimationFrame(streamFrameRef.current);
|
||||||
|
streamFrameRef.current = null;
|
||||||
|
schedulePendingStreamFlush();
|
||||||
|
}
|
||||||
|
}, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const flushOnReturn = () => {
|
const flushOnReturn = () => {
|
||||||
if (document.visibilityState !== "visible") return;
|
if (document.visibilityState !== "visible" || !threadVisibleRef.current) return;
|
||||||
if (pendingStreamEventsRef.current.length === 0) return;
|
if (pendingStreamEventsRef.current.length === 0) return;
|
||||||
flushPendingStreamEvents();
|
flushPendingStreamEvents();
|
||||||
};
|
};
|
||||||
@@ -852,6 +902,7 @@ export function useNanobotStream(
|
|||||||
const mergeNext = ev.resuming === true && ev.merge_next === true;
|
const mergeNext = ev.resuming === true && ev.merge_next === true;
|
||||||
flushPendingStreamEvents({
|
flushPendingStreamEvents({
|
||||||
closeAnswerSegment: !mergeNext,
|
closeAnswerSegment: !mergeNext,
|
||||||
|
mergeReasoning: mergeNext,
|
||||||
...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}),
|
...(typeof ev.text === "string" ? { finalAnswerText: ev.text } : {}),
|
||||||
turn,
|
turn,
|
||||||
source: ev.source,
|
source: ev.source,
|
||||||
|
|||||||
@@ -159,14 +159,21 @@ export function useSessions(): {
|
|||||||
try {
|
try {
|
||||||
const rows = await listSessions(tokenRef.current);
|
const rows = await listSessions(tokenRef.current);
|
||||||
const serverKeys = new Set(rows.map((row) => row.key));
|
const serverKeys = new Set(rows.map((row) => row.key));
|
||||||
setSessions((prev) => [
|
setSessions((prev) => {
|
||||||
...rows,
|
const byKey = new Map(prev.map((row) => [row.key, row]));
|
||||||
...prev.filter(
|
const next = [
|
||||||
(session) =>
|
...rows.map((row) => {
|
||||||
optimisticKeysRef.current.has(session.key)
|
const previous = byKey.get(row.key);
|
||||||
&& !serverKeys.has(session.key),
|
return previous && JSON.stringify(previous) === JSON.stringify(row) ? previous : row;
|
||||||
),
|
}),
|
||||||
]);
|
...prev.filter(
|
||||||
|
(session) =>
|
||||||
|
optimisticKeysRef.current.has(session.key)
|
||||||
|
&& !serverKeys.has(session.key),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
return next.length === prev.length && next.every((row, index) => row === prev[index]) ? prev : next;
|
||||||
|
});
|
||||||
for (const key of Array.from(optimisticKeysRef.current)) {
|
for (const key of Array.from(optimisticKeysRef.current)) {
|
||||||
if (serverKeys.has(key)) optimisticKeysRef.current.delete(key);
|
if (serverKeys.has(key)) optimisticKeysRef.current.delete(key);
|
||||||
}
|
}
|
||||||
@@ -191,18 +198,16 @@ export function useSessions(): {
|
|||||||
}, [refresh]);
|
}, [refresh]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let disposed = false;
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||||
let refreshQueued = false;
|
|
||||||
const unsubscribe = client.onSessionUpdate(() => {
|
const unsubscribe = client.onSessionUpdate(() => {
|
||||||
if (refreshQueued) return;
|
if (timer !== undefined) return;
|
||||||
refreshQueued = true;
|
timer = setTimeout(() => {
|
||||||
queueMicrotask(() => {
|
timer = undefined;
|
||||||
refreshQueued = false;
|
void refresh();
|
||||||
if (!disposed) void refresh();
|
}, 250);
|
||||||
});
|
|
||||||
});
|
});
|
||||||
return () => {
|
return () => {
|
||||||
disposed = true;
|
clearTimeout(timer);
|
||||||
unsubscribe();
|
unsubscribe();
|
||||||
};
|
};
|
||||||
}, [client, refresh]);
|
}, [client, refresh]);
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { createContext, useContext } from "react";
|
||||||
|
|
||||||
|
export const ThreadVisibilityContext = createContext(true);
|
||||||
|
export function useThreadVisibility(): boolean {
|
||||||
|
return useContext(ThreadVisibilityContext);
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
import "katex/dist/katex.min.css";
|
||||||
|
export { default } from "rehype-katex";
|
||||||
@@ -24,73 +24,74 @@ export function normalizeLegacyLongTaskMessages(messages: UIMessage[]): UIMessag
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
interface PreparedMessage {
|
||||||
* Replay timestamps an assistant row when its first output is recorded, while
|
message: UIMessage;
|
||||||
* latency covers the whole turn. Derive the end from the matching user start
|
hidden: boolean;
|
||||||
* so the displayed time cannot double-count the pre-output interval.
|
compact: boolean;
|
||||||
*/
|
|
||||||
function deriveAssistantCompletionTimes(messages: UIMessage[]): UIMessage[] {
|
|
||||||
const userStartedAtByTurn = new Map<string, number>();
|
|
||||||
let latestUserStartedAt: number | undefined;
|
|
||||||
|
|
||||||
return messages.map((message) => {
|
|
||||||
if (message.role === "user") {
|
|
||||||
if (Number.isFinite(message.createdAt)) {
|
|
||||||
latestUserStartedAt = message.createdAt;
|
|
||||||
if (message.turnId) userStartedAtByTurn.set(message.turnId, message.createdAt);
|
|
||||||
}
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
message.role !== "assistant"
|
|
||||||
|| message.kind === "trace"
|
|
||||||
|| message.completedAt !== undefined
|
|
||||||
|| message.latencyMs === undefined
|
|
||||||
|| !Number.isFinite(message.latencyMs)
|
|
||||||
|| message.latencyMs < 0
|
|
||||||
) {
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
const startedAt = message.turnId
|
|
||||||
? userStartedAtByTurn.get(message.turnId)
|
|
||||||
: message.source
|
|
||||||
? undefined
|
|
||||||
: latestUserStartedAt;
|
|
||||||
if (startedAt === undefined) return message;
|
|
||||||
return { ...message, completedAt: startedAt + message.latencyMs };
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function identifyCompactReplies(messages: UIMessage[]): UIMessage[] {
|
const preparedMessages = new WeakMap<UIMessage, PreparedMessage>();
|
||||||
const turns = new Set(messages.flatMap((message) => (
|
const completionMessages = new WeakMap<UIMessage, { completedAt: number; message: UIMessage }>();
|
||||||
message.role === "user" && message.content.trim().toLowerCase() === "/compact" && message.turnId
|
|
||||||
? [message.turnId]
|
function prepareMessage(original: UIMessage): PreparedMessage {
|
||||||
: []
|
const cached = preparedMessages.get(original);
|
||||||
)));
|
if (cached) return cached;
|
||||||
return messages.map((message) => {
|
const message = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages([original]))[0];
|
||||||
if (message.role !== "assistant" || message.kind || message.isStreaming
|
const prepared = {
|
||||||
|| !message.turnId || !turns.has(message.turnId)) return message;
|
message,
|
||||||
if (message.content === "Nothing to compact.") return { ...message, compactReply: "empty" };
|
hidden: isSystemCommandTurnId(message.turnId)
|
||||||
if (message.content === "Unable to compact context. Check the logs and try again.") {
|
|| (message.role === "user" && isModelCommandText(message.content))
|
||||||
return { ...message, compactReply: "failed" };
|
|| (message.role === "assistant" && isModelCommandResponseText(message.content)),
|
||||||
}
|
compact: message.role === "user" && message.content.trim().toLowerCase() === "/compact",
|
||||||
return message;
|
};
|
||||||
});
|
preparedMessages.set(original, prepared);
|
||||||
|
return prepared;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
|
export function projectWebuiThreadMessages(messages: UIMessage[]): UIMessage[] {
|
||||||
const normalized = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages(messages));
|
const hiddenTurns = new Set<string>();
|
||||||
const hiddenTurns = new Set(normalized.flatMap((message) => (
|
const compactTurns = new Set<string>();
|
||||||
message.role === "user" && isModelCommandText(message.content) && message.turnId
|
for (const original of messages) {
|
||||||
? [message.turnId]
|
const { message, hidden, compact } = prepareMessage(original);
|
||||||
: []
|
if (message.role !== "user" || !message.turnId) continue;
|
||||||
)));
|
if (hidden && isModelCommandText(message.content)) hiddenTurns.add(message.turnId);
|
||||||
const visible = normalized.filter((message) => (
|
if (compact && !hidden) compactTurns.add(message.turnId);
|
||||||
!isSystemCommandTurnId(message.turnId)
|
}
|
||||||
&& (!message.turnId || !hiddenTurns.has(message.turnId))
|
const visible: UIMessage[] = [];
|
||||||
&& !(message.role === "user" && isModelCommandText(message.content))
|
const starts = new Map<string, number>();
|
||||||
&& !(message.role === "assistant" && isModelCommandResponseText(message.content))
|
let latestStart: number | undefined;
|
||||||
));
|
for (const original of messages) {
|
||||||
return deriveAssistantCompletionTimes(identifyCompactReplies(visible));
|
const prepared = prepareMessage(original);
|
||||||
|
let message = prepared.message;
|
||||||
|
if (prepared.hidden || (message.turnId && hiddenTurns.has(message.turnId))) continue;
|
||||||
|
if (message.role === "user" && Number.isFinite(message.createdAt)) {
|
||||||
|
latestStart = message.createdAt;
|
||||||
|
if (message.turnId) starts.set(message.turnId, message.createdAt);
|
||||||
|
}
|
||||||
|
if (message.role === "assistant" && !message.kind && !message.isStreaming
|
||||||
|
&& message.turnId && compactTurns.has(message.turnId)) {
|
||||||
|
if (message.content === "Nothing to compact.") message = { ...message, compactReply: "empty" };
|
||||||
|
if (message.content === "Unable to compact context. Check the logs and try again.") {
|
||||||
|
message = { ...message, compactReply: "failed" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Replay latency starts at the user prompt, not the first assistant output.
|
||||||
|
if (message.role === "assistant" && message.kind !== "trace"
|
||||||
|
&& message.completedAt === undefined && message.latencyMs !== undefined
|
||||||
|
&& Number.isFinite(message.latencyMs) && message.latencyMs >= 0) {
|
||||||
|
const start = message.turnId ? starts.get(message.turnId) : message.source ? undefined : latestStart;
|
||||||
|
if (start !== undefined) {
|
||||||
|
const completedAt = start + message.latencyMs;
|
||||||
|
const cached = completionMessages.get(message);
|
||||||
|
if (cached?.completedAt === completedAt) message = cached.message;
|
||||||
|
else {
|
||||||
|
const completed = { ...message, completedAt };
|
||||||
|
completionMessages.set(message, { completedAt, message: completed });
|
||||||
|
message = completed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
visible.push(message);
|
||||||
|
}
|
||||||
|
return visible;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { UIMessage } from "./types";
|
||||||
|
|
||||||
|
/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */
|
||||||
|
export class ThreadMessageCache {
|
||||||
|
private entries = new Map<string, { messages: UIMessage[]; bytes: number }>();
|
||||||
|
private sizes = new WeakMap<object, number>();
|
||||||
|
private bytes = 0;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private isPinned: (key: string) => boolean,
|
||||||
|
private maxBytes = 16 * 1024 * 1024,
|
||||||
|
private maxEntries = 12,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
get(key: string): UIMessage[] | undefined {
|
||||||
|
const entry = this.entries.get(key);
|
||||||
|
if (!entry) return undefined;
|
||||||
|
this.entries.delete(key);
|
||||||
|
this.entries.set(key, entry);
|
||||||
|
return entry.messages;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(key: string, messages: UIMessage[]): void {
|
||||||
|
this.delete(key);
|
||||||
|
const bytes = this.estimate(messages);
|
||||||
|
this.entries.set(key, { messages, bytes });
|
||||||
|
this.bytes += bytes;
|
||||||
|
for (const candidate of this.entries.keys()) {
|
||||||
|
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
|
||||||
|
if (!this.isPinned(candidate)) this.delete(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(key: string): void {
|
||||||
|
const entry = this.entries.get(key);
|
||||||
|
if (entry) this.bytes -= entry.bytes;
|
||||||
|
this.entries.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private estimate(value: unknown): number {
|
||||||
|
if (typeof value === "string") return value.length * 2;
|
||||||
|
if (!value || typeof value !== "object") return 8;
|
||||||
|
const cached = this.sizes.get(value);
|
||||||
|
if (cached !== undefined) return cached;
|
||||||
|
const size = 32 + Object.values(value).reduce<number>((total, item) => total + this.estimate(item), 0);
|
||||||
|
this.sizes.set(value, size);
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,39 @@ function progressMessage(id: string, phase: "start" | "end" | "error"): UIMessag
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("activity message coalescing", () => {
|
describe("activity message coalescing", () => {
|
||||||
|
it("keeps reused call IDs isolated by turn and picks the latest compatible legacy row", () => {
|
||||||
|
const call = (id: string, turnId?: string): UIMessage => ({
|
||||||
|
...progressMessage(id, "start"), turnId,
|
||||||
|
toolEvents: [{ call_id: "shared", phase: "start", name: "web_search" }],
|
||||||
|
});
|
||||||
|
const complete = (id: string, turnId?: string): UIMessage => ({
|
||||||
|
...call(id, turnId), toolEvents: [{ call_id: "shared", phase: "end", name: "web_search" }],
|
||||||
|
});
|
||||||
|
const result = coalesceActivityMessages([
|
||||||
|
call("first", "a"), call("second", "b"), complete("finish-a", "a"),
|
||||||
|
]);
|
||||||
|
expect(result.map((row) => [row.id, row.toolEvents?.[0].phase])).toEqual([
|
||||||
|
["first", "end"], ["second", "start"],
|
||||||
|
]);
|
||||||
|
expect(coalesceActivityMessages([
|
||||||
|
call("first", "a"), call("second", "b"), complete("legacy"),
|
||||||
|
]).map((row) => [row.id, row.toolEvents?.[0].phase])).toEqual([
|
||||||
|
["first", "start"], ["second", "end"],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("processes independent calls with a linear event-read budget", () => {
|
||||||
|
let reads = 0;
|
||||||
|
const messages: UIMessage[] = Array.from({ length: 1000 }, (_, index) => ({
|
||||||
|
id: `${index}`, role: "tool", kind: "trace", content: `tool${index}()`, createdAt: index,
|
||||||
|
get toolEvents() {
|
||||||
|
reads++;
|
||||||
|
return [{ call_id: `${index}`, phase: "end" as const, name: `tool${index}` }];
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
expect(coalesceActivityMessages(messages)).toEqual(messages);
|
||||||
|
expect(reads).toBeLessThanOrEqual(messages.length * 4);
|
||||||
|
});
|
||||||
it("folds persisted start and terminal progress into one activity", () => {
|
it("folds persisted start and terminal progress into one activity", () => {
|
||||||
const result = coalesceActivityMessages([
|
const result = coalesceActivityMessages([
|
||||||
progressMessage("start", "start"),
|
progressMessage("start", "start"),
|
||||||
|
|||||||
@@ -563,6 +563,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.queryByText("Edited files")).not.toBeInTheDocument();
|
expect(screen.queryByText("Edited files")).not.toBeInTheDocument();
|
||||||
const fileRef = screen.getByTestId("activity-file-reference");
|
const fileRef = screen.getByTestId("activity-file-reference");
|
||||||
@@ -679,15 +680,28 @@ describe("AgentActivityCluster", () => {
|
|||||||
}
|
}
|
||||||
const assertIndependentDiff = () => {
|
const assertIndependentDiff = () => {
|
||||||
const diff = screen.getByTestId("file-edit-diff");
|
const diff = screen.getByTestId("file-edit-diff");
|
||||||
|
expect(diff).toBeVisible();
|
||||||
expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-scroll"]'))
|
expect(diff.closest('[aria-hidden="true"], [inert], [data-testid="agent-activity-scroll"]'))
|
||||||
.toBeNull();
|
.toBeNull();
|
||||||
|
expect(screen.getAllByTestId("activity-file-reference")).toHaveLength(1);
|
||||||
|
};
|
||||||
|
const assertExpandedOrder = () => {
|
||||||
|
for (const toggle of document.querySelectorAll<HTMLButtonElement>(
|
||||||
|
'[data-thread-disclosure][aria-expanded="false"]',
|
||||||
|
)) {
|
||||||
|
fireEvent.click(toggle);
|
||||||
|
}
|
||||||
|
const diff = screen.getByTestId("file-edit-diff");
|
||||||
|
expect(screen.getByText("Before edit")).toBeVisible();
|
||||||
|
expect(screen.getByText("After edit")).toBeVisible();
|
||||||
expect(screen.getByText("Before edit").compareDocumentPosition(diff)
|
expect(screen.getByText("Before edit").compareDocumentPosition(diff)
|
||||||
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
expect(diff.compareDocumentPosition(screen.getByText("After edit"))
|
expect(diff.compareDocumentPosition(screen.getByText("After edit"))
|
||||||
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
& Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||||
expect(screen.getAllByTestId("activity-file-reference")).toHaveLength(1);
|
assertIndependentDiff();
|
||||||
};
|
};
|
||||||
assertIndependentDiff();
|
assertIndependentDiff();
|
||||||
|
assertExpandedOrder();
|
||||||
for (const toggle of document.querySelectorAll<HTMLButtonElement>("[data-thread-disclosure]")) {
|
for (const toggle of document.querySelectorAll<HTMLButtonElement>("[data-thread-disclosure]")) {
|
||||||
fireEvent.click(toggle);
|
fireEvent.click(toggle);
|
||||||
assertIndependentDiff();
|
assertIndependentDiff();
|
||||||
@@ -710,6 +724,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
fireEvent.click(screen.getByTestId("file-edit-diff-toggle"));
|
fireEvent.click(screen.getByTestId("file-edit-diff-toggle"));
|
||||||
}
|
}
|
||||||
assertIndependentDiff();
|
assertIndependentDiff();
|
||||||
|
assertExpandedOrder();
|
||||||
} finally {
|
} finally {
|
||||||
localStorage.removeItem("nanobot-webui.settings-preferences");
|
localStorage.removeItem("nanobot-webui.settings-preferences");
|
||||||
}
|
}
|
||||||
@@ -1051,6 +1066,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.getByText("Deleted")).toBeInTheDocument();
|
expect(screen.getByText("Deleted")).toBeInTheDocument();
|
||||||
expect(screen.queryByText("Edited")).not.toBeInTheDocument();
|
expect(screen.queryByText("Edited")).not.toBeInTheDocument();
|
||||||
@@ -1308,6 +1324,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.getByText("Searched X · nanobot oauth")).toBeInTheDocument();
|
expect(screen.getByText("Searched X · nanobot oauth")).toBeInTheDocument();
|
||||||
expect(screen.queryByText(/Completed X search/i)).not.toBeInTheDocument();
|
expect(screen.queryByText(/Completed X search/i)).not.toBeInTheDocument();
|
||||||
@@ -1341,6 +1358,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.queryByText(/signed-secret|secret1234|url-secret/)).not.toBeInTheDocument();
|
expect(screen.queryByText(/signed-secret|secret1234|url-secret/)).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("Searched release notes access_token=<redacted>")).toBeInTheDocument();
|
expect(screen.getByText("Searched release notes access_token=<redacted>")).toBeInTheDocument();
|
||||||
@@ -1557,6 +1575,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const title = screen.getByText("Example documentation");
|
const title = screen.getByText("Example documentation");
|
||||||
const url = screen.getByText("example.com/docs");
|
const url = screen.getByText("example.com/docs");
|
||||||
@@ -1638,6 +1657,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const run = screen.getByText(/Reviewed sources.*2 files/).closest('[data-testid="activity-step"]');
|
const run = screen.getByText(/Reviewed sources.*2 files/).closest('[data-testid="activity-step"]');
|
||||||
expect(run).toBeInTheDocument();
|
expect(run).toBeInTheDocument();
|
||||||
@@ -1678,6 +1698,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const row = screen.getByText("Could not search files “needle”").closest(
|
const row = screen.getByText("Could not search files “needle”").closest(
|
||||||
'[data-testid="activity-step"]',
|
'[data-testid="activity-step"]',
|
||||||
@@ -1706,6 +1727,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.queryByText(/password|signed-secret/)).not.toBeInTheDocument();
|
expect(screen.queryByText(/password|signed-secret/)).not.toBeInTheDocument();
|
||||||
expect(screen.getByText("Completed Download asset")).toBeInTheDocument();
|
expect(screen.getByText("Completed Download asset")).toBeInTheDocument();
|
||||||
@@ -1792,6 +1814,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.getByText("Edited")).toBeInTheDocument();
|
expect(screen.getByText("Edited")).toBeInTheDocument();
|
||||||
expect(screen.queryByText("+0")).not.toBeInTheDocument();
|
expect(screen.queryByText("+0")).not.toBeInTheDocument();
|
||||||
@@ -1886,6 +1909,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
|
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
|
||||||
expect(row).toBeInTheDocument();
|
expect(row).toBeInTheDocument();
|
||||||
@@ -1919,6 +1943,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
|
const row = screen.getByText("Could not edit").closest('[data-testid="activity-step"]');
|
||||||
expect(row).toBeInTheDocument();
|
expect(row).toBeInTheDocument();
|
||||||
@@ -1986,6 +2011,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
"-const fps = 30;",
|
"-const fps = 30;",
|
||||||
"+const fps = 60;",
|
"+const fps = 60;",
|
||||||
" start();",
|
" start();",
|
||||||
|
|
||||||
]),
|
]),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -1995,6 +2021,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const fileRefs = screen.getAllByTestId("activity-file-reference");
|
const fileRefs = screen.getAllByTestId("activity-file-reference");
|
||||||
expect(fileRefs).toHaveLength(3);
|
expect(fileRefs).toHaveLength(3);
|
||||||
@@ -2055,6 +2082,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.getByText("Edited")).toBeInTheDocument();
|
expect(screen.getByText("Edited")).toBeInTheDocument();
|
||||||
expect(screen.getByText("Could not edit")).toBeInTheDocument();
|
expect(screen.getByText("Could not edit")).toBeInTheDocument();
|
||||||
@@ -2162,6 +2190,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
expect(screen.getByText("Could not generate image")).toBeInTheDocument();
|
expect(screen.getByText("Could not generate image")).toBeInTheDocument();
|
||||||
const row = screen.getByText("Could not generate image").closest(
|
const row = screen.getByText("Could not generate image").closest(
|
||||||
@@ -2234,6 +2263,7 @@ describe("AgentActivityCluster", () => {
|
|||||||
hasBodyBelow={false}
|
hasBodyBelow={false}
|
||||||
/>,
|
/>,
|
||||||
);
|
);
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /^Worked/ }));
|
||||||
|
|
||||||
const steps = screen.getAllByTestId("activity-step");
|
const steps = screen.getAllByTestId("activity-step");
|
||||||
expect(steps.length).toBeGreaterThanOrEqual(3);
|
expect(steps.length).toBeGreaterThanOrEqual(3);
|
||||||
|
|||||||
@@ -39,6 +39,33 @@ vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
describe("CodeBlock", () => {
|
describe("CodeBlock", () => {
|
||||||
|
it("renders and copies a large code block in full without pagination", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
const writeText = vi.fn().mockResolvedValue(undefined);
|
||||||
|
Object.defineProperty(navigator, "clipboard", {
|
||||||
|
configurable: true,
|
||||||
|
value: { writeText },
|
||||||
|
});
|
||||||
|
const source = Array.from({ length: 1200 }, (_, i) => `const value${i} = ${i};`).join("\n");
|
||||||
|
|
||||||
|
try {
|
||||||
|
render(<CodeBlock code={source} language="typescript" showLineNumbers />);
|
||||||
|
expect((await screen.findByTestId("highlighted-code")).textContent).toBe(source);
|
||||||
|
expect(screen.getAllByRole("button")).toHaveLength(1);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Copy code" }));
|
||||||
|
expect(writeText).toHaveBeenCalledWith(source);
|
||||||
|
} finally {
|
||||||
|
Reflect.deleteProperty(navigator, "clipboard");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders long plain text with Unicode in full", () => {
|
||||||
|
const source = "x".repeat(23999) + "😀tail";
|
||||||
|
render(<CodeBlock code={source} highlight={false} />);
|
||||||
|
expect(screen.getByTestId("plain-code-fallback").textContent).toBe(source);
|
||||||
|
expect(screen.getAllByRole("button")).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
it("renders plain code without mounting the highlighter when highlighting is disabled", () => {
|
it("renders plain code without mounting the highlighter when highlighting is disabled", () => {
|
||||||
render(
|
render(
|
||||||
<ThemeProvider theme="dark">
|
<ThemeProvider theme="dark">
|
||||||
|
|||||||
@@ -757,6 +757,276 @@
|
|||||||
"turnSeq": 6
|
"turnSeq": 6
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "length_continuation_reasoning_then_new_recovery_turn",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"initial_messages": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "Write long code.",
|
||||||
|
"turnId": "long-turn",
|
||||||
|
"turnPhase": "user",
|
||||||
|
"turnSeq": 1,
|
||||||
|
"id": "length-user"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"live_events": [
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 2,
|
||||||
|
"text": "Plan."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 3
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 4,
|
||||||
|
"text": "```python\nfirst"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 5,
|
||||||
|
"text": "```python\nfirst",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 6,
|
||||||
|
"text": "Continue "
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 7,
|
||||||
|
"text": "code."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 8
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 9,
|
||||||
|
"text": "\nsecond"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 10,
|
||||||
|
"text": "```python\nfirst\nsecond",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 11,
|
||||||
|
"text": "Finish code."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 12
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 1,
|
||||||
|
"text": "Recover."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 3,
|
||||||
|
"text": "Recovered "
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 4,
|
||||||
|
"text": "Recovered ",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 5,
|
||||||
|
"text": "Continue recovery."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 6
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "delta",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 7,
|
||||||
|
"text": "answer."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 8,
|
||||||
|
"text": "Recovered answer."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "turn_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 9,
|
||||||
|
"latency_ms": 50
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"transcript": [
|
||||||
|
{
|
||||||
|
"event": "user",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"text": "Write long code.",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 3,
|
||||||
|
"text": "Plan."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 5,
|
||||||
|
"text": "```python\nfirst",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 8,
|
||||||
|
"text": "Continue code."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 10,
|
||||||
|
"text": "```python\nfirst\nsecond",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "long-turn",
|
||||||
|
"turn_seq": 12,
|
||||||
|
"text": "Finish code."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 2,
|
||||||
|
"text": "Recover."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 4,
|
||||||
|
"text": "Recovered ",
|
||||||
|
"resuming": true,
|
||||||
|
"merge_next": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "reasoning_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 6,
|
||||||
|
"text": "Continue recovery."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "stream_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 8,
|
||||||
|
"text": "Recovered answer."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"event": "turn_end",
|
||||||
|
"chat_id": "fixture-length-recovery",
|
||||||
|
"turn_id": "recovery-turn",
|
||||||
|
"turn_seq": 9,
|
||||||
|
"latency_ms": 50
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"expected": [
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": "Write long code.",
|
||||||
|
"turnId": "long-turn",
|
||||||
|
"turnPhase": "user",
|
||||||
|
"turnSeq": 1
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "```python\nfirst\nsecond",
|
||||||
|
"reasoning": "Plan.\n\nContinue code.\n\nFinish code.",
|
||||||
|
"turnId": "long-turn",
|
||||||
|
"turnPhase": "answer",
|
||||||
|
"turnSeq": 10,
|
||||||
|
"activitySegmentId": "segment-1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "Recovered answer.",
|
||||||
|
"reasoning": "Recover.\n\nContinue recovery.",
|
||||||
|
"turnId": "recovery-turn",
|
||||||
|
"turnPhase": "answer",
|
||||||
|
"turnSeq": 8,
|
||||||
|
"activitySegmentId": "segment-2",
|
||||||
|
"latencyMs": 50
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,17 @@
|
|||||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
|
||||||
import MarkdownTextRenderer from "@/components/MarkdownTextRenderer";
|
import MarkdownTextRenderer from "@/components/MarkdownTextRenderer";
|
||||||
|
|
||||||
|
|
||||||
|
// Exercise the asynchronous math boundary once, then test the loaded grammar cases.
|
||||||
|
beforeAll(async () => {
|
||||||
|
const view = render(<MarkdownTextRenderer>{"$$x^2$$"}</MarkdownTextRenderer>);
|
||||||
|
await waitFor(() => expect(view.container.querySelector(".katex")).toBeInTheDocument());
|
||||||
|
view.unmount();
|
||||||
|
});
|
||||||
|
|
||||||
describe("MarkdownTextRenderer", () => {
|
describe("MarkdownTextRenderer", () => {
|
||||||
it("renders clickable markdown links in blue", () => {
|
it("renders clickable markdown links in blue", () => {
|
||||||
render(<MarkdownTextRenderer>[local server](http://127.0.0.1:7891/)</MarkdownTextRenderer>);
|
render(<MarkdownTextRenderer>[local server](http://127.0.0.1:7891/)</MarkdownTextRenderer>);
|
||||||
|
|||||||
@@ -17,6 +17,17 @@ function session(index: number): ChatSummary {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("SessionSearchDialog", () => {
|
describe("SessionSearchDialog", () => {
|
||||||
|
it("windows large result sets and selects an item reached beyond the first window", () => {
|
||||||
|
const onSelect = vi.fn();
|
||||||
|
render(<SessionSearchDialog open sessions={Array.from({ length: 1000 }, (_, i) => session(i))}
|
||||||
|
activeKey={null} loading={false} onOpenChange={() => {}} onSelect={onSelect} />);
|
||||||
|
expect(screen.getAllByRole("button").length).toBeLessThanOrEqual(24);
|
||||||
|
const input = screen.getByRole("textbox", { name: "Search" });
|
||||||
|
for (let i = 0; i < 40; i++) fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||||
|
fireEvent.keyDown(input, { key: "Enter" });
|
||||||
|
expect(onSelect).toHaveBeenCalledWith("websocket:chat-40");
|
||||||
|
expect(screen.getAllByRole("button").length).toBeLessThanOrEqual(24);
|
||||||
|
});
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { render, screen } from "@testing-library/react";
|
import { fireEvent, render, screen } from "@testing-library/react";
|
||||||
|
import { useState } from "react";
|
||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { ThinkingReasoningShell } from "@/components/thread/activity/ThinkingReasoningShell";
|
import { ThinkingReasoningShell } from "@/components/thread/activity/ThinkingReasoningShell";
|
||||||
@@ -22,6 +23,26 @@ function renderShell(expanded: boolean) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("ThinkingReasoningShell", () => {
|
describe("ThinkingReasoningShell", () => {
|
||||||
|
it("mounts details on first expansion and preserves their state across folding", () => {
|
||||||
|
const mounted = vi.fn();
|
||||||
|
function Details() {
|
||||||
|
const [count, setCount] = useState(() => { mounted(); return 0; });
|
||||||
|
return <button onClick={() => setCount(count + 1)}>Count {count}</button>;
|
||||||
|
}
|
||||||
|
const shell = (expanded: boolean) => (
|
||||||
|
<ThinkingReasoningShell active={false} expanded={expanded} label="Thought"
|
||||||
|
viewportRef={null} contentRef={null} fadeTop={false} fadeBottom={false}
|
||||||
|
onToggle={() => {}} onScroll={() => {}}><Details /></ThinkingReasoningShell>
|
||||||
|
);
|
||||||
|
const view = render(shell(false));
|
||||||
|
expect(mounted).toHaveBeenCalledTimes(0);
|
||||||
|
view.rerender(shell(true));
|
||||||
|
fireEvent.click(screen.getByText("Count 0"));
|
||||||
|
view.rerender(shell(false));
|
||||||
|
view.rerender(shell(true));
|
||||||
|
expect(screen.getByRole("button", { name: "Count 1" })).toBeVisible();
|
||||||
|
expect(mounted).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
it("makes collapsed descendants inert as well as visually hidden", () => {
|
it("makes collapsed descendants inert as well as visually hidden", () => {
|
||||||
const { rerender } = renderShell(false);
|
const { rerender } = renderShell(false);
|
||||||
const disclosure = screen.getByRole("button", { name: "Thought" });
|
const disclosure = screen.getByRole("button", { name: "Thought" });
|
||||||
|
|||||||
@@ -9,6 +9,15 @@ import type { UIMessage } from "@/lib/types";
|
|||||||
|
|
||||||
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
|
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
|
||||||
|
|
||||||
|
it("reuses completed historical rows across streaming updates and recalculates changed start times", () => {
|
||||||
|
const prompt: UIMessage = { id: "u", role: "user", content: "hello", createdAt: 100 };
|
||||||
|
const answer: UIMessage = { id: "a", role: "assistant", content: "world", latencyMs: 50, createdAt: 120 };
|
||||||
|
const first = projectWebuiThreadMessages([prompt, answer]);
|
||||||
|
const second = projectWebuiThreadMessages([prompt, answer, { id: "next", role: "user", content: "next", createdAt: 200 }]);
|
||||||
|
expect(second[1]).toBe(first[1]);
|
||||||
|
expect(projectWebuiThreadMessages([{ ...prompt, createdAt: 200 }, answer])[1].completedAt).toBe(250);
|
||||||
|
});
|
||||||
|
|
||||||
function message(
|
function message(
|
||||||
role: UIMessage["role"],
|
role: UIMessage["role"],
|
||||||
overrides: Partial<Omit<UIMessage, "role">> = {},
|
overrides: Partial<Omit<UIMessage, "role">> = {},
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { expect, it } from "vitest";
|
||||||
|
import { ThreadMessageCache } from "@/lib/thread-message-cache";
|
||||||
|
import type { UIMessage } from "@/lib/types";
|
||||||
|
|
||||||
|
const rows: UIMessage[] = [{ id: "u", role: "user", content: "hello", createdAt: 1 }];
|
||||||
|
|
||||||
|
it("keeps recently visited chats within the entry budget", () => {
|
||||||
|
const cache = new ThreadMessageCache(() => false, 10000, 2);
|
||||||
|
cache.set("a", rows); cache.set("b", rows);
|
||||||
|
expect(cache.get("a")).toBe(rows);
|
||||||
|
cache.set("c", rows);
|
||||||
|
expect([cache.get("a"), cache.get("b"), cache.get("c")]).toEqual([rows, undefined, rows]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("bounds large replay snapshots while retaining temporary chats", () => {
|
||||||
|
const cache = new ThreadMessageCache((key) => key === "temporary", 1000, 2);
|
||||||
|
cache.set("temporary", rows);
|
||||||
|
cache.set("large", [{ ...rows[0], content: "x".repeat(1000) }]);
|
||||||
|
expect(cache.get("large")).toBeUndefined();
|
||||||
|
expect(cache.get("temporary")).toBe(rows);
|
||||||
|
cache.delete("temporary");
|
||||||
|
cache.set("small", rows);
|
||||||
|
expect(cache.get("small")).toBe(rows);
|
||||||
|
});
|
||||||
@@ -12,6 +12,7 @@ import type { UIMessage } from "@/lib/types";
|
|||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.restoreAllMocks();
|
vi.restoreAllMocks();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
vi.useRealTimers();
|
vi.useRealTimers();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -125,19 +126,26 @@ describe("ThreadMessages", () => {
|
|||||||
expect(screen.getByText("latest answer").closest(".thread-render-unit")).toBeNull();
|
expect(screen.getByText("latest answer").closest(".thread-render-unit")).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("still defers historical non-tail answers on their initial render", () => {
|
it("recycles offscreen historical content while preserving its measured space", () => {
|
||||||
render(
|
let notify: (entries: Array<{ isIntersecting: boolean }>) => void = () => {};
|
||||||
<ThreadMessages
|
vi.stubGlobal("IntersectionObserver", class {
|
||||||
messages={[
|
constructor(callback: typeof notify) { notify = callback; }
|
||||||
{ id: "u1", role: "user", content: "old question", createdAt: 1 },
|
observe() {}
|
||||||
{ id: "a1", role: "assistant", content: "historical answer", createdAt: 2 },
|
disconnect() {}
|
||||||
{ id: "u2", role: "user", content: "latest question", createdAt: 3 },
|
});
|
||||||
]}
|
const view = render(<ThreadMessages messages={[
|
||||||
isStreaming={false}
|
{ id: "u1", role: "user", content: "old question", createdAt: 1 },
|
||||||
/>,
|
{ id: "a1", role: "assistant", content: "historical answer", createdAt: 2 },
|
||||||
);
|
{ id: "u2", role: "user", content: "latest question", createdAt: 3 },
|
||||||
|
]} isStreaming={false} />);
|
||||||
expect(screen.getByText("historical answer").closest(".thread-render-unit")).not.toBeNull();
|
const unit = screen.getByText("historical answer").closest<HTMLElement>("[data-thread-display-unit]")!;
|
||||||
|
vi.spyOn(unit, "getBoundingClientRect").mockReturnValue({ height: 240 } as DOMRect);
|
||||||
|
act(() => notify([{ isIntersecting: false }]));
|
||||||
|
expect(unit.style.height).toBe("240px");
|
||||||
|
expect(unit.childElementCount).toBe(0);
|
||||||
|
act(() => notify([{ isIntersecting: true }]));
|
||||||
|
expect(screen.getByText("historical answer")).toBeVisible();
|
||||||
|
expect(view.container).toHaveTextContent("old question");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("preserves an answer's markdown tree across completion and the next prompt", async () => {
|
it("preserves an answer's markdown tree across completion and the next prompt", async () => {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type { ReactNode } from "react";
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
import { useNanobotStream } from "@/hooks/useNanobotStream";
|
||||||
|
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
|
||||||
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
|
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
|
||||||
import type { StreamError } from "@/lib/nanobot-client";
|
import type { StreamError } from "@/lib/nanobot-client";
|
||||||
import type {
|
import type {
|
||||||
@@ -344,6 +345,30 @@ describe("useNanobotStream", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("buffers a hidden chat view and flushes its ordered deltas on return", () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const fake = fakeClient();
|
||||||
|
const Client = wrap(fake.client);
|
||||||
|
let visible = false;
|
||||||
|
const { result, rerender, unmount } = renderHook(() => useNanobotStream("hidden-view", EMPTY_MESSAGES), {
|
||||||
|
wrapper: ({ children }) => <Client><ThreadVisibilityContext.Provider value={visible}>{children}</ThreadVisibilityContext.Provider></Client>,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
act(() => {
|
||||||
|
for (let seq = 1; seq <= 100; seq++) fake.emit("hidden-view", {
|
||||||
|
event: "delta", chat_id: "hidden-view", text: "x", turn_id: "turn", turn_seq: seq,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
expect(result.current.messages).toHaveLength(0);
|
||||||
|
visible = true;
|
||||||
|
rerender();
|
||||||
|
expect(result.current.messages[0]).toMatchObject({ content: "x".repeat(100), turnSeq: 100 });
|
||||||
|
} finally {
|
||||||
|
unmount();
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps the turn pending on disconnect without breaking a resumed stream", async () => {
|
it("keeps the turn pending on disconnect without breaking a resumed stream", async () => {
|
||||||
const fake = fakeClient();
|
const fake = fakeClient();
|
||||||
const { result } = renderHook(
|
const { result } = renderHook(
|
||||||
@@ -3409,18 +3434,53 @@ describe("useNanobotStream", () => {
|
|||||||
|
|
||||||
describe("live/replay projection before canonical-event revision migration", () => {
|
describe("live/replay projection before canonical-event revision migration", () => {
|
||||||
it.each(PROJECTION_FIXTURE_CASES)("matches the shared $name fixture", (fixtureCase) => {
|
it.each(PROJECTION_FIXTURE_CASES)("matches the shared $name fixture", (fixtureCase) => {
|
||||||
|
// Keep client-only elapsed-time estimates out of the transport contract.
|
||||||
|
const clock = vi.spyOn(Date, "now").mockReturnValue(0);
|
||||||
|
try {
|
||||||
|
const fake = fakeClient();
|
||||||
|
const { result } = renderHook(
|
||||||
|
() => useNanobotStream(fixtureCase.chat_id, fixtureCase.initial_messages),
|
||||||
|
{ wrapper: wrap(fake.client) },
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const event of fixtureCase.live_events) {
|
||||||
|
act(() => {
|
||||||
|
fake.emit(fixtureCase.chat_id, event);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(normalizeProjection(result.current.messages)).toEqual(fixtureCase.expected);
|
||||||
|
} finally {
|
||||||
|
clock.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([true, false])("keeps continuation reasoning before its answer across frames (text snapshots: %s)", async (snapshots) => {
|
||||||
|
const fixture = PROJECTION_FIXTURE_CASES.find(
|
||||||
|
(candidate) => candidate.name === "length_continuation_reasoning_then_new_recovery_turn",
|
||||||
|
)!;
|
||||||
const fake = fakeClient();
|
const fake = fakeClient();
|
||||||
const { result } = renderHook(
|
const { result } = renderHook(
|
||||||
() => useNanobotStream(fixtureCase.chat_id, fixtureCase.initial_messages),
|
() => useNanobotStream(fixture.chat_id, fixture.initial_messages),
|
||||||
{ wrapper: wrap(fake.client) },
|
{ wrapper: wrap(fake.client) },
|
||||||
);
|
);
|
||||||
|
for (const event of fixture.live_events) {
|
||||||
for (const event of fixtureCase.live_events) {
|
|
||||||
act(() => {
|
act(() => {
|
||||||
fake.emit(fixtureCase.chat_id, event);
|
fake.emit(fixture.chat_id, event.event === "stream_end" && !snapshots
|
||||||
|
? { ...event, text: undefined }
|
||||||
|
: event);
|
||||||
});
|
});
|
||||||
|
await flushStreamFrame();
|
||||||
}
|
}
|
||||||
|
const units = normalizeActivityTimeline(result.current.messages);
|
||||||
expect(normalizeProjection(result.current.messages)).toEqual(fixtureCase.expected);
|
expect(units.map((unit) => unit.type === "activity"
|
||||||
|
? unit.messages.map((message) => message.reasoning).join("")
|
||||||
|
: unit.message.content)).toEqual([
|
||||||
|
"Write long code.",
|
||||||
|
"Plan.\n\nContinue code.\n\nFinish code.",
|
||||||
|
"```python\nfirst\nsecond",
|
||||||
|
"Recover.\n\nContinue recovery.",
|
||||||
|
"Recovered answer.",
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -60,6 +60,35 @@ function wrap(
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("useSessions", () => {
|
describe("useSessions", () => {
|
||||||
|
it("coalesces a burst across tasks and preserves unchanged session identities", async () => {
|
||||||
|
const row = { key: "websocket:burst", channel: "websocket", chatId: "burst",
|
||||||
|
createdAt: "2026-09-08", updatedAt: "2026-09-08", preview: "Stable" };
|
||||||
|
vi.mocked(api.listSessions).mockImplementation(async () => [{ ...row }]);
|
||||||
|
const client = fakeClient();
|
||||||
|
const { result, unmount } = renderHook(() => useSessions(), { wrapper: wrap(client) });
|
||||||
|
await waitFor(() => expect(result.current.sessions).toHaveLength(1));
|
||||||
|
const original = result.current.sessions;
|
||||||
|
vi.useFakeTimers();
|
||||||
|
try {
|
||||||
|
for (let index = 0; index < 20; index++) {
|
||||||
|
await act(async () => {
|
||||||
|
client.emitSessionUpdate("burst");
|
||||||
|
await vi.advanceTimersByTimeAsync(10);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
expect(api.listSessions).toHaveBeenCalledTimes(1);
|
||||||
|
await act(async () => { await vi.advanceTimersByTimeAsync(50); });
|
||||||
|
expect(api.listSessions).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result.current.sessions).toBe(original);
|
||||||
|
client.emitSessionUpdate("burst");
|
||||||
|
unmount();
|
||||||
|
await vi.advanceTimersByTimeAsync(250);
|
||||||
|
expect(api.listSessions).toHaveBeenCalledTimes(2);
|
||||||
|
} finally {
|
||||||
|
vi.useRealTimers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.mocked(api.listSessions).mockReset();
|
vi.mocked(api.listSessions).mockReset();
|
||||||
vi.mocked(api.deleteSession).mockReset();
|
vi.mocked(api.deleteSession).mockReset();
|
||||||
@@ -266,8 +295,8 @@ describe("useSessions", () => {
|
|||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
});
|
});
|
||||||
|
|
||||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
await waitFor(() => expect(api.listSessions).toHaveBeenCalledTimes(2));
|
||||||
expect(api.listSessions).toHaveBeenCalledTimes(2);
|
expect(result.current.loading).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("runs one trailing refresh when an update arrives during a session request", async () => {
|
it("runs one trailing refresh when an update arrives during a session request", async () => {
|
||||||
|
|||||||
@@ -51,6 +51,15 @@ describe("entryLazyFeatureImports", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe("webuiManualChunk", () => {
|
describe("webuiManualChunk", () => {
|
||||||
|
it("groups common and channel translations into one request per locale", () => {
|
||||||
|
expect(webuiManualChunk("/repo/webui/src/i18n/locales/en/common.json")).toBe("locale-en");
|
||||||
|
expect(webuiManualChunk("/repo/nanobot/channels/slack/webui/locales/en.json")).toBe("locale-en");
|
||||||
|
expect(webuiManualChunk("/repo/nanobot/channels/slack/webui/locales/zh-CN.json")).toBe("locale-zh-CN");
|
||||||
|
expect(webuiManualChunk("/repo/node_modules/rehype-katex/index.js")).toBe("markdown-math");
|
||||||
|
expect(webuiManualChunk("/repo/webui/src/lib/markdown-math.ts")).toBe("markdown-math");
|
||||||
|
expect(webuiManualChunk("/repo/node_modules/micromark-extension-math/lib/html.js")).toBe("markdown-math");
|
||||||
|
expect(webuiManualChunk("/repo/webui/src/lib/clipboard.ts")).toBe("clipboard");
|
||||||
|
});
|
||||||
it("keeps the React runtime outside lazy feature chunks", () => {
|
it("keeps the React runtime outside lazy feature chunks", () => {
|
||||||
expect(webuiManualChunk("/repo/node_modules/react/index.js")).toBe("react-vendor");
|
expect(webuiManualChunk("/repo/node_modules/react/index.js")).toBe("react-vendor");
|
||||||
expect(webuiManualChunk("/repo/node_modules/react-dom/client.js")).toBe("react-vendor");
|
expect(webuiManualChunk("/repo/node_modules/react-dom/client.js")).toBe("react-vendor");
|
||||||
@@ -83,10 +92,10 @@ describe("webuiManualChunk", () => {
|
|||||||
it("leaves Streamdown's optional renderers as lazy chunks", () => {
|
it("leaves Streamdown's optional renderers as lazy chunks", () => {
|
||||||
expect(
|
expect(
|
||||||
webuiManualChunk("/repo/node_modules/streamdown/dist/mermaid-ABC.js"),
|
webuiManualChunk("/repo/node_modules/streamdown/dist/mermaid-ABC.js"),
|
||||||
).toBeUndefined();
|
).toBe("markdown-diagrams");
|
||||||
expect(
|
expect(
|
||||||
webuiManualChunk("/repo/node_modules/streamdown/dist/highlighted-body-ABC.js"),
|
webuiManualChunk("/repo/node_modules/streamdown/dist/highlighted-body-ABC.js"),
|
||||||
).toBeUndefined();
|
).toBe("markdown-code");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("leaves language grammars as independently loaded chunks", () => {
|
it("leaves language grammars as independently loaded chunks", () => {
|
||||||
|
|||||||
+13
-6
@@ -59,6 +59,17 @@ export function gzipWebuiAssets(): Plugin {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function webuiManualChunk(id: string): string | undefined {
|
export function webuiManualChunk(id: string): string | undefined {
|
||||||
|
const locale = /\/webui\/locales\/([^/]+)\.json$/.exec(id)?.[1]
|
||||||
|
?? /\/src\/i18n\/locales\/([^/]+)\/common\.json$/.exec(id)?.[1];
|
||||||
|
if (locale) return `locale-${locale}`;
|
||||||
|
// Clipboard actions are shared with lazy Markdown and must not pull it into the shell.
|
||||||
|
if (id.endsWith("/src/lib/clipboard.ts")) return "clipboard";
|
||||||
|
if (id.endsWith("/src/lib/markdown-math.ts")
|
||||||
|
|| id.includes("node_modules/rehype-katex/")
|
||||||
|
// The micromark barrel also exports an HTML renderer that imports KaTeX.
|
||||||
|
|| (id.includes("node_modules/micromark-extension-math/") && id.endsWith("/html.js"))) {
|
||||||
|
return "markdown-math";
|
||||||
|
}
|
||||||
if (
|
if (
|
||||||
id.includes("node_modules/react/")
|
id.includes("node_modules/react/")
|
||||||
|| id.includes("node_modules/react-dom/")
|
|| id.includes("node_modules/react-dom/")
|
||||||
@@ -73,12 +84,8 @@ export function webuiManualChunk(id: string): string | undefined {
|
|||||||
}
|
}
|
||||||
// Streamdown lazy-loads diagrams and highlighted code. Keep those modules
|
// Streamdown lazy-loads diagrams and highlighted code. Keep those modules
|
||||||
// outside the core markdown chunk so ordinary replies do not download them.
|
// outside the core markdown chunk so ordinary replies do not download them.
|
||||||
if (
|
if (id.includes("node_modules/streamdown/dist/mermaid-")) return "markdown-diagrams";
|
||||||
id.includes("node_modules/streamdown/dist/mermaid-")
|
if (id.includes("node_modules/streamdown/dist/highlighted-body-")) return "markdown-code";
|
||||||
|| id.includes("node_modules/streamdown/dist/highlighted-body-")
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Refractor reaches this HAST helper through hastscript. Keeping it with
|
// Refractor reaches this HAST helper through hastscript. Keeping it with
|
||||||
// Refractor prevents syntax-highlight <-> markdown-vendor circular chunks.
|
// Refractor prevents syntax-highlight <-> markdown-vendor circular chunks.
|
||||||
if (
|
if (
|
||||||
|
|||||||
Reference in new issue
Block a user