mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-06-11 09:55:59 +00:00
Merge remote-tracking branch 'origin/main' into codex/im-channel-connections
# Conflicts: # backend/app/channels/discord.py # backend/app/channels/manager.py # backend/app/channels/slack.py # backend/app/channels/telegram.py
This commit is contained in:
@@ -18,7 +18,8 @@ import {
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
|
||||
import { createContext, memo, useContext, useEffect, useState } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import { ClipboardSafeStreamdown } from "./streamdown";
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
@@ -302,11 +303,13 @@ export const MessageBranchPage = ({
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageResponseProps = ComponentProps<typeof Streamdown>;
|
||||
export type MessageResponseProps = ComponentProps<
|
||||
typeof ClipboardSafeStreamdown
|
||||
>;
|
||||
|
||||
export const MessageResponse = memo(
|
||||
({ className, ...props }: MessageResponseProps) => (
|
||||
<Streamdown
|
||||
<ClipboardSafeStreamdown
|
||||
className={cn(
|
||||
"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
className,
|
||||
|
||||
@@ -881,6 +881,7 @@ export type PromptInputTextareaProps = ComponentProps<
|
||||
|
||||
export const PromptInputTextarea = ({
|
||||
onChange,
|
||||
onKeyDown,
|
||||
className,
|
||||
placeholder = "What would you like to know?",
|
||||
...props
|
||||
@@ -891,6 +892,10 @@ export const PromptInputTextarea = ({
|
||||
const [isComposing, setIsComposing] = useState(false);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
|
||||
onKeyDown?.(e);
|
||||
if (e.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter") {
|
||||
if (isIMEComposing(e, isComposing)) {
|
||||
return;
|
||||
|
||||
@@ -10,9 +10,9 @@ import { cn } from "@/lib/utils";
|
||||
import { BrainIcon, ChevronDownIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, memo, useContext, useEffect, useState } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
import { reasoningPlugins } from "@/core/streamdown/plugins";
|
||||
import { Shimmer } from "./shimmer";
|
||||
import { ClipboardSafeStreamdown } from "./streamdown";
|
||||
|
||||
type ReasoningContextValue = {
|
||||
isStreaming: boolean;
|
||||
@@ -178,7 +178,9 @@ export const ReasoningContent = memo(
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Streamdown {...reasoningPlugins}>{children}</Streamdown>
|
||||
<ClipboardSafeStreamdown {...reasoningPlugins}>
|
||||
{children}
|
||||
</ClipboardSafeStreamdown>
|
||||
</CollapsibleContent>
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { type ComponentProps } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import { installClipboardFallback } from "@/core/clipboard";
|
||||
|
||||
export type ClipboardSafeStreamdownProps = ComponentProps<typeof Streamdown>;
|
||||
|
||||
// Only patch browser globals in client context; skip during SSR
|
||||
if (typeof document !== "undefined") {
|
||||
installClipboardFallback();
|
||||
}
|
||||
|
||||
export function ClipboardSafeStreamdown(props: ClipboardSafeStreamdownProps) {
|
||||
return <Streamdown {...props} />;
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import {
|
||||
Artifact,
|
||||
@@ -20,6 +19,7 @@ import {
|
||||
ArtifactHeader,
|
||||
ArtifactTitle,
|
||||
} from "@/components/ai-elements/artifact";
|
||||
import { ClipboardSafeStreamdown } from "@/components/ai-elements/streamdown";
|
||||
import { Select, SelectItem } from "@/components/ui/select";
|
||||
import {
|
||||
SelectContent,
|
||||
@@ -400,13 +400,13 @@ export function ArtifactFilePreview({
|
||||
if (language === "markdown") {
|
||||
return (
|
||||
<div className="size-full px-4">
|
||||
<Streamdown
|
||||
<ClipboardSafeStreamdown
|
||||
className="size-full"
|
||||
{...streamdownPlugins}
|
||||
components={{ a: ArtifactLink }}
|
||||
>
|
||||
{content ?? ""}
|
||||
</Streamdown>
|
||||
</ClipboardSafeStreamdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type KeyboardEvent,
|
||||
} from "react";
|
||||
|
||||
import {
|
||||
@@ -59,6 +60,8 @@ import { fetch } from "@/core/api/fetcher";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import type { Skill } from "@/core/skills";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import type { AgentThreadContext } from "@/core/threads";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -86,6 +89,48 @@ import { Tooltip } from "./tooltip";
|
||||
|
||||
type InputMode = "flash" | "thinking" | "pro" | "ultra";
|
||||
|
||||
const MAX_SKILL_SUGGESTIONS = 6;
|
||||
|
||||
function getLeadingSlashSkillQuery(value: string): string | null {
|
||||
if (!value.startsWith("/")) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const query = value.slice(1);
|
||||
if (query.includes("/") || /\s/.test(query)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
function getMatchingSkillSuggestions(skills: Skill[], query: string): Skill[] {
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
|
||||
return skills
|
||||
.map((skill, index) => ({
|
||||
skill,
|
||||
index,
|
||||
name: skill.name.toLowerCase(),
|
||||
}))
|
||||
.filter(({ skill, name }) => {
|
||||
if (!skill.enabled) {
|
||||
return false;
|
||||
}
|
||||
return !normalizedQuery || name.includes(normalizedQuery);
|
||||
})
|
||||
.sort((a, b) => {
|
||||
const aStartsWith = a.name.startsWith(normalizedQuery);
|
||||
const bStartsWith = b.name.startsWith(normalizedQuery);
|
||||
if (aStartsWith !== bStartsWith) {
|
||||
return aStartsWith ? -1 : 1;
|
||||
}
|
||||
return a.index - b.index;
|
||||
})
|
||||
.slice(0, MAX_SKILL_SUGGESTIONS)
|
||||
.map(({ skill }) => skill);
|
||||
}
|
||||
|
||||
function getResolvedMode(
|
||||
mode: InputMode | undefined,
|
||||
supportsThinking: boolean,
|
||||
@@ -153,11 +198,17 @@ export function InputBox({
|
||||
const { models } = useModels();
|
||||
const { thread, isMock } = useThread();
|
||||
const { textInput } = usePromptInputController();
|
||||
const { skills } = useSkills();
|
||||
const promptRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const [followups, setFollowups] = useState<string[]>([]);
|
||||
const [followupsHidden, setFollowupsHidden] = useState(false);
|
||||
const [followupsLoading, setFollowupsLoading] = useState(false);
|
||||
const [textareaFocused, setTextareaFocused] = useState(false);
|
||||
const [skillSuggestionIndex, setSkillSuggestionIndex] = useState(0);
|
||||
const [dismissedSkillSuggestionValue, setDismissedSkillSuggestionValue] =
|
||||
useState<string | null>(null);
|
||||
const lastGeneratedForAiIdRef = useRef<string | null>(null);
|
||||
const wasStreamingRef = useRef(false);
|
||||
const messagesRef = useRef(thread.messages);
|
||||
@@ -347,9 +398,98 @@ export function InputBox({
|
||||
setTimeout(() => requestFormSubmit(), 0);
|
||||
}, [pendingSuggestion, requestFormSubmit, textInput]);
|
||||
|
||||
const slashSkillQuery = useMemo(
|
||||
() => getLeadingSlashSkillQuery(textInput.value ?? ""),
|
||||
[textInput.value],
|
||||
);
|
||||
const skillSuggestions = useMemo(
|
||||
() =>
|
||||
slashSkillQuery === null
|
||||
? []
|
||||
: getMatchingSkillSuggestions(skills, slashSkillQuery),
|
||||
[skills, slashSkillQuery],
|
||||
);
|
||||
const showSkillSuggestions =
|
||||
!disabled &&
|
||||
textareaFocused &&
|
||||
slashSkillQuery !== null &&
|
||||
skillSuggestions.length > 0 &&
|
||||
dismissedSkillSuggestionValue !== textInput.value;
|
||||
|
||||
useEffect(() => {
|
||||
setSkillSuggestionIndex(0);
|
||||
}, [slashSkillQuery, skillSuggestions.length]);
|
||||
|
||||
const applySkillSuggestion = useCallback(
|
||||
(skill: Skill) => {
|
||||
const nextValue = `/${skill.name} `;
|
||||
textInput.setInput(nextValue);
|
||||
setDismissedSkillSuggestionValue(nextValue);
|
||||
requestAnimationFrame(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) {
|
||||
return;
|
||||
}
|
||||
textarea.focus();
|
||||
textarea.setSelectionRange(nextValue.length, nextValue.length);
|
||||
});
|
||||
},
|
||||
[textInput],
|
||||
);
|
||||
|
||||
const handleSkillSuggestionKeyDown = useCallback(
|
||||
(event: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (!showSkillSuggestions) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
setSkillSuggestionIndex(
|
||||
(index) => (index + 1) % skillSuggestions.length,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
setSkillSuggestionIndex(
|
||||
(index) =>
|
||||
(index - 1 + skillSuggestions.length) % skillSuggestions.length,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Enter" || event.key === "Tab") {
|
||||
if (event.shiftKey) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
const selectedSkill = skillSuggestions[skillSuggestionIndex];
|
||||
if (selectedSkill) {
|
||||
applySkillSuggestion(selectedSkill);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
setDismissedSkillSuggestionValue(textInput.value);
|
||||
}
|
||||
},
|
||||
[
|
||||
applySkillSuggestion,
|
||||
showSkillSuggestions,
|
||||
skillSuggestionIndex,
|
||||
skillSuggestions,
|
||||
textInput.value,
|
||||
],
|
||||
);
|
||||
|
||||
const showFollowups =
|
||||
!disabled &&
|
||||
!isWelcomeMode &&
|
||||
!showSkillSuggestions &&
|
||||
!followupsHidden &&
|
||||
(followupsLoading || followups.length > 0);
|
||||
|
||||
@@ -478,6 +618,48 @@ export function InputBox({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{showSkillSuggestions && (
|
||||
<div className="absolute right-0 bottom-full left-0 z-40 mb-2 px-1">
|
||||
<div
|
||||
aria-label="Skill suggestions"
|
||||
className="bg-popover/95 text-popover-foreground border-border max-h-72 overflow-y-auto rounded-xl border p-1 shadow-lg backdrop-blur-sm"
|
||||
role="listbox"
|
||||
>
|
||||
{skillSuggestions.map((skill, index) => {
|
||||
const selected = index === skillSuggestionIndex;
|
||||
return (
|
||||
<button
|
||||
aria-selected={selected}
|
||||
className={cn(
|
||||
"flex min-h-12 w-full min-w-0 cursor-pointer items-center gap-3 rounded-lg px-3 py-2 text-left transition-colors",
|
||||
selected
|
||||
? "bg-accent text-accent-foreground"
|
||||
: "text-popover-foreground hover:bg-accent/70 hover:text-accent-foreground",
|
||||
)}
|
||||
key={skill.name}
|
||||
onClick={() => applySkillSuggestion(skill)}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
onMouseEnter={() => setSkillSuggestionIndex(index)}
|
||||
role="option"
|
||||
type="button"
|
||||
>
|
||||
<SparklesIcon className="text-muted-foreground size-4 shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">
|
||||
/{skill.name}
|
||||
</span>
|
||||
{skill.description && (
|
||||
<span className="text-muted-foreground block truncate text-xs">
|
||||
{skill.description}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<PromptInput
|
||||
className={cn(
|
||||
"bg-background/85 rounded-2xl backdrop-blur-sm transition-all duration-300 ease-out *:data-[slot='input-group']:rounded-2xl",
|
||||
@@ -506,6 +688,10 @@ export function InputBox({
|
||||
placeholder={t.inputBox.placeholder}
|
||||
autoFocus={autoFocus}
|
||||
defaultValue={initialValue}
|
||||
onBlur={() => setTextareaFocused(false)}
|
||||
onFocus={() => setTextareaFocused(true)}
|
||||
onKeyDown={handleSkillSuggestionKeyDown}
|
||||
ref={textareaRef}
|
||||
/>
|
||||
</PromptInputBody>
|
||||
<PromptInputFooter className="flex">
|
||||
@@ -860,11 +1046,13 @@ export function InputBox({
|
||||
)}
|
||||
</PromptInput>
|
||||
|
||||
{isWelcomeMode && searchParams.get("mode") !== "skill" && (
|
||||
<div className="flex items-center justify-center pt-2">
|
||||
<SuggestionList />
|
||||
</div>
|
||||
)}
|
||||
{isWelcomeMode &&
|
||||
searchParams.get("mode") !== "skill" &&
|
||||
!showSkillSuggestions && (
|
||||
<div className="flex items-center justify-center pt-2">
|
||||
<SuggestionList />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
|
||||
<DialogContent>
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
XCircleIcon,
|
||||
} from "lucide-react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import {
|
||||
ChainOfThought,
|
||||
@@ -14,6 +13,7 @@ import {
|
||||
ChainOfThoughtStep,
|
||||
} from "@/components/ai-elements/chain-of-thought";
|
||||
import { Shimmer } from "@/components/ai-elements/shimmer";
|
||||
import { ClipboardSafeStreamdown } from "@/components/ai-elements/streamdown";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ShineBorder } from "@/components/ui/shine-border";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
@@ -126,12 +126,12 @@ export function SubtaskCard({
|
||||
{task.prompt && (
|
||||
<ChainOfThoughtStep
|
||||
label={
|
||||
<Streamdown
|
||||
<ClipboardSafeStreamdown
|
||||
{...streamdownPluginsWithWordAnimation}
|
||||
components={{ a: CitationLink }}
|
||||
>
|
||||
{task.prompt}
|
||||
</Streamdown>
|
||||
</ClipboardSafeStreamdown>
|
||||
}
|
||||
></ChainOfThoughtStep>
|
||||
)}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { Streamdown } from "streamdown";
|
||||
import { ClipboardSafeStreamdown } from "@/components/ai-elements/streamdown";
|
||||
|
||||
import { aboutMarkdown } from "./about-content";
|
||||
|
||||
export function AboutSettingsPage() {
|
||||
return <Streamdown>{aboutMarkdown}</Streamdown>;
|
||||
return <ClipboardSafeStreamdown>{aboutMarkdown}</ClipboardSafeStreamdown>;
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
import Link from "next/link";
|
||||
import { useDeferredValue, useId, useRef, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Streamdown } from "streamdown";
|
||||
|
||||
import { ClipboardSafeStreamdown } from "@/components/ai-elements/streamdown";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
@@ -639,12 +639,12 @@ export function MemorySettingsPage() {
|
||||
<div className="text-muted-foreground mb-4 text-sm">
|
||||
{summaryReadOnly}
|
||||
</div>
|
||||
<Streamdown
|
||||
<ClipboardSafeStreamdown
|
||||
className="size-full min-w-0 [overflow-wrap:anywhere] [&>*:first-child]:mt-0 [&>*:last-child]:mb-0"
|
||||
{...streamdownPlugins}
|
||||
>
|
||||
{summariesToMarkdown(memory, filteredSectionGroups, t)}
|
||||
</Streamdown>
|
||||
</ClipboardSafeStreamdown>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { User } from "./types";
|
||||
|
||||
export const AUTH_DISABLED_USER: User = {
|
||||
id: "e2e-user",
|
||||
email: "e2e@test.local",
|
||||
system_role: "admin",
|
||||
needs_setup: false,
|
||||
};
|
||||
|
||||
const PRODUCTION_ENV_VALUES = new Set(["prod", "production"]);
|
||||
|
||||
function isExplicitProductionEnvironment() {
|
||||
return ["DEER_FLOW_ENV", "ENVIRONMENT"].some((name) =>
|
||||
PRODUCTION_ENV_VALUES.has((process.env[name] ?? "").trim().toLowerCase()),
|
||||
);
|
||||
}
|
||||
|
||||
export function isAuthDisabledMode() {
|
||||
return (
|
||||
process.env.DEER_FLOW_AUTH_DISABLED === "1" &&
|
||||
!isExplicitProductionEnvironment()
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { cookies } from "next/headers";
|
||||
|
||||
import { isStaticWebsiteOnly } from "../static-mode";
|
||||
|
||||
import { AUTH_DISABLED_USER, isAuthDisabledMode } from "./auth-disabled-user";
|
||||
import { getGatewayConfig } from "./gateway-config";
|
||||
import { STATIC_WEBSITE_USER } from "./static-user";
|
||||
import { type AuthResult, userSchema } from "./types";
|
||||
@@ -20,15 +21,10 @@ export async function getServerSideUser(): Promise<AuthResult> {
|
||||
};
|
||||
}
|
||||
|
||||
if (process.env.DEER_FLOW_AUTH_DISABLED === "1") {
|
||||
if (isAuthDisabledMode()) {
|
||||
return {
|
||||
tag: "authenticated",
|
||||
user: {
|
||||
id: "e2e-user",
|
||||
email: "e2e@test.local",
|
||||
system_role: "admin",
|
||||
needs_setup: false,
|
||||
},
|
||||
user: AUTH_DISABLED_USER,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+246
-19
@@ -1,3 +1,47 @@
|
||||
type ClipboardItemLike = {
|
||||
types?: readonly string[];
|
||||
getType?: (type: string) => Promise<Blob>;
|
||||
items?: Record<string, Blob | string>;
|
||||
};
|
||||
|
||||
function copyTextWithExecCommand(text: string): boolean {
|
||||
const document = globalThis.document;
|
||||
if (
|
||||
typeof document?.createElement !== "function" ||
|
||||
typeof document.body?.appendChild !== "function" ||
|
||||
typeof document.execCommand !== "function"
|
||||
) {
|
||||
throw new Error("Clipboard DOM fallback not available");
|
||||
}
|
||||
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.setAttribute("readonly", "");
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.top = "-9999px";
|
||||
textarea.style.left = "-9999px";
|
||||
|
||||
let copied = false;
|
||||
let appended = false;
|
||||
try {
|
||||
document.body.appendChild(textarea);
|
||||
appended = true;
|
||||
textarea.select();
|
||||
copied = document.execCommand("copy");
|
||||
} finally {
|
||||
if (appended) {
|
||||
const parentNode = textarea.parentNode;
|
||||
if (typeof textarea.remove === "function") {
|
||||
textarea.remove();
|
||||
} else if (typeof parentNode?.removeChild === "function") {
|
||||
parentNode.removeChild(textarea);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return copied;
|
||||
}
|
||||
|
||||
export async function writeTextToClipboard(text: string): Promise<boolean> {
|
||||
try {
|
||||
const clipboard = globalThis.navigator?.clipboard;
|
||||
@@ -6,26 +50,209 @@ export async function writeTextToClipboard(text: string): Promise<boolean> {
|
||||
return true;
|
||||
}
|
||||
|
||||
const document = globalThis.document;
|
||||
if (!document?.body?.appendChild || !document.execCommand) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.setAttribute("readonly", "");
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.top = "-9999px";
|
||||
textarea.style.left = "-9999px";
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
|
||||
try {
|
||||
return document.execCommand("copy");
|
||||
} finally {
|
||||
textarea.remove();
|
||||
}
|
||||
return copyTextWithExecCommand(text);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackWriteText(text: string): Promise<void> {
|
||||
try {
|
||||
if (!copyTextWithExecCommand(text)) {
|
||||
return Promise.reject(new Error("Clipboard copy command failed"));
|
||||
}
|
||||
} catch (error) {
|
||||
return Promise.reject(
|
||||
error instanceof Error ? error : new Error(String(error)),
|
||||
);
|
||||
}
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function hasUsableClipboardItem(): boolean {
|
||||
return typeof globalThis.ClipboardItem === "function";
|
||||
}
|
||||
|
||||
async function readPlainTextFromClipboardItem(
|
||||
item: ClipboardItemLike,
|
||||
): Promise<string> {
|
||||
const plainText = item.items?.["text/plain"];
|
||||
if (typeof plainText === "string") {
|
||||
return plainText;
|
||||
}
|
||||
if (plainText instanceof Blob) {
|
||||
return await plainText.text();
|
||||
}
|
||||
|
||||
if (item.types && !item.types.includes("text/plain")) {
|
||||
throw new Error("Clipboard item is missing text/plain data");
|
||||
}
|
||||
|
||||
if (typeof item.getType !== "function") {
|
||||
throw new Error("Clipboard item cannot read text/plain data");
|
||||
}
|
||||
|
||||
const blob = await item.getType("text/plain");
|
||||
if (blob instanceof Blob) {
|
||||
return await blob.text();
|
||||
}
|
||||
|
||||
throw new Error("Clipboard item text/plain data is not a Blob");
|
||||
}
|
||||
|
||||
function canDefineNavigatorClipboard(
|
||||
navigator: Navigator,
|
||||
descriptor: PropertyDescriptor | undefined,
|
||||
): boolean {
|
||||
if (descriptor) {
|
||||
return descriptor.configurable === true;
|
||||
}
|
||||
return Object.isExtensible(navigator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs browser clipboard fallbacks for Streamdown copy controls by patching
|
||||
* missing navigator.clipboard methods and ClipboardItem when the host permits it.
|
||||
*/
|
||||
export function installClipboardFallback(): void {
|
||||
const navigator = globalThis.navigator;
|
||||
if (!navigator) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rawClipboard = navigator.clipboard;
|
||||
const clipboard =
|
||||
typeof rawClipboard === "object" && rawClipboard !== null
|
||||
? (rawClipboard as Partial<Clipboard>)
|
||||
: undefined;
|
||||
const clipboardDescriptor = Object.getOwnPropertyDescriptor(
|
||||
navigator,
|
||||
"clipboard",
|
||||
);
|
||||
const hasWriteText = typeof clipboard?.writeText === "function";
|
||||
const hasWrite = typeof clipboard?.write === "function";
|
||||
const hasClipboardItem = hasUsableClipboardItem();
|
||||
|
||||
if (hasWriteText && hasWrite && hasClipboardItem) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writeText = hasWriteText
|
||||
? clipboard.writeText!.bind(clipboard)
|
||||
: fallbackWriteText;
|
||||
const write = hasWrite
|
||||
? clipboard.write!.bind(clipboard)
|
||||
: (items: ClipboardItemLike[]) => {
|
||||
const firstItem = items[0];
|
||||
if (!firstItem) {
|
||||
return Promise.reject(new Error("Clipboard item not available"));
|
||||
}
|
||||
|
||||
return readPlainTextFromClipboardItem(firstItem).then(writeText);
|
||||
};
|
||||
|
||||
const fallbackClipboard = clipboard ?? {};
|
||||
|
||||
try {
|
||||
const missingMethods: PropertyDescriptorMap = {};
|
||||
if (!hasWrite) {
|
||||
missingMethods.write = {
|
||||
configurable: true,
|
||||
value: write,
|
||||
writable: true,
|
||||
};
|
||||
}
|
||||
if (!hasWriteText) {
|
||||
missingMethods.writeText = {
|
||||
configurable: true,
|
||||
value: writeText,
|
||||
writable: true,
|
||||
};
|
||||
}
|
||||
|
||||
Object.defineProperties(fallbackClipboard, missingMethods);
|
||||
|
||||
if (
|
||||
!clipboard &&
|
||||
canDefineNavigatorClipboard(navigator, clipboardDescriptor)
|
||||
) {
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: fallbackClipboard,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
if (!canDefineNavigatorClipboard(navigator, clipboardDescriptor)) {
|
||||
// The ClipboardItem fallback below is independent from navigator.clipboard.
|
||||
if (hasClipboardItem) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const replacement = Object.create(clipboard ?? null);
|
||||
for (const methodName of ["read", "readText"] as const) {
|
||||
const method = clipboard?.[methodName];
|
||||
if (typeof method === "function") {
|
||||
Object.defineProperty(replacement, methodName, {
|
||||
configurable: true,
|
||||
value: method.bind(clipboard),
|
||||
writable: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
Object.defineProperties(replacement, {
|
||||
write: {
|
||||
configurable: true,
|
||||
value: write,
|
||||
writable: true,
|
||||
},
|
||||
writeText: {
|
||||
configurable: true,
|
||||
value: writeText,
|
||||
writable: true,
|
||||
},
|
||||
});
|
||||
try {
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
configurable: true,
|
||||
value: replacement,
|
||||
});
|
||||
} catch {
|
||||
// The ClipboardItem fallback below is independent from navigator.clipboard.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasClipboardItem) {
|
||||
class ClipboardItemFallback {
|
||||
items: Record<string, Blob | string>;
|
||||
types: string[];
|
||||
|
||||
constructor(items: Record<string, Blob | string>) {
|
||||
this.items = items;
|
||||
this.types = Object.keys(items);
|
||||
}
|
||||
|
||||
getType(type: string): Promise<Blob> {
|
||||
const value = this.items[type];
|
||||
if (value instanceof Blob) {
|
||||
return Promise.resolve(value);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return Promise.resolve(new Blob([value], { type }));
|
||||
}
|
||||
return Promise.reject(
|
||||
new Error(`Clipboard item is missing ${type} data`),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Object.defineProperty(globalThis, "ClipboardItem", {
|
||||
configurable: true,
|
||||
value: ClipboardItemFallback,
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,10 +469,14 @@ export function findToolCallResult(toolCallId: string, messages: Message[]) {
|
||||
}
|
||||
|
||||
export function isHiddenFromUIMessage(message: Message) {
|
||||
const content = extractTextFromMessage(message);
|
||||
return (
|
||||
message.additional_kwargs?.hide_from_ui === true ||
|
||||
(typeof message.name === "string" &&
|
||||
HIDDEN_CONTROL_MESSAGE_NAMES.has(message.name))
|
||||
HIDDEN_CONTROL_MESSAGE_NAMES.has(message.name)) ||
|
||||
(message.type === "human" &&
|
||||
content.includes("<slash_skill_activation>") &&
|
||||
stripUploadedFilesTag(content).length === 0)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -488,12 +492,13 @@ export interface FileInMessage {
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip <uploaded_files> tag from message content.
|
||||
* Returns the content with the tag removed.
|
||||
* Strip backend-injected human context tags from message content.
|
||||
* Kept under its historical name because callers use it for uploaded-file
|
||||
* display cleanup.
|
||||
*/
|
||||
export function stripUploadedFilesTag(content: string): string {
|
||||
return content
|
||||
.replace(/<uploaded_files>[\s\S]*?<\/uploaded_files>/g, "")
|
||||
.replace(/<(uploaded_files|slash_skill_activation)>[\s\S]*?<\/\1>/g, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
@@ -504,6 +509,7 @@ export function stripUploadedFilesTag(content: string): string {
|
||||
* These markers are *not* user copy — they come from:
|
||||
*
|
||||
* - ``UploadsMiddleware`` → ``<uploaded_files>``
|
||||
* - ``SkillActivationMiddleware`` → ``<slash_skill_activation>``
|
||||
* - ``DynamicContextMiddleware`` → ``<system-reminder>`` (carrying
|
||||
* ``<memory>`` / ``<current_date>`` inside)
|
||||
* - ``TodoListMiddleware`` / ``LoopDetectionMiddleware`` style reminders
|
||||
@@ -517,6 +523,7 @@ export function stripUploadedFilesTag(content: string): string {
|
||||
*/
|
||||
export const INTERNAL_MARKER_TAGS = [
|
||||
"uploaded_files",
|
||||
"slash_skill_activation",
|
||||
"system-reminder",
|
||||
"memory",
|
||||
"current_date",
|
||||
|
||||
@@ -364,7 +364,7 @@ export function useThreadStream({
|
||||
loadMore: loadMoreHistory,
|
||||
loading: isHistoryLoading,
|
||||
appendMessages,
|
||||
} = useThreadHistory(onStreamThreadId ?? "");
|
||||
} = useThreadHistory(onStreamThreadId ?? "", { enabled: !isMock });
|
||||
|
||||
// Keep listeners ref updated with latest callbacks
|
||||
useEffect(() => {
|
||||
@@ -854,8 +854,15 @@ export function useThreadStream({
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function useThreadHistory(threadId: string) {
|
||||
const runs = useThreadRuns(threadId);
|
||||
type ThreadHistoryOptions = {
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
export function useThreadHistory(
|
||||
threadId: string,
|
||||
{ enabled = true }: ThreadHistoryOptions = {},
|
||||
) {
|
||||
const runs = useThreadRuns(threadId, { enabled });
|
||||
const threadIdRef = useRef(threadId);
|
||||
const runsRef = useRef(runs.data ?? []);
|
||||
const indexRef = useRef(-1);
|
||||
@@ -864,10 +871,15 @@ export function useThreadHistory(threadId: string) {
|
||||
const loadingRunIdRef = useRef<string | null>(null);
|
||||
const loadedRunIdsRef = useRef<Set<string>>(new Set());
|
||||
const runBeforeSeqRef = useRef<Map<string, number>>(new Map());
|
||||
const loadGenerationRef = useRef(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
|
||||
const loadMessages = useCallback(async () => {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
const loadGeneration = loadGenerationRef.current;
|
||||
if (loadingRef.current) {
|
||||
const pendingRunIndex = findLatestUnloadedRunIndex(
|
||||
runsRef.current,
|
||||
@@ -921,12 +933,15 @@ export function useThreadHistory(threadId: string) {
|
||||
}).then((res) => {
|
||||
return res.json();
|
||||
});
|
||||
if (
|
||||
loadGenerationRef.current !== loadGeneration ||
|
||||
threadIdRef.current !== requestThreadId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const _messages = result.data
|
||||
.filter((m) => !m.metadata.caller?.startsWith("middleware:"))
|
||||
.map((m) => m.content);
|
||||
if (threadIdRef.current !== requestThreadId) {
|
||||
return;
|
||||
}
|
||||
setMessages((prev) =>
|
||||
dedupeMessagesByIdentity([..._messages, ...prev]),
|
||||
);
|
||||
@@ -961,16 +976,19 @@ export function useThreadHistory(threadId: string) {
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
loadingRef.current = false;
|
||||
loadingRunIdRef.current = null;
|
||||
setLoading(false);
|
||||
if (loadGenerationRef.current === loadGeneration) {
|
||||
loadingRef.current = false;
|
||||
loadingRunIdRef.current = null;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
}, [enabled]);
|
||||
useEffect(() => {
|
||||
const threadChanged = threadIdRef.current !== threadId;
|
||||
threadIdRef.current = threadId;
|
||||
|
||||
if (threadChanged) {
|
||||
if (!enabled || threadChanged) {
|
||||
loadGenerationRef.current += 1;
|
||||
runsRef.current = [];
|
||||
indexRef.current = -1;
|
||||
pendingLoadRef.current = false;
|
||||
@@ -982,6 +1000,10 @@ export function useThreadHistory(threadId: string) {
|
||||
setMessages([]);
|
||||
}
|
||||
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (runs.data && runs.data.length > 0) {
|
||||
runsRef.current = runs.data ?? [];
|
||||
indexRef.current = findLatestUnloadedRunIndex(
|
||||
@@ -992,14 +1014,15 @@ export function useThreadHistory(threadId: string) {
|
||||
loadMessages().catch(() => {
|
||||
toast.error("Failed to load thread history.");
|
||||
});
|
||||
}, [threadId, runs.data, loadMessages]);
|
||||
}, [enabled, threadId, runs.data, loadMessages]);
|
||||
|
||||
const appendMessages = useCallback((_messages: Message[]) => {
|
||||
setMessages((prev) => {
|
||||
return dedupeMessagesByIdentity([...prev, ..._messages]);
|
||||
});
|
||||
}, []);
|
||||
const hasMore = indexRef.current >= 0 || !runs.data;
|
||||
const hasMore =
|
||||
enabled && Boolean(threadId) && (indexRef.current >= 0 || !runs.data);
|
||||
return {
|
||||
runs: runs.data,
|
||||
messages,
|
||||
@@ -1077,7 +1100,10 @@ export function useThreads(
|
||||
});
|
||||
}
|
||||
|
||||
export function useThreadRuns(threadId?: string) {
|
||||
export function useThreadRuns(
|
||||
threadId?: string,
|
||||
{ enabled = true }: { enabled?: boolean } = {},
|
||||
) {
|
||||
const apiClient = getAPIClient();
|
||||
return useQuery<Run[]>({
|
||||
queryKey: ["thread", threadId],
|
||||
@@ -1088,6 +1114,7 @@ export function useThreadRuns(threadId?: string) {
|
||||
const response = await apiClient.runs.list(threadId);
|
||||
return response;
|
||||
},
|
||||
enabled: enabled && Boolean(threadId),
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user