283 lines
11 KiB
TypeScript
283 lines
11 KiB
TypeScript
"use client";
|
|
|
|
import { BotIcon, PlusSquare } from "lucide-react";
|
|
import { useParams, useRouter } from "next/navigation";
|
|
import { useRouteBase } from "@/core/route-base";
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
|
|
import type { PromptInputMessage } from "@/components/ai-elements/prompt-input";
|
|
import { Button } from "@/components/ui/button";
|
|
import { AgentWelcome } from "@/components/workspace/agent-welcome";
|
|
import { ArtifactTrigger } from "@/components/workspace/artifacts";
|
|
import { ChatBox, useThreadChat } from "@/components/workspace/chats";
|
|
import { ExportTrigger } from "@/components/workspace/export-trigger";
|
|
import { InputBox } from "@/components/workspace/input-box";
|
|
import {
|
|
MessageList,
|
|
MESSAGE_LIST_DEFAULT_PADDING_BOTTOM,
|
|
MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM,
|
|
} from "@/components/workspace/messages";
|
|
import { ThreadContext } from "@/components/workspace/messages/context";
|
|
import { ThreadTitle } from "@/components/workspace/thread-title";
|
|
import { TodoList } from "@/components/workspace/todo-list";
|
|
import { TokenUsageIndicator } from "@/components/workspace/token-usage-indicator";
|
|
import { Tooltip } from "@/components/workspace/tooltip";
|
|
import { useAgent } from "@/core/agents";
|
|
import { useI18n } from "@/core/i18n/hooks";
|
|
import { useModels } from "@/core/models/hooks";
|
|
import { useNotification } from "@/core/notification/hooks";
|
|
import { useThreadSettings } from "@/core/settings";
|
|
import { useThreadStream } from "@/core/threads/hooks";
|
|
import { textOfMessage } from "@/core/threads/utils";
|
|
import { env } from "@/env";
|
|
import { desensitize } from "@/lib/desensitize";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
export default function AgentChatPage() {
|
|
const routeBase = useRouteBase();
|
|
const { t } = useI18n();
|
|
const [showFollowups, setShowFollowups] = useState(false);
|
|
const router = useRouter();
|
|
|
|
const { agent_id } = useParams<{
|
|
agent_id: string;
|
|
}>();
|
|
|
|
// If ChatPage stashed an opening message for this agent, skip the landing
|
|
// screen on first render so the user doesn't see a flash of the welcome UI
|
|
// before the auto-sent message takes over.
|
|
const hasPendingForThisAgent = () => {
|
|
if (typeof window === "undefined" || !agent_id) return false;
|
|
try {
|
|
const raw = sessionStorage.getItem("pendingAgentMessage");
|
|
if (!raw) return false;
|
|
const parsed = JSON.parse(raw);
|
|
return parsed?.agentId === agent_id && !!parsed?.text;
|
|
} catch {
|
|
return false;
|
|
}
|
|
};
|
|
const [hasStartedConversation, setHasStartedConversation] = useState(
|
|
hasPendingForThisAgent,
|
|
);
|
|
|
|
const { agent, isLoading: isAgentLoading } = useAgent(agent_id);
|
|
const agentDisplayName = desensitize(
|
|
agent?.name ?? (isAgentLoading ? t.common.loading : ""),
|
|
);
|
|
|
|
const { threadId, setThreadId, isNewThread, setIsNewThread } =
|
|
useThreadChat();
|
|
const [settings, setSettings] = useThreadSettings(threadId);
|
|
const { tokenUsageEnabled } = useModels();
|
|
|
|
useEffect(() => {
|
|
if (isNewThread) {
|
|
setHasStartedConversation(hasPendingForThisAgent());
|
|
}
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [isNewThread, threadId, agent_id]);
|
|
|
|
const { showNotification } = useNotification();
|
|
const [thread, sendMessage] = useThreadStream({
|
|
threadId: isNewThread ? undefined : threadId,
|
|
assistantId: agent_id,
|
|
context: { ...settings.context, agent_id },
|
|
onStart: (createdThreadId) => {
|
|
setThreadId(createdThreadId);
|
|
setIsNewThread(false);
|
|
// Keep the current component mounted while updating the hash route.
|
|
history.replaceState(
|
|
null,
|
|
"",
|
|
`${window.location.pathname}${window.location.search}#${routeBase}/agents/${agent_id}/chats/${createdThreadId}`,
|
|
);
|
|
},
|
|
onFinish: (state) => {
|
|
if (document.hidden || !document.hasFocus()) {
|
|
let body = "Conversation finished";
|
|
const lastMessage = state.messages[state.messages.length - 1];
|
|
if (lastMessage) {
|
|
const textContent = textOfMessage(lastMessage);
|
|
if (textContent) {
|
|
body =
|
|
textContent.length > 200
|
|
? textContent.substring(0, 200) + "..."
|
|
: textContent;
|
|
}
|
|
}
|
|
showNotification(state.title, { body });
|
|
}
|
|
},
|
|
});
|
|
|
|
const handleSubmit = useCallback(
|
|
(message: PromptInputMessage) => {
|
|
setHasStartedConversation(true);
|
|
window.dispatchEvent(
|
|
new CustomEvent("workspace:sandbox-resume-autoscroll"),
|
|
);
|
|
void sendMessage(threadId, message, { agent_id });
|
|
},
|
|
[sendMessage, threadId, agent_id],
|
|
);
|
|
|
|
// ChatPage stashes the opening message in sessionStorage when the user picks
|
|
// an agent on the landing screen, then redirects here. Replay it once so the
|
|
// user doesn't have to re-type the question on the agent chat page.
|
|
const pendingMessageHandled = useRef(false);
|
|
useEffect(() => {
|
|
if (pendingMessageHandled.current) return;
|
|
if (!agent_id || !isNewThread || hasStartedConversation) return;
|
|
let pending: { agentId?: string; text?: string } | null = null;
|
|
try {
|
|
const raw = sessionStorage.getItem("pendingAgentMessage");
|
|
if (raw) pending = JSON.parse(raw);
|
|
} catch {
|
|
pending = null;
|
|
}
|
|
if (!pending || pending.agentId !== agent_id || !pending.text) return;
|
|
pendingMessageHandled.current = true;
|
|
sessionStorage.removeItem("pendingAgentMessage");
|
|
handleSubmit({ text: pending.text, files: [] });
|
|
}, [agent_id, isNewThread, hasStartedConversation, handleSubmit]);
|
|
|
|
const handleClarificationSubmit = useCallback(
|
|
(answer: string) => {
|
|
setHasStartedConversation(true);
|
|
void sendMessage(threadId, { text: answer, files: [] }, { agent_id });
|
|
},
|
|
[sendMessage, threadId, agent_id],
|
|
);
|
|
|
|
const handleStop = useCallback(async () => {
|
|
await thread.stop();
|
|
}, [thread]);
|
|
|
|
const messageListPaddingBottom = showFollowups
|
|
? MESSAGE_LIST_DEFAULT_PADDING_BOTTOM +
|
|
MESSAGE_LIST_FOLLOWUPS_EXTRA_PADDING_BOTTOM
|
|
: undefined;
|
|
const isLandingState = isNewThread && !hasStartedConversation;
|
|
|
|
return (
|
|
<ThreadContext.Provider value={{ thread }}>
|
|
<ChatBox threadId={threadId}>
|
|
<div className="relative flex size-full min-h-0 justify-between">
|
|
<header
|
|
className={cn(
|
|
"absolute top-0 right-0 left-0 z-30 flex h-12 shrink-0 items-center gap-2 border-b px-4",
|
|
isLandingState
|
|
? "border-transparent bg-transparent"
|
|
: "bg-card/90 border-border/70 shadow-sm backdrop-blur-md",
|
|
)}
|
|
>
|
|
{/* Agent badge */}
|
|
<div className="flex shrink-0 items-center gap-1.5 rounded-md border px-2 py-1">
|
|
<BotIcon className="text-primary h-3.5 w-3.5" />
|
|
<span
|
|
className="max-w-[200px] truncate text-xs font-medium"
|
|
title={agentDisplayName}
|
|
>
|
|
{agentDisplayName}
|
|
</span>
|
|
</div>
|
|
|
|
<div className="flex w-full items-center text-sm font-medium">
|
|
<ThreadTitle threadId={threadId} thread={thread} />
|
|
</div>
|
|
<div className="mr-4 flex items-center">
|
|
<Tooltip content={t.agents.newChat}>
|
|
<Button
|
|
size="sm"
|
|
variant="secondary"
|
|
onClick={() => {
|
|
router.push(`/page/workspace/agents/${agent_id}/chats/new`);
|
|
}}
|
|
>
|
|
<PlusSquare /> {t.agents.newChat}
|
|
</Button>
|
|
</Tooltip>
|
|
<TokenUsageIndicator
|
|
enabled={tokenUsageEnabled}
|
|
messages={thread.messages}
|
|
/>
|
|
<ExportTrigger threadId={threadId} />
|
|
<ArtifactTrigger />
|
|
</div>
|
|
</header>
|
|
|
|
<main className="flex min-h-0 max-w-full grow flex-col">
|
|
<div className="flex size-full justify-center">
|
|
<MessageList
|
|
className={cn("size-full", !isLandingState && "pt-10")}
|
|
threadId={threadId}
|
|
thread={thread}
|
|
paddingBottom={messageListPaddingBottom}
|
|
tokenUsageEnabled={tokenUsageEnabled}
|
|
onClarificationSubmit={handleClarificationSubmit}
|
|
/>
|
|
</div>
|
|
|
|
<div className="absolute right-0 bottom-0 left-0 z-30 flex justify-center px-4">
|
|
<div
|
|
className={cn(
|
|
"relative w-full",
|
|
isLandingState && "-translate-y-[calc(50vh-96px)]",
|
|
isLandingState
|
|
? "max-w-(--container-width-md)"
|
|
: "max-w-(--container-width-lg)",
|
|
)}
|
|
>
|
|
<div className="absolute -top-4 right-0 left-0 z-0">
|
|
<div className="absolute right-0 bottom-0 left-0">
|
|
<TodoList
|
|
className="bg-background/5"
|
|
todos={thread.values.todos ?? []}
|
|
hidden={
|
|
!thread.values.todos || thread.values.todos.length === 0
|
|
}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="w-full -translate-y-4">
|
|
<InputBox
|
|
className="w-full"
|
|
isNewThread={isLandingState}
|
|
threadId={threadId}
|
|
autoFocus={isLandingState}
|
|
status={
|
|
thread.error
|
|
? "error"
|
|
: thread.isLoading
|
|
? "streaming"
|
|
: "ready"
|
|
}
|
|
context={settings.context}
|
|
extraHeader={
|
|
isLandingState && (
|
|
<AgentWelcome agent={agent} agentName={agentDisplayName} />
|
|
)
|
|
}
|
|
disabled={env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true"}
|
|
onContextChange={(context) => setSettings("context", context)}
|
|
onFollowupsVisibilityChange={setShowFollowups}
|
|
onSubmit={handleSubmit}
|
|
onStop={handleStop}
|
|
/>
|
|
</div>
|
|
{env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" && (
|
|
<div className="text-muted-foreground/67 w-full translate-y-12 text-center text-xs">
|
|
{t.common.notAvailableInDemoMode}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
</div>
|
|
</ChatBox>
|
|
</ThreadContext.Provider>
|
|
);
|
|
}
|