Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions apps/web/src/components/agent-header.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as stylex from "@stylexjs/stylex";
import { Link } from "@tanstack/react-router";
import type { ReactNode } from "react";
import { Link, useRouter } from "@tanstack/react-router";
import { type ReactNode, useEffect } from "react";
import type { Agent } from "../features/agents/schema";
import { useDashboardsEnabled } from "../features/dashboards/preference";
import { motion } from "../styles/motion.stylex";
Expand All @@ -19,6 +19,26 @@ export function AgentHeader({
children?: ReactNode;
}) {
const dashboardsEnabled = useDashboardsEnabled();
const showDashboard = dashboard || dashboardsEnabled;
const router = useRouter();
// Warm every tab so a click or tap renders from the router cache at once;
// the destination then refreshes in the background. Preloads within the
// router's preload stale time are free, so remounting the header is cheap.
useEffect(() => {
const timer = setTimeout(() => {
const params = { agentId: agent.id };
const tabs = [
"/agents/$agentId",
"/agents/$agentId/note",
...(agent.kind === "coding" ? ["/agents/$agentId/jobs" as const] : []),
...(showDashboard ? ["/agents/$agentId/dashboard" as const] : []),
] as const;
for (const to of tabs)
if (!router.matchRoute({ to, params }))
void router.preloadRoute({ to, params }).catch(() => {});
}, 250);
return () => clearTimeout(timer);
}, [router, agent.id, agent.kind, showDashboard]);
return (
<header {...stylex.props(styles.header)}>
<div {...stylex.props(styles.identity)}>
Expand Down Expand Up @@ -55,7 +75,7 @@ export function AgentHeader({
Jobs
</Link>
)}
{(dashboard || dashboardsEnabled) && (
{showDashboard && (
<Link
to="/agents/$agentId/dashboard"
params={{ agentId: agent.id }}
Expand Down
260 changes: 153 additions & 107 deletions apps/web/src/components/conversation.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as stylex from "@stylexjs/stylex";
import {
lazy,
memo,
type ReactNode,
Suspense,
useCallback,
useEffect,
Expand All @@ -15,6 +17,7 @@ import {
type InitialConversation,
openThread,
} from "../features/chat/functions";
import type { Message } from "../features/chat/schema";
import { useConversation } from "../features/chat/use-conversation";
import { computerPreviewAnchor } from "../features/computer/preview";
import { useLiveEntries, useMountedAfterLoad } from "../features/motion";
Expand Down Expand Up @@ -74,7 +77,7 @@ export function Conversation({
title?: string;
onClose?: () => void;
conversationId?: string;
parent?: import("../features/chat/schema").Message;
parent?: Message;
onOpenThread?: (id: string) => void;
suggestion?: { id: number; text: string };
}) {
Expand Down Expand Up @@ -350,6 +353,43 @@ export function Conversation({
};
}, [updateBottomButton]);

// Rows are memoized, so they get stable handlers that read the latest state.
const latest = useRef({ react, threads, onOpenThread });
useLayoutEffect(() => {
latest.current = { react, threads, onOpenThread };
});
const reactToMessage = useCallback(
(messageId: string, emoji: string, active: boolean) =>
latest.current.react(messageId, emoji, active),
[],
);
const openReplyToMessage = useCallback(
async (messageId: string) => {
const { threads, onOpenThread } = latest.current;
if (!onOpenThread) return;
const existingThread = threads.find(
(thread) => thread.parentMessageId === messageId,
);
if (existingThread) {
setThreadError(undefined);
onOpenThread(existingThread.id);
return;
}
try {
const result = await openThread({
data: { agentId: agent.id, parentMessageId: messageId },
});
if (result.ok) {
setThreadError(undefined);
onOpenThread(result.value.id);
} else setThreadError(result.error);
} catch {
setThreadError("Could not open this thread. Please retry.");
}
},
[agent.id],
);

function replyLabel(messageId: string) {
const thread = threads.find((t) => t.parentMessageId === messageId);
return thread
Expand Down Expand Up @@ -500,116 +540,23 @@ export function Conversation({
)}
{threadError && <p role="alert">{threadError}</p>}
{messages.map((message, index) => {
const existingThread = threads.find(
const thread = threads.find(
(thread) => thread.parentMessageId === message.id,
);
const openReply = async () => {
if (!onOpenThread) return;
if (existingThread) {
setThreadError(undefined);
onOpenThread(existingThread.id);
return;
}
try {
const result = await openThread({
data: {
agentId: agent.id,
parentMessageId: message.id,
},
});
if (result.ok) {
setThreadError(undefined);
onOpenThread(result.value.id);
} else setThreadError(result.error);
} catch {
setThreadError("Could not open this thread. Please retry.");
}
};

const replyAction = onOpenThread &&
message.role === "assistant" && (
<Button
xstyle={styles.replyAction}
title="Reply in thread"
aria-label="Reply in thread"
onClick={openReply}
>
<Icon name="reply" />
</Button>
);
return (
<div
<ConversationRow
key={message.id}
id={message.id}
data-message-id={message.id}
agent={agent}
message={message}
previous={parent ? messages[index - 1] : undefined}
inThread={!!parent}
entering={entering.has(message.id)}
conversationId={conversationId}
canReply={!!onOpenThread}
replyLabel={thread ? replyLabel(message.id) : undefined}
onReact={reactToMessage}
onOpenReply={openReplyToMessage}
>
{parent &&
(message.role === "user" ||
message.role === "assistant") ? (
<ThreadMessage
agent={agent}
message={message}
previous={messages[index - 1]}
onReact={(emoji, active) =>
react(message.id, emoji, active)
}
entering={entering.has(message.id)}
/>
) : message.role === "user" ? (
<UserMessage
reactions={
<MessageReactions
message={message}
agentName={agent.name}
/>
}
files={message.files}
entering={entering.has(message.id)}
>
{message.text}
</UserMessage>
) : message.role === "notice" ? (
<ConversationNotice
agentId={agent.id}
message={message}
/>
) : message.role === "activity" ? (
<ToolActivity
conversationId={conversationId}
agentId={agent.id}
message={message}
entering={entering.has(message.id)}
/>
) : (
<AgentMessage
reactions={
<MessageReactions
message={message}
agentName={agent.name}
onReact={(emoji, active) =>
react(message.id, emoji, active)
}
/>
}
action={replyAction}
name={agent.name}
title={message.title}
files={message.files}
ui={message.ui}
entering={entering.has(message.id)}
>
{message.text}
</AgentMessage>
)}
{onOpenThread && existingThread && (
<Button
title="Reply in thread"
aria-label={`Reply in thread: ${message.text.slice(0, 60)}. ${replyLabel(message.id)}`}
onClick={openReply}
>
{replyLabel(message.id)}
</Button>
)}
{computerEnabled &&
computerOpen &&
message.id === computerAnchor && (
Expand All @@ -622,7 +569,7 @@ export function Conversation({
/>
</Suspense>
)}
</div>
</ConversationRow>
);
})}
{computerEnabled &&
Expand Down Expand Up @@ -736,6 +683,105 @@ const fadeIn = stylex.keyframes({
to: { opacity: 1 },
});

// Polls and scroll bookkeeping re-render the conversation every second, so
// unchanged messages must not re-render with it.
const ConversationRow = memo(function ConversationRow({
agent,
message,
previous,
inThread,
entering,
conversationId,
canReply,
replyLabel,
onReact,
onOpenReply,
children,
}: {
agent: Agent;
message: Message;
previous?: Message;
inThread: boolean;
entering: boolean;
conversationId: string;
canReply: boolean;
replyLabel?: string;
onReact: (messageId: string, emoji: string, active: boolean) => Promise<void>;
onOpenReply: (messageId: string) => Promise<void>;
children?: ReactNode;
}) {
const replyAction = canReply && message.role === "assistant" && (
<Button
xstyle={styles.replyAction}
title="Reply in thread"
aria-label="Reply in thread"
onClick={() => onOpenReply(message.id)}
>
<Icon name="reply" />
</Button>
);
return (
<div id={message.id} data-message-id={message.id}>
{inThread && (message.role === "user" || message.role === "assistant") ? (
<ThreadMessage
agent={agent}
message={message}
previous={previous}
onReact={(emoji, active) => onReact(message.id, emoji, active)}
entering={entering}
/>
) : message.role === "user" ? (
<UserMessage
reactions={
<MessageReactions message={message} agentName={agent.name} />
}
files={message.files}
entering={entering}
>
{message.text}
</UserMessage>
) : message.role === "notice" ? (
<ConversationNotice agentId={agent.id} message={message} />
) : message.role === "activity" ? (
<ToolActivity
conversationId={conversationId}
agentId={agent.id}
message={message}
entering={entering}
/>
) : (
<AgentMessage
reactions={
<MessageReactions
message={message}
agentName={agent.name}
onReact={(emoji, active) => onReact(message.id, emoji, active)}
/>
}
action={replyAction}
name={agent.name}
title={message.title}
files={message.files}
ui={message.ui}
entering={entering}
>
{message.text}
</AgentMessage>
)}
{canReply && replyLabel && (
<Button
title="Reply in thread"
aria-label={`Reply in thread: ${message.text.slice(0, 60)}. ${replyLabel}`}
onClick={() => onOpenReply(message.id)}
>
{replyLabel}
</Button>
)}
{children}
</div>
);
});

const styles = stylex.create({
replyAction: {
display: "flex",
Expand Down
7 changes: 6 additions & 1 deletion apps/web/src/components/note-workspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,10 @@ type Pending =
};
};

export function NoteWorkspace({ initial }: { initial: NoteSnapshot }) {
export function NoteWorkspace({ initial: loaded }: { initial: NoteSnapshot }) {
// A tab switch can render from cached loader data; the poll below catches up
// and a later background reload must not re-run draft recovery.
const [initial] = useState(loaded);
const scrollRef = useRef<HTMLDivElement>(null);
const contentRef = useRef<HTMLDivElement>(null);
const [base, setBase] = useState(initial);
Expand Down Expand Up @@ -160,6 +163,8 @@ export function NoteWorkspace({ initial }: { initial: NoteSnapshot }) {
setError("");
void refresh();
};
// The opening snapshot may come from the router cache.
if (navigator.onLine) void refresh();
const timer = window.setInterval(() => {
if (navigator.onLine) void refresh();
}, 5000);
Expand Down
4 changes: 4 additions & 0 deletions apps/web/src/router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { routeTree } from "./routeTree.gen";
export function getRouter() {
return createRouter({
routeTree,
// Agent tabs preload each other, so keep visited and preloaded loader data
// long enough that switching tabs renders from cache and revalidates.
defaultGcTime: 30 * 60_000,
defaultPreloadGcTime: 30 * 60_000,
// Conversations follow their latest message and manage older-history scroll.
scrollRestoration: ({ location }) =>
!/^\/agents\/[0-9a-f-]{36}(?:\/dashboard)?$/i.test(location.pathname),
Expand Down
Loading