Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(chat): TipTap composer migration + instant cache-first render
Gus07aefe377e79
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 75e627099..1bab45168 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -1182,6 +1182,32 @@.tiptap u { text-decoration: underline; }.tiptap s { text-decoration: line-through; }+/* ── Chat composer (TipTap input) — uniform font, scoped overrides ──+ The shared .tiptap rules above (line-height 1.6, p margins) would bleed into+ the chat input. Scope here to keep every line one size/weight and let the+ px-13 py-3 wrapper own padding. Higher specificity (two classes) beats the+ single-class base rules. Do NOT touch the shared .tiptap rules — the+ comment/email editors depend on them. */+.chat-composer .tiptap {+ line-height: 24px; /* matches .chat-input-line-height */+ outline: none;+}+.chat-composer .tiptap p,+.chat-composer .tiptap li {+ font-size: 1rem;+ font-weight: 400;+ margin: 0;+ line-height: 24px;+}+.chat-composer .tiptap > p:first-child { margin-top: 0; }+.chat-composer .tiptap > p:last-child { margin-bottom: 0; }+.chat-composer .tiptap ul,+.chat-composer .tiptap ol {+ margin: 0;+ padding-left: 1.5em;+}+.chat-composer .tiptap li { margin: 0; }+/* ── Thin scrollbar (code blocks, tool panels, chat scroll) ── */.markdown pre,[data-streamdown] pre,diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex f9a67f339..0245b328b 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -1,6 +1,12 @@"use client";-import React, { useEffect, useState, useRef, useCallback, useMemo } from "react";+import React, {+ useEffect,+ useState,+ useRef,+ useCallback,+ useMemo,+} from "react";import { flushSync } from "react-dom";import { useParams, useSearchParams } from "next/navigation";import { useWorkspace } from "@/contexts/workspace-context";@@ -33,9 +39,33 @@ import {unflagMessage as apiUnflagMessage,getAgentSkills,} from "@/lib/api";-import { appendCachedMessage, getCachedMessages, getCachedMessagesBefore, getCacheMeta, mergeCachedMessages } from "@/lib/chat-cache";+import {+ appendCachedMessage,+ getCachedMessages,+ getCachedMessagesBefore,+ getCacheMeta,+ mergeCachedMessages,+ getLastOpenConversation,+ setLastOpenConversation,+} from "@/lib/chat-cache";+import {+ createFastLoadGateState,+ fastLoadKey,+ shouldSkipFastLoad,+ markFastLoadCompleted,+} from "@/components/agent-chat/fast-load-gate";import type { PreviousConversation, TraceTask } from "@/lib/api";-import type { Artifact, Conversation, Issue, IssueComment, Message, SkillEntry, TaskApi as Task, TaskMessageResponse, WsMessage } from "@alook/shared";+import type {+ Artifact,+ Conversation,+ Issue,+ IssueComment,+ Message,+ SkillEntry,+ TaskApi as Task,+ TaskMessageResponse,+ WsMessage,+} from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";import { useInboxCount } from "@/contexts/inbox-count-context";import { useFlagCount } from "@/contexts/flag-count-context";@@ -43,42 +73,81 @@ import { useChannel } from "@/contexts/channel-context";import { toast } from "sonner";import { cn } from "@/lib/utils";import { Skeleton } from "@/components/ui/skeleton";-import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";-import { ArrowUp, BedDouble, Box, FileText, Loader2, Mail, MessageSquareQuote, Paperclip, Square, X } from "lucide-react";+import {+ Tooltip,+ TooltipTrigger,+ TooltipContent,+} from "@/components/ui/tooltip";+import {+ ArrowUp,+ BedDouble,+ Box,+ FileText,+ Loader2,+ Mail,+ MessageSquareQuote,+ Paperclip,+ Plus,+ Square,+ X,+} from "lucide-react";import { useCachedMessages } from "@/hooks/use-cached-messages";-import { useMentionPopup } from "@/hooks/use-mention-popup";-import { MentionPopup } from "@/components/agent-chat/mention-popup";import { useSlashCommand } from "@/hooks/use-slash-command";import { SlashCommandPopup } from "@/components/agent-chat/slash-command-popup";-import { highlightMentions } from "@/lib/highlight-mentions";-import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";+import {+ ChatComposer,+ type ChatComposerHandle,+} from "@/components/agent-chat/chat-composer";+import {+ ArtifactSheet,+ formatSize,+} from "@/components/agent-chat/artifact-sheet";import { EmailEventSheet } from "@/components/agent-chat/email-event-sheet";import { CalendarEventSheet } from "@/components/calendar/calendar-event-sheet";import { IssueSheet } from "@/components/issues/issue-sheet";-import { isPreviewable, getArtifactUrl, computeArtifactVersions } from "@/components/artifact-content-renderer";+import {+ isPreviewable,+ getArtifactUrl,+ computeArtifactVersions,+} from "@/components/artifact-content-renderer";import { FollowUpBuffer } from "@/components/agent-chat/follow-up-buffer";import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";import { MessageItem } from "@/components/agent-chat/message-list";import { AgentPreviewCard } from "@/components/agent-preview-card";-import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from "@/components/ui/popover";const MESSAGE_LIMIT = 20;const MAX_CONV_FETCHES_PER_CLICK = 5;const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB-function MentionHighlight(props: Record<string, unknown> & { children?: React.ReactNode }) {+function MentionHighlight(+ props: Record<string, unknown> & { children?: React.ReactNode },+) {const { children, ...rest } = props;const { agents } = useAgentContext();- const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as string | undefined;+ const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as+ | string+ | undefined;let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;if (!agent && typeof children === "string") {const nameToMatch = children.startsWith("@") ? children.slice(1) : children;- agent = agents.find((a) => a.name.toLowerCase() === nameToMatch.toLowerCase());+ agent = agents.find(+ (a) => a.name.toLowerCase() === nameToMatch.toLowerCase(),+ );}if (agent) {return (<Popover>- <PopoverTrigger openOnHover delay={300} nativeButton={false} render={<span className="mention-highlight cursor-pointer" />}>+ <PopoverTrigger+ openOnHover+ delay={300}+ nativeButton={false}+ render={<span className="mention-highlight cursor-pointer" />}+ >{children}</PopoverTrigger><PopoverContent side="top" className="w-fit max-w-80">@@ -89,17 +158,31 @@ function MentionHighlight(props: Record<string, unknown> & { children?: React.Re}return <span className="mention-highlight">{children}</span>;}-const MENTION_COMPONENTS: Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>> = {+const MENTION_COMPONENTS: Record<+ string,+ React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>+> = {mention: MentionHighlight,- p: ({ children, node, ...rest }: Record<string, unknown> & { children?: React.ReactNode }) => {+ p: ({+ children,+ node,+ ...rest+ }: Record<string, unknown> & { children?: React.ReactNode }) => {void node;- return <div data-md-p="" {...rest}>{children}</div>;+ return (+ <div data-md-p="" {...rest}>+ {children}+ </div>+ );},};type EventIconType = "issue" | "email" | "calendar";-export function getEventIconType(content: string, conversationType?: string | null): EventIconType {+export function getEventIconType(+ content: string,+ conversationType?: string | null,+): EventIconType {if (conversationType === "issue_event") return "issue";if (conversationType === "email_notification") return "email";if (conversationType === "calendar_event") return "calendar";@@ -110,7 +193,6 @@ export function getEventIconType(content: string, conversationType?: string | nureturn "calendar";}-/** Sort messages by (created_at, id) ascending — guarantees chronological order. */export function sortMessages(msgs: Message[]): Message[] {return msgs.slice().sort((a, b) => {@@ -121,25 +203,41 @@ export function sortMessages(msgs: Message[]): Message[] {}/** Merge two message arrays by ID (latest wins), then sort chronologically. */-export function mergeMessages(existing: Message[], incoming: Message[]): Message[] {+export function mergeMessages(+ existing: Message[],+ incoming: Message[],+): Message[] {const merged = new Map<string, Message>();for (const m of existing) merged.set(m.id, m);for (const m of incoming) merged.set(m.id, m);return sortMessages([...merged.values()]);}-export function addBufferedIfNew(prev: Message[], incoming: Message): Message[] {+export function addBufferedIfNew(+ prev: Message[],+ incoming: Message,+): Message[] {if (prev.some((m) => m.id === incoming.id)) return prev;// Skip if there's a recent optimistic entry — avoids brief duplicate flash// when WS followup.created arrives before createBufferedMessage HTTP response.const t = new Date(incoming.created_at).getTime();- if (prev.some((m) => m.id.startsWith("temp-") && Math.abs(new Date(m.created_at).getTime() - t) < 2000)) {+ if (+ prev.some(+ (m) =>+ m.id.startsWith("temp-") &&+ Math.abs(new Date(m.created_at).getTime() - t) < 2000,+ )+ ) {return prev;}return [...prev, incoming];}-export function replaceOptimisticBuffered(prev: Message[], optimisticId: string, real: Message): Message[] {+export function replaceOptimisticBuffered(+ prev: Message[],+ optimisticId: string,+ real: Message,+): Message[] {if (prev.some((m) => m.id === real.id)) {return prev.filter((m) => m.id !== optimisticId);}@@ -153,7 +251,65 @@ type TimelineItem =| { kind: "artifact"; data: Artifact }| { kind: "nap"; data: NapMarker };-export function reorderArtifactsAfterAssistant(items: TimelineItem[]): TimelineItem[] {+export type GroupPosition = "first" | "middle" | "last" | "solo";++function computeGroupPositions(+ timeline: TimelineItem[],+): (GroupPosition | null)[] {+ const positions: (GroupPosition | null)[] = new Array(timeline.length).fill(+ null,+ );+ const GROUP_THRESHOLD_MS = 60_000;++ // Only user/assistant messages group into tight iMessage-style stacks.+ // Event messages (email/issue/calendar notifications) must keep normal spacing.+ const isGroupable = (m: Message) =>+ m.role === "user" || m.role === "assistant";++ for (let i = 0; i < timeline.length; i++) {+ const item = timeline[i];+ if (item.kind !== "message") continue;++ const msg = item.data as Message;+ if (!isGroupable(msg)) continue; // leave as null → normal mt-4 spacing, full rounding++ const prev = i > 0 ? timeline[i - 1] : null;+ const next = i < timeline.length - 1 ? timeline[i + 1] : null;++ const sameAsPrev =+ prev?.kind === "message" &&+ isGroupable(prev.data as Message) &&+ (prev.data as Message).role === msg.role &&+ (!msg.created_at ||+ !(prev.data as Message).created_at ||+ Math.abs(+ new Date(msg.created_at).getTime() -+ new Date((prev.data as Message).created_at).getTime(),+ ) < GROUP_THRESHOLD_MS);++ const sameAsNext =+ next?.kind === "message" &&+ isGroupable(next.data as Message) &&+ (next.data as Message).role === msg.role &&+ (!msg.created_at ||+ !(next.data as Message).created_at ||+ Math.abs(+ new Date((next.data as Message).created_at).getTime() -+ new Date(msg.created_at).getTime(),+ ) < GROUP_THRESHOLD_MS);++ if (sameAsPrev && sameAsNext) positions[i] = "middle";+ else if (sameAsPrev && !sameAsNext) positions[i] = "last";+ else if (!sameAsPrev && sameAsNext) positions[i] = "first";+ else positions[i] = "solo";+ }++ return positions;+}++export function reorderArtifactsAfterAssistant(+ items: TimelineItem[],+): TimelineItem[] {const result: TimelineItem[] = [];let pending: TimelineItem[] = [];let collecting = false;@@ -204,7 +360,9 @@ export function buildTimeline(}const napConvIds = new Set(napMarkers.map((n) => n.id.replace(/^nap-/, "")));- const sortedNaps = [...napMarkers].sort((a, b) => a.created_at.localeCompare(b.created_at));+ const sortedNaps = [...napMarkers].sort((a, b) =>+ a.created_at.localeCompare(b.created_at),+ );const groupItems = (convId: string): TimelineItem[] => {const msgs: TimelineItem[] = messages@@ -233,8 +391,12 @@ export function buildTimeline(result.push(...groupItems(currentConversationId));const knownConvIds = new Set([...napConvIds, currentConversationId]);- const orphanMsgs = messages.filter((m) => !knownConvIds.has(m.conversation_id));- const orphanArts = artifacts.filter((a) => !knownConvIds.has(a.conversation_id));+ const orphanMsgs = messages.filter(+ (m) => !knownConvIds.has(m.conversation_id),+ );+ const orphanArts = artifacts.filter(+ (a) => !knownConvIds.has(a.conversation_id),+ );if (orphanMsgs.length > 0 || orphanArts.length > 0) {const orphanItems: TimelineItem[] = [...orphanMsgs.map((m): TimelineItem => ({ kind: "message", data: m })),@@ -278,14 +440,24 @@ function NapSeparator({ agentName }: { agentName: string }) {);}-function ArtifactCard({ artifact, version, hasDuplicates, onClick }: { artifact: Artifact; version: number; hasDuplicates: boolean; onClick: (a: Artifact) => void }) {+function ArtifactCard({+ artifact,+ version,+ hasDuplicates,+ onClick,+}: {+ artifact: Artifact;+ version: number;+ hasDuplicates: boolean;+ onClick: (a: Artifact) => void;+}) {return (<buttononClick={() => onClick(artifact)}className={cn("flex items-center gap-3 w-full max-w-sm rounded-lg border border-border/60 bg-muted/30","px-3.5 py-2.5 text-left transition-colors duration-150",- "hover:bg-muted/60 hover:border-border"+ "hover:bg-muted/60 hover:border-border",)}><FileText className="size-4 shrink-0 text-muted-foreground" />@@ -298,7 +470,9 @@ function ArtifactCard({ artifact, version, hasDuplicates, onClick }: { artifact:</span>)}</p>- <p className="text-xs text-muted-foreground">{formatSize(artifact.size)}</p>+ <p className="text-xs text-muted-foreground">+ {formatSize(artifact.size)}+ </p></div></button>);@@ -318,19 +492,42 @@ export function AgentChatView({const params = useParams();const searchParams = useSearchParams();const { workspaceId, slug } = useWorkspace();- const { agents, agentLinks, activeTaskCounts, subscribeWs, subscribeReconnect } = useAgentContext();+ const {+ agents,+ agentLinks,+ activeTaskCounts,+ subscribeWs,+ subscribeReconnect,+ } = useAgentContext();const { refresh: refreshInboxCount } = useInboxCount();- const { activeChannel, loading: channelLoading, setAgentId: setChannelAgentId } = useChannel();+ const {+ activeChannel,+ loading: channelLoading,+ setAgentId: setChannelAgentId,+ } = useChannel();const agentId = propAgentId ?? (params.id as string);- const scrollToTaskId = propScrollToTaskId !== undefined ? propScrollToTaskId : searchParams.get("task");- const scrollToMessageId = propScrollToMessageId !== undefined ? propScrollToMessageId : searchParams.get("msg");- const targetConvId = propTargetConvId !== undefined ? propTargetConvId : searchParams.get("conv");+ const scrollToTaskId =+ propScrollToTaskId !== undefined+ ? propScrollToTaskId+ : searchParams.get("task");+ const scrollToMessageId =+ propScrollToMessageId !== undefined+ ? propScrollToMessageId+ : searchParams.get("msg");+ const targetConvId =+ propTargetConvId !== undefined+ ? propTargetConvId+ : searchParams.get("conv");const [conversation, setConversation] = useState<Conversation | null>(null);const [messages, setMessages] = useState<Message[]>([]);const [input, setInput] = useState(() => {if (typeof window === "undefined") return "";- return localStorage.getItem(`chat-draft:${agentId}:${targetConvId ?? 'default'}`) ?? "";+ return (+ localStorage.getItem(+ `chat-draft:${agentId}:${targetConvId ?? "default"}`,+ ) ?? ""+ );});const [sending, setSending] = useState(false);const [cancelling, setCancelling] = useState(false);@@ -342,12 +539,18 @@ export function AgentChatView({const [loadingMore, setLoadingMore] = useState(false);const [artifacts, setArtifacts] = useState<Artifact[]>([]);const [artifactSheetOpen, setArtifactSheetOpen] = useState(false);- const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(null);- const [artifactSheetSource, setArtifactSheetSource] = useState<"agent" | "issue" | null>(null);+ const [selectedArtifact, setSelectedArtifact] = useState<Artifact | null>(+ null,+ );+ const [artifactSheetSource, setArtifactSheetSource] = useState<+ "agent" | "issue" | null+ >(null);const [emailSheetOpen, setEmailSheetOpen] = useState(false);const [selectedEmailId, setSelectedEmailId] = useState<string | null>(null);const [calendarEventSheetOpen, setCalendarEventSheetOpen] = useState(false);- const [selectedCalendarEventId, setSelectedCalendarEventId] = useState<string | null>(null);+ const [selectedCalendarEventId, setSelectedCalendarEventId] = useState<+ string | null+ >(null);const [issueSheetOpen, setIssueSheetOpen] = useState(false);const [selectedIssueId, setSelectedIssueId] = useState<string | null>(null);const [issueDetail, setIssueDetail] = useState<{@@ -357,75 +560,128 @@ export function AgentChatView({artifacts: Artifact[];} | null>(null);const [issueDetailLoading, setIssueDetailLoading] = useState(false);- const [issueTraceTasks, setIssueTraceTasks] = useState<TraceTask[] | null>(null);+ const [issueTraceTasks, setIssueTraceTasks] = useState<TraceTask[] | null>(+ null,+ );const [issueActiveTask, setIssueActiveTask] = useState<Task | null>(null);const [pendingFiles, setPendingFiles] = useState<File[]>([]);const [bufferedMessages, setBufferedMessages] = useState<Message[]>([]);const [caretIndex, setCaretIndex] = useState<number | null>(null);- const [previousConversations, setPreviousConversations] = useState<PreviousConversation[]>([]);+ const [previousConversations, setPreviousConversations] = useState<+ PreviousConversation[]+ >([]);const [hasMoreConversations, setHasMoreConversations] = useState(false);const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);- const [thinkingCounts, setThinkingCounts] = useState<Record<string, number>>({});+ const [thinkingCounts, setThinkingCounts] = useState<Record<string, number>>(+ {},+ );const [renderNow] = useState(() => Date.now());- const [pendingFilesByMessage, setPendingFilesByMessage] = useState<Map<string, File[]>>(() => new Map());+ const [pendingFilesByMessage, setPendingFilesByMessage] = useState<+ Map<string, File[]>+ >(() => new Map());const [quotedText, setQuotedText] = useState<string | null>(() => {if (typeof window === "undefined") return null;try {- const meta = JSON.parse(localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`) ?? "null");+ const meta = JSON.parse(+ localStorage.getItem(+ `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`,+ ) ?? "null",+ );return meta?.quote ?? null;- } catch { return null; }+ } catch {+ return null;+ }});- const [selectionPopup, setSelectionPopup] = useState<{ text: string; x: number; y: number } | null>(null);+ const [isMultiLine, setIsMultiLine] = useState(false);+ const [selectionPopup, setSelectionPopup] = useState<{+ text: string;+ x: number;+ y: number;+ } | null>(null);const [flaggedIds, setFlaggedIds] = useState<Set<string>>(new Set());const flaggedIdsRef = useRef(flaggedIds);- useEffect(() => { flaggedIdsRef.current = flaggedIds; });+ useEffect(() => {+ flaggedIdsRef.current = flaggedIds;+ });- const { increment: flagIncrement, decrement: flagDecrement, refresh: flagRefresh } = useFlagCount();+ const {+ increment: flagIncrement,+ decrement: flagDecrement,+ refresh: flagRefresh,+ } = useFlagCount();const { writeToCache } = useCachedMessages(targetConvId ?? null, workspaceId);const writeToCacheRef = useRef(writeToCache);- useEffect(() => { writeToCacheRef.current = writeToCache; }, [writeToCache]);+ useEffect(() => {+ writeToCacheRef.current = writeToCache;+ }, [writeToCache]);useEffect(() => {setChannelAgentId(agentId);}, [agentId, setChannelAgentId]);+ const agentArtifacts = useMemo(+ () => artifacts.filter((a) => a.source === "agent"),+ [artifacts],+ );- const agentArtifacts = useMemo(() => artifacts.filter((a) => a.source === "agent"), [artifacts]);-- const { versionMap, duplicateFilenames } = useMemo(() => computeArtifactVersions(agentArtifacts), [agentArtifacts]);+ const { versionMap, duplicateFilenames } = useMemo(+ () => computeArtifactVersions(agentArtifacts),+ [agentArtifacts],+ );const artifactSheetArtifacts = useMemo(- () => artifactSheetSource === "agent" ? agentArtifacts : artifactSheetSource === "issue" ? (issueDetail?.artifacts ?? []) : [],+ () =>+ artifactSheetSource === "agent"+ ? agentArtifacts+ : artifactSheetSource === "issue"+ ? (issueDetail?.artifacts ?? [])+ : [],[artifactSheetSource, agentArtifacts, issueDetail?.artifacts],);- const { versionMap: artifactSheetVersionMap, duplicateFilenames: artifactSheetDuplicateFilenames } = useMemo(+ const {+ versionMap: artifactSheetVersionMap,+ duplicateFilenames: artifactSheetDuplicateFilenames,+ } = useMemo(() => computeArtifactVersions(artifactSheetArtifacts),[artifactSheetArtifacts],);- const timeline = useMemo(() => buildTimeline(messages, agentArtifacts, napMarkers, conversation?.id), [messages, agentArtifacts, napMarkers, conversation?.id]);+ const timeline = useMemo(+ () => buildTimeline(messages, agentArtifacts, napMarkers, conversation?.id),+ [messages, agentArtifacts, napMarkers, conversation?.id],+ );+ const groupPositions = useMemo(+ () => computeGroupPositions(timeline),+ [timeline],+ );- const handleArtifactClick = useCallback((artifact: Artifact) => {- if (isPreviewable(artifact)) {- setSelectedArtifact(artifact);- setArtifactSheetSource("agent");- setArtifactSheetOpen(true);- } else {- window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");- }- }, [workspaceId]);+ const handleArtifactClick = useCallback(+ (artifact: Artifact) => {+ if (isPreviewable(artifact)) {+ setSelectedArtifact(artifact);+ setArtifactSheetSource("agent");+ setArtifactSheetOpen(true);+ } else {+ window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");+ }+ },+ [workspaceId],+ );- const handleIssueArtifactClick = useCallback((artifact: Artifact) => {- if (isPreviewable(artifact)) {- setSelectedArtifact(artifact);- setArtifactSheetSource("issue");- setArtifactSheetOpen(true);- } else {- window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");- }- }, [workspaceId]);+ const handleIssueArtifactClick = useCallback(+ (artifact: Artifact) => {+ if (isPreviewable(artifact)) {+ setSelectedArtifact(artifact);+ setArtifactSheetSource("issue");+ setArtifactSheetOpen(true);+ } else {+ window.open(getArtifactUrl(artifact.id, workspaceId, true), "_blank");+ }+ },+ [workspaceId],+ );const scrollRef = useRef<HTMLDivElement>(null);const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);@@ -437,24 +693,35 @@ export function AgentChatView({const loadingMoreRef = useRef(false);const isNearBottom = useRef(true);const scrollTargetActiveRef = useRef(false);- const startPollingRef = useRef<((taskId: string, conversationId: string, initialSeq?: number) => void) | null>(null);+ const startPollingRef = useRef<+ | ((taskId: string, conversationId: string, initialSeq?: number) => void)+ | null+ >(null);const oldestConversationCursorRef = useRef<PreviousConversation | null>(null);const backfillAttemptsRef = useRef(0);const prevConversationIdRef = useRef<string | undefined>(undefined);+ // The server-confirmed conversation id for the current load. Cache writes+ // (mergeCachedMessages / appendCachedMessage / setLastOpenConversation) must+ // guard on this so a write never lands on an optimistically-rendered (not yet+ // confirmed) conversation during the cache-first window. Stays null until+ // checkFreshness / chatInit / conversationInit confirms an id.+ const loadConvIdRef = useRef<string | null>(null);+ // Dedup gate for the fast-path load: skips a redundant re-run when only+ // channel deps (activeChannel / channelLoading) change, WITHOUT stranding the+ // skeleton if a run is cancelled mid-flight. See fast-load-gate.ts (Part 2-a /+ // TODO 6 + stuck-skeleton fix).+ const fastLoadGateRef = useRef(createFastLoadGateState());const fileInputRef = useRef<HTMLInputElement>(null);- const textareaRef = useRef<HTMLTextAreaElement>(null);-- const otherAgents = useMemo(() => agents.filter(a => a.id !== agentId), [agents, agentId]);-- const mentionPopup = useMentionPopup({- input,- caretIndex,- textareaRef,- agents: otherAgents,- agentLinks,- currentAgentId: agentId,- onInputChange: setInput,- });+ // TipTap composer imperative handle (focus / clear / isEmpty / anchor coords).+ const composerRef = useRef<ChatComposerHandle>(null);+ // Editor plain text + caret, reported up from the composer, drive the+ // slash-command popup (mentions are handled natively inside the composer).+ const [editorText, setEditorText] = useState("");++ const otherAgents = useMemo(+ () => agents.filter((a) => a.id !== agentId),+ [agents, agentId],+ );// Slash command skills — fetch from D1 on mountconst [agentSkills, setAgentSkills] = useState<SkillEntry[]>([]);@@ -472,29 +739,44 @@ export function AgentChatView({const [initialActiveSkill] = useState<SkillEntry | null>(() => {if (typeof window === "undefined") return null;try {- const meta = JSON.parse(localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`) ?? "null");+ const meta = JSON.parse(+ localStorage.getItem(+ `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`,+ ) ?? "null",+ );return meta?.skill ?? null;- } catch { return null; }+ } catch {+ return null;+ }});const slashCommand = useSlashCommand({- input,+ input: editorText,caretIndex,- textareaRef,skills: agentSkills,- onInputChange: setInput,+ onInputChange: () => composerRef.current?.clear(),initialActiveSkill,+ getAnchorPos: useCallback(+ (triggerStart: number) =>+ composerRef.current?.coordsAtTextIndex(triggerStart) ?? null,+ [],+ ),+ onAfterSelect: useCallback(() => {+ requestAnimationFrame(() => composerRef.current?.focus());+ }, []),});useEffect(() => {if (agentSkills.length === 0 || !slashCommand.activeSkill) return;- const exists = agentSkills.some(s => s.name === slashCommand.activeSkill!.name);+ const exists = agentSkills.some(+ (s) => s.name === slashCommand.activeSkill!.name,+ );if (!exists) slashCommand.setActiveSkill(null);// eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally omits slashCommand; only re-validate when the skills list itself changes}, [agentSkills]);useEffect(() => {- const key = `chat-draft:${agentId}:${targetConvId ?? 'default'}`;+ const key = `chat-draft:${agentId}:${targetConvId ?? "default"}`;if (input) {localStorage.setItem(key, input);} else {@@ -504,10 +786,16 @@ export function AgentChatView({useEffect(() => {if (!draftMetaRestoredRef.current) return;- const key = `chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`;- const meta: { skill?: { name: string; description: string } | null; quote?: string | null } = {};+ const key = `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`;+ const meta: {+ skill?: { name: string; description: string } | null;+ quote?: string | null;+ } = {};if (slashCommand.activeSkill) {- meta.skill = { name: slashCommand.activeSkill.name, description: slashCommand.activeSkill.description };+ meta.skill = {+ name: slashCommand.activeSkill.name,+ description: slashCommand.activeSkill.description,+ };}if (quotedText) {meta.quote = quotedText;@@ -521,7 +809,7 @@ export function AgentChatView({useEffect(() => {if (!sending) {- textareaRef.current?.focus();+ composerRef.current?.focus();}}, [sending]);@@ -536,11 +824,31 @@ export function AgentChatView({}, []);useEffect(() => {- if (channelLoading) return;+ // The slow path (no targetConvId) resolves the conversation id via the+ // server using activeChannel, so it must wait for the channel list. The+ // fast path (known targetConvId) and the cache-first optimistic paint need+ // neither activeChannel nor a loaded channel list, so they must NOT be+ // gated by channelLoading (Part 2-a). channelLoading stays in the dep array+ // so the slow path retries once channels load.+ if (!targetConvId && channelLoading) return;++ // Fast path: ignore channel-only dep changes (TODO 6). shouldSkipFastLoad+ // returns true only when a load for this identity has already COMPLETED, and+ // otherwise clears the completed marker so a run cancelled mid-flight leaves+ // no "done" marker — the recovery run then proceeds and clears the skeleton+ // instead of getting stuck forever. See fast-load-gate.ts.+ const fastKey = fastLoadKey({+ workspaceId,+ agentId,+ targetConvId,+ scrollToTaskId,+ });+ if (shouldSkipFastLoad(fastKey, fastLoadGateRef.current)) return;if (pollRef.current) clearInterval(pollRef.current);pollRef.current = null;pollTaskIdRef.current = null;+ loadConvIdRef.current = null;let ignore = false;setMessagesLoading(true);initialScrollDone.current = false;@@ -553,13 +861,21 @@ export function AgentChatView({setPreviousConversations([]);setHasMoreConversations(false);oldestConversationCursorRef.current = null;- setInput(localStorage.getItem(`chat-draft:${agentId}:${targetConvId ?? 'default'}`) ?? "");- const metaRaw = localStorage.getItem(`chat-draft-meta:${agentId}:${targetConvId ?? 'default'}`);+ setInput(+ localStorage.getItem(+ `chat-draft:${agentId}:${targetConvId ?? "default"}`,+ ) ?? "",+ );+ const metaRaw = localStorage.getItem(+ `chat-draft-meta:${agentId}:${targetConvId ?? "default"}`,+ );if (metaRaw) {try {const meta = JSON.parse(metaRaw);setQuotedText(meta.quote ?? null);- slashCommand.setActiveSkill(meta.skill ? (meta.skill as SkillEntry) : null);+ slashCommand.setActiveSkill(+ meta.skill ? (meta.skill as SkillEntry) : null,+ );} catch {setQuotedText(null);slashCommand.setActiveSkill(null);@@ -570,46 +886,107 @@ export function AgentChatView({}draftMetaRestoredRef.current = true;setMessages([]);++ // Paint cached messages for a known conversation id without any network.+ // Returns true if it painted, so the caller can suppress the loading+ // skeleton until the background reconcile runs.+ async function paintFromCache(convId: string): Promise<{+ painted: boolean;+ cacheMeta: Awaited<ReturnType<typeof getCacheMeta>>;+ }> {+ const cacheMeta = await getCacheMeta(convId, workspaceId);+ if (cacheMeta?.newestMessageId) {+ const cached = await getCachedMessages(convId, workspaceId);+ if (ignore) return { painted: false, cacheMeta };+ if (cached && cached.length > 0) {+ setMessages(cached);+ setHasMore(cacheMeta.hasMore);+ setMessagesLoading(false);+ return { painted: true, cacheMeta };+ }+ }+ return { painted: false, cacheMeta };+ }+async function load() {let hasCachedMessages = false;try {let convId: string | null = null;let cacheMeta: Awaited<ReturnType<typeof getCacheMeta>> = null;+ // The id we optimistically painted in the slow path; reconciled against+ // the server-confirmed id once checkFreshness returns.+ let optimisticConvId: string | null = null;if (targetConvId) {// Fast path: we already know the conv ID — render from cache immediately, no network neededconvId = targetConvId;- cacheMeta = await getCacheMeta(convId, workspaceId);- if (cacheMeta?.newestMessageId) {- const cached = await getCachedMessages(convId, workspaceId);+ const res = await paintFromCache(convId);+ if (ignore) return;+ cacheMeta = res.cacheMeta;+ hasCachedMessages = res.painted;+ } else {+ // Slow path: resolve the conversation id locally first (last-open+ // pointer) and paint its cache immediately, then verify in the+ // background. Only paint optimistically when the pointer is plausibly+ // fresh (serverMessageCount > 0 and a non-empty cache), so a stale or+ // empty pointer falls back to the skeleton (review #4).+ const lastOpen = await getLastOpenConversation(+ agentId,+ activeChannel,+ workspaceId,+ );+ if (ignore) return;+ if (lastOpen?.conversation_id && lastOpen.serverMessageCount > 0) {+ const res = await paintFromCache(lastOpen.conversation_id);if (ignore) return;- if (cached && cached.length > 0) {+ if (res.painted) {hasCachedMessages = true;- setMessages(cached);- setHasMore(cacheMeta.hasMore);- setMessagesLoading(false);+ optimisticConvId = lastOpen.conversation_id;+ cacheMeta = res.cacheMeta;}}- } else {- // Slow path: need server to resolve conv ID first++ // Background freshness check — does NOT gate the paint above.try {- const fresh = await checkFreshness({ agentId, channel: activeChannel }, workspaceId);+ const fresh = await checkFreshness(+ { agentId, channel: activeChannel },+ workspaceId,+ );if (ignore) return;convId = fresh.conversation_id;- cacheMeta = await getCacheMeta(convId, workspaceId);- const idMatches = !!(cacheMeta?.newestMessageId && cacheMeta.newestMessageId === fresh.newest_message_id);- const countMatches = cacheMeta?.serverMessageCount ? cacheMeta.serverMessageCount === fresh.message_count : true;- const cacheValid = idMatches && countMatches;- if (cacheValid) {- const cached = await getCachedMessages(convId, workspaceId);++ if (optimisticConvId && convId !== optimisticConvId) {+ // We painted the wrong/stale conversation. Swap to the correct+ // one and reset scroll intent so the initial-scroll effect+ // re-fires for the new message set (review #2).+ initialScrollDone.current = false;+ isNearBottom.current = true;+ const res = await paintFromCache(convId);if (ignore) return;- if (cached && cached.length > 0) {- hasCachedMessages = true;- setMessages(cached);- setHasMore(cacheMeta!.hasMore);- setMessagesLoading(false);+ cacheMeta = res.cacheMeta;+ hasCachedMessages = res.painted;+ if (!res.painted) {+ // The correct conversation has no cache — clear the stale+ // optimistic render so the Phase B merge below starts from an+ // empty list instead of mixing conversation A's messages into B.+ setMessages([]);+ setMessagesLoading(true);}+ } else if (!optimisticConvId) {+ // Nothing painted yet — read the resolved conversation's cache.+ const res = await paintFromCache(convId);+ if (ignore) return;+ cacheMeta = res.cacheMeta;+ hasCachedMessages = res.painted;}+ // else: optimistic id matched the confirmed id — keep the paint.+ //+ // We always fall through to Phase B: even when the cache is fresh+ // (idMatches && countMatches), conversationInit returns cache_valid+ // and is still needed for conversation meta / tasks / artifacts, and+ // it does NOT re-set messages — so a fresh cache means exactly one+ // setMessages (the instant paint), no flicker. Phase B also writes+ // the server-confirmed last_open pointer for both fresh and stale.} catch {// checkFreshness failed — fall back to chatInit below}@@ -617,20 +994,66 @@ export function AgentChatView({// Phase B: full data fetch (background hydration or stale-cache refresh)if (convId) {+ loadConvIdRef.current = convId;const data = await conversationInit(convId, workspaceId, {newestMessageId: cacheMeta?.newestMessageId ?? undefined,- messageCount: cacheMeta?.serverMessageCount ?? undefined,+ // 0 means "count unknown" (e.g. cached via the chatInit fallback,+ // which has no server total) — omit the param so the server skips+ // the count compare and relies on newestMessageId alone. Sending+ // "0" would make the server's `serverMessageCount === 0` check fail+ // for every non-empty conversation, forcing a needless full merge.+ messageCount: cacheMeta?.serverMessageCount || undefined,});if (ignore) return;setConversation(data.conversation);setHasMoreConversations(data.has_more_conversations);if (!data.cache_valid && data.messages) {+ // Stale cache — merge server data in place, preserving scroll+ // position unless the user was already near the bottom (A2 / TODO 5).+ const wasNearBottom = isNearBottom.current;setMessages((prev) => mergeMessages(prev, data.messages!));- writeToCacheRef.current(data.messages, data.has_more_messages, data.message_count).catch(() => {});+ if (loadConvIdRef.current === convId) {+ mergeCachedMessages(+ convId,+ data.messages,+ data.has_more_messages,+ workspaceId,+ data.message_count,+ ).catch(() => {});+ }setHasMore(data.has_more_messages);+ if (+ hasCachedMessages &&+ initialScrollDone.current &&+ wasNearBottom+ ) {+ scrollToBottom();+ }} else if (cacheMeta) {setHasMore(cacheMeta.hasMore);}+ // Record the last-open pointer with server-confirmed freshness so the+ // next param-less open can resolve this conversation locally. Re-read+ // the cache meta (just updated by mergeCachedMessages on the stale+ // path) so the stored newest id is authoritative rather than inferred+ // from page order.+ if (loadConvIdRef.current === convId) {+ const confirmedMeta = await getCacheMeta(convId, workspaceId);+ if (ignore) return;+ setLastOpenConversation(+ agentId,+ activeChannel,+ {+ conversation_id: convId,+ newestMessageId:+ confirmedMeta?.newestMessageId ??+ cacheMeta?.newestMessageId ??+ null,+ serverMessageCount: data.message_count,+ },+ workspaceId,+ ).catch(() => {});+ }setThinkingCounts(data.thinking_counts);setArtifacts(data.artifacts);setBufferedMessages(data.buffered_messages);@@ -639,16 +1062,32 @@ export function AgentChatView({setActiveTask(data.active_task);setTaskMessages(data.task_messages);if (data.task_messages.length > 0) {- lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));+ lastSeqRef.current = Math.max(+ ...data.task_messages.map((m) => m.seq),+ );}- startPollingRef.current?.(data.active_task.id, convId, lastSeqRef.current);+ startPollingRef.current?.(+ data.active_task.id,+ convId,+ lastSeqRef.current,+ );}if (scrollToTaskId) {- const task = await getTask(scrollToTaskId, workspaceId).catch(() => null);+ const task = await getTask(scrollToTaskId, workspaceId).catch(+ () => null,+ );if (ignore) return;- if (task && !["completed", "failed", "cancelled", "superseded"].includes(task.status)) {+ if (+ task &&+ !["completed", "failed", "cancelled", "superseded"].includes(+ task.status,+ )+ ) {setActiveTask(task);- const tmsgs = await getTaskMessages(scrollToTaskId, workspaceId).catch(() => [] as TaskMessageResponse[]);+ const tmsgs = await getTaskMessages(+ scrollToTaskId,+ workspaceId,+ ).catch(() => [] as TaskMessageResponse[]);if (ignore) return;setTaskMessages(tmsgs);if (tmsgs.length > 0) {@@ -661,24 +1100,70 @@ export function AgentChatView({// checkFreshness failed entirely — fall back to chatInitconst data = await chatInit(agentId, workspaceId, activeChannel);if (ignore) return;+ loadConvIdRef.current = data.conversation.id;setConversation(data.conversation);- setMessages((prev) => prev.length > 0 ? mergeMessages(prev, data.messages) : data.messages);+ const wasNearBottom = isNearBottom.current;+ setMessages((prev) =>+ prev.length > 0+ ? mergeMessages(prev, data.messages)+ : data.messages,+ );setHasMore(data.has_more_messages);setArtifacts(data.artifacts);setBufferedMessages(data.buffered_messages);setHasMoreConversations(data.has_more_conversations);- writeToCacheRef.current(data.messages, data.has_more_messages).catch(() => {});+ mergeCachedMessages(+ data.conversation.id,+ data.messages,+ data.has_more_messages,+ workspaceId,+ ).catch(() => {});+ setLastOpenConversation(+ agentId,+ activeChannel,+ {+ conversation_id: data.conversation.id,+ newestMessageId:+ data.messages.length > 0+ ? data.messages[data.messages.length - 1].id+ : null,+ // chatInit returns no server total; data.messages is only the first+ // page. When more pages exist, the count is unknown — store 0, which+ // the read site treats as "unknown" and omits from the freshness+ // compare (relying on newestMessageId instead). Storing the partial+ // page length would otherwise force a needless full merge next open.+ serverMessageCount: data.has_more_messages+ ? 0+ : data.messages.length,+ },+ workspaceId,+ ).catch(() => {});+ if (hasCachedMessages && initialScrollDone.current && wasNearBottom) {+ scrollToBottom();+ }listFlaggedMessageIds(workspaceId, data.conversation.id)- .then((r) => { if (!ignore) setFlaggedIds(new Set(r.message_ids)); })+ .then((r) => {+ if (!ignore) setFlaggedIds(new Set(r.message_ids));+ }).catch(() => {});if (data.active_task) {setActiveTask(data.active_task);if (data.task_messages.length > 0) {setTaskMessages(data.task_messages);- lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));+ lastSeqRef.current = Math.max(+ ...data.task_messages.map((m) => m.seq),+ );}- if (!["completed", "failed", "cancelled", "superseded"].includes(data.active_task.status)) {- startPollingRef.current?.(data.active_task.id, data.conversation.id, lastSeqRef.current);+ if (+ !["completed", "failed", "cancelled", "superseded"].includes(+ data.active_task.status,+ )+ ) {+ startPollingRef.current?.(+ data.active_task.id,+ data.conversation.id,+ lastSeqRef.current,+ );}}}@@ -689,16 +1174,34 @@ export function AgentChatView({toast.error("Couldn't refresh conversation");}} finally {- if (!ignore) setMessagesLoading(false);+ if (!ignore) {+ setMessagesLoading(false);+ // Mark this fast-path identity as completed only now, so a re-fire+ // caused purely by a channel-dep change is deduped (TODO 6) — while a+ // run cancelled before reaching here leaves no marker, letting the+ // successor run take over and clear the skeleton.+ markFastLoadCompleted(fastKey, fastLoadGateRef.current);+ }}}load();- return () => { ignore = true; };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel, channelLoading]);+ return () => {+ ignore = true;+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ agentId,+ workspaceId,+ targetConvId,+ scrollToTaskId,+ activeChannel,+ channelLoading,+ ]);const refreshInboxCountRef = useRef(refreshInboxCount);- useEffect(() => { refreshInboxCountRef.current = refreshInboxCount; }, [refreshInboxCount]);+ useEffect(() => {+ refreshInboxCountRef.current = refreshInboxCount;+ }, [refreshInboxCount]);const markedReadRef = useRef<string | null>(null);useEffect(() => {@@ -724,12 +1227,19 @@ export function AgentChatView({isNearBottom.current = false;} else if (propTargetConvId) {setTimeout(() => {- const assistantMsgs = scrollRef.current?.querySelectorAll('[data-quote-source]');+ const assistantMsgs = scrollRef.current?.querySelectorAll(+ "[data-quote-source]",+ );if (assistantMsgs && assistantMsgs.length > 0) {const lastAssistant = assistantMsgs[assistantMsgs.length - 1];- lastAssistant.scrollIntoView({ behavior: "instant", block: "start" });+ lastAssistant.scrollIntoView({+ behavior: "instant",+ block: "start",+ });} else {- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });+ scrollRef.current?.scrollTo({+ top: scrollRef.current.scrollHeight,+ });}}, 50);} else {@@ -738,7 +1248,13 @@ export function AgentChatView({}, 50);}}- }, [messagesLoading, messages.length, scrollToTaskId, scrollToMessageId, propTargetConvId]);+ }, [+ messagesLoading,+ messages.length,+ scrollToTaskId,+ scrollToMessageId,+ propTargetConvId,+ ]);// Scroll to task when ?task= param is presentuseEffect(() => {@@ -749,7 +1265,9 @@ export function AgentChatView({let highlightTimerId: ReturnType<typeof setTimeout> | undefined;const tryScroll = () => {if (cancelled) return false;- const el = document.querySelector(`[data-task-id="${CSS.escape(scrollToTaskId)}"]`);+ const el = document.querySelector(+ `[data-task-id="${CSS.escape(scrollToTaskId)}"]`,+ );if (!el) return false;el.scrollIntoView({ behavior: "smooth", block: "start" });el.classList.add("task-highlight");@@ -763,7 +1281,11 @@ export function AgentChatView({if (cancelled) return;if (tryScroll()) return;try {- const around = await listMessagesAroundTask(conversation.id, workspaceId, scrollToTaskId);+ const around = await listMessagesAroundTask(+ conversation.id,+ workspaceId,+ scrollToTaskId,+ );if (cancelled) return;if (around.length > 0) {setMessages((prev) => mergeMessages(prev, around));@@ -790,14 +1312,22 @@ export function AgentChatView({// Scroll to message when ?msg= param is present (skip if task scroll is active)useEffect(() => {- if (!scrollToMessageId || scrollToTaskId || messagesLoading || !conversation) return;+ if (+ !scrollToMessageId ||+ scrollToTaskId ||+ messagesLoading ||+ !conversation+ )+ return;isNearBottom.current = false;scrollTargetActiveRef.current = true;let cancelled = false;let highlightTimerId: ReturnType<typeof setTimeout> | undefined;const tryScroll = () => {if (cancelled) return false;- const el = document.querySelector(`[data-message-id="${CSS.escape(scrollToMessageId)}"]`);+ const el = document.querySelector(+ `[data-message-id="${CSS.escape(scrollToMessageId)}"]`,+ );if (!el) return false;el.scrollIntoView({ behavior: "smooth", block: "start" });el.classList.add("task-highlight");@@ -831,7 +1361,10 @@ export function AgentChatView({}}, [taskMessages.length, taskStatus, scrollToBottom]);- const agentName = useMemo(() => agents.find((a) => a.id === agentId)?.name ?? "Agent", [agents, agentId]);+ const agentName = useMemo(+ () => agents.find((a) => a.id === agentId)?.name ?? "Agent",+ [agents, agentId],+ );const messagesRef = useLatest(messages);const hasMoreRef = useLatest(hasMore);@@ -840,196 +1373,239 @@ export function AgentChatView({const agentNameRef = useLatest(agentName);const activeChannelRef = useLatest(activeChannel);- const loadOlderMessages = useCallback(async (scrollToEnd = false) => {- if (!conversation || loadingMoreRef.current) return;- loadingMoreRef.current = true;-- const currentMessages = messagesRef.current;- const currentHasMore = hasMoreRef.current;- const currentHasMoreConvs = hasMoreConvsRef.current;- const currentAgentName = agentNameRef.current;- const currentChannel = activeChannelRef.current;- const isSingleConvView = !!targetConvId;-- const oldest = currentMessages[0];- const paginatingConvId = oldestConversationCursorRef.current?.id ?? conversation.id;- const canLoadMoreInConv = currentHasMore && oldest;- let prevConvsList = prevConvsRef.current;-- if (!isSingleConvView && !canLoadMoreInConv && prevConvsList.length === 0 && currentHasMoreConvs) {- const oldestConv = oldestConversationCursorRef.current ?? { id: conversation.id, created_at: conversation.created_at };- try {- const result = await listPreviousConversations(agentId, workspaceId, {- exclude: conversation.id,- before: oldestConv.created_at,- channel: currentChannel,- });- prevConvsList = result.conversations;- setPreviousConversations(result.conversations);- setHasMoreConversations(result.has_more);- } catch {- setHasMoreConversations(false);+ const loadOlderMessages = useCallback(+ async (scrollToEnd = false) => {+ if (!conversation || loadingMoreRef.current) return;+ loadingMoreRef.current = true;++ const currentMessages = messagesRef.current;+ const currentHasMore = hasMoreRef.current;+ const currentHasMoreConvs = hasMoreConvsRef.current;+ const currentAgentName = agentNameRef.current;+ const currentChannel = activeChannelRef.current;+ const isSingleConvView = !!targetConvId;++ const oldest = currentMessages[0];+ const paginatingConvId =+ oldestConversationCursorRef.current?.id ?? conversation.id;+ const canLoadMoreInConv = currentHasMore && oldest;+ let prevConvsList = prevConvsRef.current;++ if (+ !isSingleConvView &&+ !canLoadMoreInConv &&+ prevConvsList.length === 0 &&+ currentHasMoreConvs+ ) {+ const oldestConv = oldestConversationCursorRef.current ?? {+ id: conversation.id,+ created_at: conversation.created_at,+ };+ try {+ const result = await listPreviousConversations(agentId, workspaceId, {+ exclude: conversation.id,+ before: oldestConv.created_at,+ channel: currentChannel,+ });+ prevConvsList = result.conversations;+ setPreviousConversations(result.conversations);+ setHasMoreConversations(result.has_more);+ } catch {+ setHasMoreConversations(false);+ }}- }- const canLoadPrevConv = !isSingleConvView && prevConvsList.length > 0;+ const canLoadPrevConv = !isSingleConvView && prevConvsList.length > 0;- if (!canLoadMoreInConv && !canLoadPrevConv) {- loadingMoreRef.current = false;- return;- }-- setLoadingMore(true);- const el = scrollRef.current;- if (el) el.style.overflowAnchor = "none";- const prevScrollHeight = el?.scrollHeight ?? 0;-- try {- let phase1Messages: Message[] = [];- let phase2Messages: Message[] = [];- let remaining = MESSAGE_LIMIT;- let lastHasMore = false;- const napMarkersToAdd: { agentName: string; created_at: string; id: string }[] = [];-- // --- Phase 1: Load from current/paginating conversation ---- let phase1HasMore = false;- if (canLoadMoreInConv) {- const cached = paginatingConvId === conversation.id- ? await getCachedMessagesBefore(paginatingConvId, oldest!.created_at, oldest!.id, MESSAGE_LIMIT, workspaceId)- : null;-- if (cached) {- phase1Messages = cached.messages;- remaining -= cached.messages.length;- lastHasMore = cached.hasMore;- } else {- const result = await listMessages(paginatingConvId, workspaceId, {- limit: MESSAGE_LIMIT,- before: oldest!.created_at,- beforeId: oldest!.id,- });- phase1Messages = result.messages;- remaining -= result.messages.length;- lastHasMore = result.has_more;- }- phase1HasMore = lastHasMore;+ if (!canLoadMoreInConv && !canLoadPrevConv) {+ loadingMoreRef.current = false;+ return;}- // --- Phase 2: Load from previous conversations (only in timeline mode) ---- if (!isSingleConvView && !lastHasMore && remaining > 0) {- if (prevConvsList.length === 0 && currentHasMoreConvs) {- const oldestConv = oldestConversationCursorRef.current ?? { id: conversation.id, created_at: conversation.created_at };- try {- const result = await listPreviousConversations(agentId, workspaceId, {- exclude: conversation.id,- before: oldestConv.created_at,- channel: currentChannel,+ setLoadingMore(true);+ const el = scrollRef.current;+ if (el) el.style.overflowAnchor = "none";+ const prevScrollHeight = el?.scrollHeight ?? 0;++ try {+ let phase1Messages: Message[] = [];+ let phase2Messages: Message[] = [];+ let remaining = MESSAGE_LIMIT;+ let lastHasMore = false;+ const napMarkersToAdd: {+ agentName: string;+ created_at: string;+ id: string;+ }[] = [];++ // --- Phase 1: Load from current/paginating conversation ---+ let phase1HasMore = false;+ if (canLoadMoreInConv) {+ const cached =+ paginatingConvId === conversation.id+ ? await getCachedMessagesBefore(+ paginatingConvId,+ oldest!.created_at,+ oldest!.id,+ MESSAGE_LIMIT,+ workspaceId,+ )+ : null;++ if (cached) {+ phase1Messages = cached.messages;+ remaining -= cached.messages.length;+ lastHasMore = cached.hasMore;+ } else {+ const result = await listMessages(paginatingConvId, workspaceId, {+ limit: MESSAGE_LIMIT,+ before: oldest!.created_at,+ beforeId: oldest!.id,});- prevConvsList = result.conversations;- setPreviousConversations(result.conversations);- setHasMoreConversations(result.has_more);- } catch {- setHasMoreConversations(false);+ phase1Messages = result.messages;+ remaining -= result.messages.length;+ lastHasMore = result.has_more;}+ phase1HasMore = lastHasMore;}- let consumed = 0;- let fetchCount = 0;+ // --- Phase 2: Load from previous conversations (only in timeline mode) ---+ if (!isSingleConvView && !lastHasMore && remaining > 0) {+ if (prevConvsList.length === 0 && currentHasMoreConvs) {+ const oldestConv = oldestConversationCursorRef.current ?? {+ id: conversation.id,+ created_at: conversation.created_at,+ };+ try {+ const result = await listPreviousConversations(+ agentId,+ workspaceId,+ {+ exclude: conversation.id,+ before: oldestConv.created_at,+ channel: currentChannel,+ },+ );+ prevConvsList = result.conversations;+ setPreviousConversations(result.conversations);+ setHasMoreConversations(result.has_more);+ } catch {+ setHasMoreConversations(false);+ }+ }- while (- consumed < prevConvsList.length &&- remaining > 0 &&- fetchCount < MAX_CONV_FETCHES_PER_CLICK- ) {- const prevConv = prevConvsList[consumed]!;- consumed++;- fetchCount++;- const result = await listMessages(prevConv.id, workspaceId, {- limit: remaining,- });+ let consumed = 0;+ let fetchCount = 0;++ while (+ consumed < prevConvsList.length &&+ remaining > 0 &&+ fetchCount < MAX_CONV_FETCHES_PER_CLICK+ ) {+ const prevConv = prevConvsList[consumed]!;+ consumed++;+ fetchCount++;+ const result = await listMessages(prevConv.id, workspaceId, {+ limit: remaining,+ });- if (result.messages.length === 0) {- oldestConversationCursorRef.current = prevConv;- continue;- }+ if (result.messages.length === 0) {+ oldestConversationCursorRef.current = prevConv;+ continue;+ }- const napTs = oldestConversationCursorRef.current?.created_at ?? conversation.created_at;- napMarkersToAdd.push({- agentName: currentAgentName,- created_at: napTs,- id: `nap-${prevConv.id}`,- });+ const napTs =+ oldestConversationCursorRef.current?.created_at ??+ conversation.created_at;+ napMarkersToAdd.push({+ agentName: currentAgentName,+ created_at: napTs,+ id: `nap-${prevConv.id}`,+ });- phase2Messages = [...result.messages, ...phase2Messages];- remaining -= result.messages.length;- lastHasMore = result.has_more;- oldestConversationCursorRef.current = prevConv;- }+ phase2Messages = [...result.messages, ...phase2Messages];+ remaining -= result.messages.length;+ lastHasMore = result.has_more;+ oldestConversationCursorRef.current = prevConv;+ }- if (consumed > 0) {- setPreviousConversations((prev) => prev.slice(consumed));+ if (consumed > 0) {+ setPreviousConversations((prev) => prev.slice(consumed));+ }}- }- // --- Final state update ---- const allNewMessages = [...phase2Messages, ...phase1Messages];- flushSync(() => {- if (allNewMessages.length > 0) {- if (napMarkersToAdd.length > 0) {- setNapMarkers((prev) => {+ // --- Final state update ---+ const allNewMessages = [...phase2Messages, ...phase1Messages];+ flushSync(() => {+ if (allNewMessages.length > 0) {+ if (napMarkersToAdd.length > 0) {+ setNapMarkers((prev) => {+ const existingIds = new Set(prev.map((m) => m.id));+ const newMarkers = napMarkersToAdd.filter(+ (m) => !existingIds.has(m.id),+ );+ return [...prev, ...newMarkers];+ });+ }+ setHasMore(lastHasMore);+ setMessages((prev) => {const existingIds = new Set(prev.map((m) => m.id));- const newMarkers = napMarkersToAdd.filter((m) => !existingIds.has(m.id));- return [...prev, ...newMarkers];+ const unique = allNewMessages.filter(+ (m) => !existingIds.has(m.id),+ );+ return [...unique, ...prev];});+ } else {+ setHasMore(false);}- setHasMore(lastHasMore);- setMessages((prev) => {- const existingIds = new Set(prev.map((m) => m.id));- const unique = allNewMessages.filter((m) => !existingIds.has(m.id));- return [...unique, ...prev];- });- } else {- setHasMore(false);- }- });+ });- if (allNewMessages.length > 0 && conversation) {- const currentConvMessages = allNewMessages.filter((m) => m.conversation_id === conversation.id);- if (currentConvMessages.length > 0) {- mergeCachedMessages(conversation.id, currentConvMessages, phase1HasMore, workspaceId).catch(() => {});+ if (allNewMessages.length > 0 && conversation) {+ const currentConvMessages = allNewMessages.filter(+ (m) => m.conversation_id === conversation.id,+ );+ if (currentConvMessages.length > 0) {+ mergeCachedMessages(+ conversation.id,+ currentConvMessages,+ phase1HasMore,+ workspaceId,+ ).catch(() => {});+ }}- }- loadingMoreRef.current = false;- flushSync(() => setLoadingMore(false));+ loadingMoreRef.current = false;+ flushSync(() => setLoadingMore(false));- if (el) {- if (scrollToEnd) {- el.scrollTop = el.scrollHeight;- } else {- const newScrollHeight = el.scrollHeight;- el.scrollTop = newScrollHeight - prevScrollHeight;+ if (el) {+ if (scrollToEnd) {+ el.scrollTop = el.scrollHeight;+ } else {+ const newScrollHeight = el.scrollHeight;+ el.scrollTop = newScrollHeight - prevScrollHeight;+ }}+ } catch {+ toast.error("Failed to load older messages");+ } finally {+ loadingMoreRef.current = false;+ setLoadingMore(false);+ if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";}- } catch {- toast.error("Failed to load older messages");- } finally {- loadingMoreRef.current = false;- setLoadingMore(false);- if (scrollRef.current) scrollRef.current.style.overflowAnchor = "";- }- }, [- conversation,- workspaceId,- agentId,- targetConvId,- messagesRef,- hasMoreRef,- hasMoreConvsRef,- agentNameRef,- activeChannelRef,- prevConvsRef,- ]);+ },+ [+ conversation,+ workspaceId,+ agentId,+ targetConvId,+ messagesRef,+ hasMoreRef,+ hasMoreConvsRef,+ agentNameRef,+ activeChannelRef,+ prevConvsRef,+ ],+ );const canLoadMore = targetConvId? hasMore@@ -1050,7 +1626,16 @@ export function AgentChatView({if (backfillAttemptsRef.current >= 3) return;backfillAttemptsRef.current += 1;loadOlderMessages(true);- }, [messagesLoading, messages.length, canLoadMore, loadingMore, conversation, loadOlderMessages, scrollToTaskId, targetConvId]);+ }, [+ messagesLoading,+ messages.length,+ canLoadMore,+ loadingMore,+ conversation,+ loadOlderMessages,+ scrollToTaskId,+ targetConvId,+ ]);const handleScroll = useCallback(() => {const el = scrollRef.current;@@ -1074,7 +1659,11 @@ export function AgentChatView({try {const [task, tmsgs] = await Promise.all([getTask(taskId, workspaceId),- getTaskMessages(taskId, workspaceId, lastSeqRef.current || undefined),+ getTaskMessages(+ taskId,+ workspaceId,+ lastSeqRef.current || undefined,+ ),]);// Re-check after await — a followup.dispatched may have started a new poll@@ -1091,40 +1680,57 @@ export function AgentChatView({});lastSeqRef.current = Math.max(...tmsgs.map((m) => m.seq),- lastSeqRef.current+ lastSeqRef.current,);}- if (task.status === "completed" || task.status === "failed" || task.status === "cancelled" || task.status === "superseded") {+ if (+ task.status === "completed" ||+ task.status === "failed" ||+ task.status === "cancelled" ||+ task.status === "superseded"+ ) {if (isStale) {// Stale poll — still merge messages but don't touch activeTask or pollinglistMessages(conversationId, workspaceId).then(({ messages: latest }) => {setMessages((prev) => mergeMessages(prev, latest));- mergeCachedMessages(conversationId, latest, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ conversationId,+ latest,+ null,+ workspaceId,+ ).catch(() => {});})- .catch(() => { });+ .catch(() => {});return;}if (pollRef.current) clearInterval(pollRef.current);pollRef.current = null;- if (markReadTimerRef.current) clearTimeout(markReadTimerRef.current);+ if (markReadTimerRef.current)+ clearTimeout(markReadTimerRef.current);markReadTimerRef.current = setTimeout(() => {markInboxRead(conversationId, workspaceId).then(() => refreshInboxCountRef.current()).catch(() => {});}, 1000);- const shouldScroll = !scrollTargetActiveRef.current && isNearBottom.current;+ const shouldScroll =+ !scrollTargetActiveRef.current && isNearBottom.current;try {const [latestResult, arts] = await Promise.all([listMessages(conversationId, workspaceId),listArtifacts(conversationId, workspaceId).catch(() => null),]);setMessages((prev) => mergeMessages(prev, latestResult.messages));- mergeCachedMessages(conversationId, latestResult.messages, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ conversationId,+ latestResult.messages,+ null,+ workspaceId,+ ).catch(() => {});if (arts) setArtifacts(arts);setActiveTask(task);} catch {@@ -1152,14 +1758,22 @@ export function AgentChatView({]);setBufferedMessages(latestBuffered);if (nextTask && nextTask.id !== taskId) {- const { messages: latestMsgs } = await listMessages(conversationId, workspaceId);+ const { messages: latestMsgs } = await listMessages(+ conversationId,+ workspaceId,+ );setMessages((prev) => mergeMessages(prev, latestMsgs));- mergeCachedMessages(conversationId, latestMsgs, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ conversationId,+ latestMsgs,+ null,+ workspaceId,+ ).catch(() => {});setActiveTask(nextTask);setTaskMessages([]);startPollingRef.current?.(nextTask.id, conversationId);}- } catch { }+ } catch {}}, 1000);} else if (!isStale) {setActiveTask(task);@@ -1178,7 +1792,7 @@ export function AgentChatView({}}, 3000);},- [workspaceId]+ [workspaceId],);useEffect(() => {startPollingRef.current = startPolling;@@ -1199,7 +1813,10 @@ export function AgentChatView({useEffect(() => {return subscribeWs((msg: WsMessage) => {- if (msg.type === "task.messages" && msg.taskId === activeTaskIdRef.current) {+ if (+ msg.type === "task.messages" &&+ msg.taskId === activeTaskIdRef.current+ ) {const incoming = msg.messages.filter((m) => m.seq > lastSeqRef.current);if (incoming.length > 0) {setTaskMessages((prev) => {@@ -1207,14 +1824,25 @@ export function AgentChatView({const unique = incoming.filter((m) => !existingSeqs.has(m.seq));return unique.length > 0 ? [...prev, ...unique] : prev;});- lastSeqRef.current = Math.max(...incoming.map((m) => m.seq), lastSeqRef.current);+ lastSeqRef.current = Math.max(+ ...incoming.map((m) => m.seq),+ lastSeqRef.current,+ );}}- if (msg.type === "task.created" && msg.conversationId === conversation?.id) {+ if (+ msg.type === "task.created" &&+ msg.conversationId === conversation?.id+ ) {listMessages(msg.conversationId, workspaceId).then(({ messages: latest }) => {setMessages((prev) => mergeMessages(prev, latest));- mergeCachedMessages(msg.conversationId, latest, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ msg.conversationId,+ latest,+ null,+ workspaceId,+ ).catch(() => {});}).catch(() => {});const task = msg.task as Task;@@ -1225,7 +1853,16 @@ export function AgentChatView({startPollingRef.current?.(task.id, msg.conversationId);}if (msg.type === "conversation.message") {- appendCachedMessage(msg.conversationId, msg.message, workspaceId).catch(() => {});+ // Only cache for the server-confirmed loaded conversation — never write+ // during the optimistic cache-first window before the id is confirmed+ // (review #1).+ if (msg.conversationId === loadConvIdRef.current) {+ appendCachedMessage(+ msg.conversationId,+ msg.message,+ workspaceId,+ ).catch(() => {});+ }if (msg.conversationId === conversation?.id) {setMessages((prev) => {const incomingTime = new Date(msg.message.created_at).getTime();@@ -1234,7 +1871,8 @@ export function AgentChatView({m.id.startsWith("temp-") &&m.role === msg.message.role &&m.content === msg.message.content &&- Math.abs(new Date(m.created_at).getTime() - incomingTime) < 2000+ Math.abs(new Date(m.created_at).getTime() - incomingTime) <+ 2000,);if (optimisticIdx !== -1) {const updated = [...prev];@@ -1245,40 +1883,70 @@ export function AgentChatView({});}}- if (msg.type === "task.updated" && msg.taskId === activeTaskIdRef.current) {- setActiveTask((prev) => prev ? { ...prev, status: msg.status } : prev);+ if (+ msg.type === "task.updated" &&+ msg.taskId === activeTaskIdRef.current+ ) {+ setActiveTask((prev) =>+ prev ? { ...prev, status: msg.status } : prev,+ );}- if (msg.type === "artifact.uploaded" && msg.conversationId === conversation?.id) {+ if (+ msg.type === "artifact.uploaded" &&+ msg.conversationId === conversation?.id+ ) {setArtifacts((prev) => {if (prev.some((a) => a.id === msg.artifact.id)) return prev;return [...prev, msg.artifact];});}- if (msg.type === "followup.dispatched" && msg.conversationId === conversation?.id) {+ if (+ msg.type === "followup.dispatched" &&+ msg.conversationId === conversation?.id+ ) {// Optimistically remove by real ID- setBufferedMessages((prev) => prev.filter((m) => m.id !== msg.message.id));+ setBufferedMessages((prev) =>+ prev.filter((m) => m.id !== msg.message.id),+ );// Always sync from server to handle temp-ID / duplicate edge caseslistBufferedMessages(msg.conversationId, workspaceId)- .then(setBufferedMessages).catch(() => {});+ .then(setBufferedMessages)+ .catch(() => {});listMessages(msg.conversationId, workspaceId).then(({ messages: latest }) => {setMessages((prev) => mergeMessages(prev, latest));- mergeCachedMessages(msg.conversationId, latest, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ msg.conversationId,+ latest,+ null,+ workspaceId,+ ).catch(() => {});})- .catch(() => { });+ .catch(() => {});const task = msg.task as Task;activeTaskIdRef.current = task.id;setActiveTask(task);setTaskMessages([]);startPollingRef.current?.(task.id, msg.conversationId);}- if (msg.type === "followup.created" && msg.conversationId === conversation?.id) {+ if (+ msg.type === "followup.created" &&+ msg.conversationId === conversation?.id+ ) {setBufferedMessages((prev) => addBufferedIfNew(prev, msg.message));}- if (msg.type === "followup.deleted" && msg.conversationId === conversation?.id) {- setBufferedMessages((prev) => prev.filter((m) => m.id !== msg.messageId));+ if (+ msg.type === "followup.deleted" &&+ msg.conversationId === conversation?.id+ ) {+ setBufferedMessages((prev) =>+ prev.filter((m) => m.id !== msg.messageId),+ );}- if (msg.type === "followup.dispatch_failed" && msg.conversationId === conversation?.id) {+ if (+ msg.type === "followup.dispatch_failed" &&+ msg.conversationId === conversation?.id+ ) {toast.error(msg.error || "Failed to dispatch follow-up");}});@@ -1291,22 +1959,29 @@ export function AgentChatView({conversationInit(conversation.id, workspaceId, {newestMessageId: meta?.newestMessageId ?? undefined,messageCount: meta?.serverMessageCount ?? undefined,- }).then((data) => {- if (!data.cache_valid && data.messages) {- setMessages((prev) => mergeMessages(prev, data.messages!));- writeToCacheRef.current(data.messages, data.has_more_messages, data.message_count).catch(() => {});- }- }).catch(() => {});+ })+ .then((data) => {+ if (!data.cache_valid && data.messages) {+ setMessages((prev) => mergeMessages(prev, data.messages!));+ writeToCacheRef+ .current(+ data.messages,+ data.has_more_messages,+ data.message_count,+ )+ .catch(() => {});+ }+ })+ .catch(() => {});});});}, [subscribeReconnect, conversation?.id, workspaceId]);- const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {- const fileList = e.target.files;- if (!fileList) return;-+ // Validate (10 MB cap) + stage files. Shared by the file picker, drag/drop,+ // and the composer's paste/drop handlers.+ const addPendingFiles = useCallback((files: File[]) => {const valid: File[] = [];- for (const file of Array.from(fileList)) {+ for (const file of files) {if (file.size > MAX_FILE_SIZE) {toast.error(`"${file.name}" exceeds 10 MB limit`);} else {@@ -1316,10 +1991,19 @@ export function AgentChatView({if (valid.length > 0) {setPendingFiles((prev) => [...prev, ...valid]);}- // Reset input so re-selecting the same file works- e.target.value = "";}, []);+ const handleFileSelect = useCallback(+ (e: React.ChangeEvent<HTMLInputElement>) => {+ const fileList = e.target.files;+ if (!fileList) return;+ addPendingFiles(Array.from(fileList));+ // Reset input so re-selecting the same file works+ e.target.value = "";+ },+ [addPendingFiles],+ );+const removePendingFile = useCallback((index: number) => {setPendingFiles((prev) => prev.filter((_, i) => i !== index));}, []);@@ -1331,12 +2015,16 @@ export function AgentChatView({return;}const text = selection.toString().trim();- if (!text) { setSelectionPopup(null); return; }+ if (!text) {+ setSelectionPopup(null);+ return;+ }// Only allow quoting from assistant message bubblesconst range = selection.getRangeAt(0);- const container = range.commonAncestorContainer instanceof HTMLElement- ? range.commonAncestorContainer- : range.commonAncestorContainer.parentElement;+ const container =+ range.commonAncestorContainer instanceof HTMLElement+ ? range.commonAncestorContainer+ : range.commonAncestorContainer.parentElement;if (!container?.closest("[data-quote-source]")) {setSelectionPopup(null);return;@@ -1348,7 +2036,8 @@ export function AgentChatView({useEffect(() => {document.addEventListener("selectionchange", handleTextSelect);- return () => document.removeEventListener("selectionchange", handleTextSelect);+ return () =>+ document.removeEventListener("selectionchange", handleTextSelect);}, [handleTextSelect]);const handleQuoteSelection = useCallback(() => {@@ -1356,7 +2045,7 @@ export function AgentChatView({setQuotedText(selectionPopup.text);setSelectionPopup(null);window.getSelection()?.removeAllRanges();- textareaRef.current?.focus();+ composerRef.current?.focus();}}, [selectionPopup]);@@ -1386,56 +2075,16 @@ export function AgentChatView({e.stopPropagation();}, []);- const handleDrop = useCallback((e: React.DragEvent) => {- e.preventDefault();- e.stopPropagation();- setDragging(false);- dragCounter.current = 0;-- const droppedFiles = Array.from(e.dataTransfer.files);- const valid: File[] = [];- for (const file of droppedFiles) {- if (file.size > MAX_FILE_SIZE) {- toast.error(`"${file.name}" exceeds 10 MB limit`);- } else {- valid.push(file);- }- }- if (valid.length > 0) {- setPendingFiles((prev) => [...prev, ...valid]);- }- }, []);-- const handlePaste = useCallback((e: React.ClipboardEvent) => {- const items = e.clipboardData?.items;- if (!items) return;-- const files: File[] = [];- for (let i = 0; i < items.length; i++) {- const item = items[i];- if (item.kind === "file") {- const file = item.getAsFile();- if (file) files.push(file);- }- }-- if (files.length === 0) return;-- // Prevent default only when we have files to handle- e.preventDefault();-- const valid: File[] = [];- for (const file of files) {- if (file.size > MAX_FILE_SIZE) {- toast.error(`"${file.name}" exceeds 10 MB limit`);- } else {- valid.push(file);- }- }- if (valid.length > 0) {- setPendingFiles((prev) => [...prev, ...valid]);- }- }, []);+ const handleDrop = useCallback(+ (e: React.DragEvent) => {+ e.preventDefault();+ e.stopPropagation();+ setDragging(false);+ dragCounter.current = 0;+ addPendingFiles(Array.from(e.dataTransfer.files));+ },+ [addPendingFiles],+ );const handleStop = async () => {if (!conversation || cancelling) return;@@ -1444,7 +2093,10 @@ export function AgentChatView({const cancelled = await cancelActiveTask(conversation.id, workspaceId);if (cancelled) {// If WS followup.dispatched already set a new active task, don't overwrite- if (activeTaskIdRef.current && activeTaskIdRef.current !== cancelled.id) {+ if (+ activeTaskIdRef.current &&+ activeTaskIdRef.current !== cancelled.id+ ) {return;}if (pollRef.current) clearInterval(pollRef.current);@@ -1454,7 +2106,12 @@ export function AgentChatView({listBufferedMessages(conversation.id, workspaceId),]);setMessages((prev) => mergeMessages(prev, latestResult.messages));- mergeCachedMessages(conversation.id, latestResult.messages, null, workspaceId).catch(() => {});+ mergeCachedMessages(+ conversation.id,+ latestResult.messages,+ null,+ workspaceId,+ ).catch(() => {});setBufferedMessages(latestBuffered);setActiveTask(cancelled as Task);setTaskMessages([]);@@ -1468,7 +2125,8 @@ export function AgentChatView({const handleSend = async () => {const rawContent = input.trim();- if ((!rawContent && pendingFiles.length === 0) || sending || !conversation) return;+ if ((!rawContent && pendingFiles.length === 0) || sending || !conversation)+ return;if (!rawContent) {toast.error("Please type a message");return;@@ -1491,7 +2149,11 @@ export function AgentChatView({slashCommand.clearActiveSkill();setSending(true);- const taskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);+ const taskActive =+ !!activeTask &&+ !["completed", "failed", "cancelled", "superseded"].includes(+ activeTask.status,+ );if (taskActive) {// Buffer mode: queue message for later dispatch@@ -1515,13 +2177,17 @@ export function AgentChatView({workspaceId,filesToSend.length > 0 ? filesToSend : undefined,);- setBufferedMessages((prev) => replaceOptimisticBuffered(prev, optimisticId, message));+ setBufferedMessages((prev) =>+ replaceOptimisticBuffered(prev, optimisticId, message),+ );} catch (err) {- setBufferedMessages((prev) => prev.filter((m) => m.id !== optimisticId));+ setBufferedMessages((prev) =>+ prev.filter((m) => m.id !== optimisticId),+ );setInput(content);setPendingFiles(filesToSend);toast.error(- err instanceof Error ? err.message : "Failed to queue follow-up"+ err instanceof Error ? err.message : "Failed to queue follow-up",);} finally {setSending(false);@@ -1573,14 +2239,18 @@ export function AgentChatView({const hasReal = prev.some((m) => m.id === message.id);return hasReal ? prev : sortMessages([...prev, message]);}- const without = prev.filter((m) => m.id !== optimistic.id && m.id !== message.id);+ const without = prev.filter(+ (m) => m.id !== optimistic.id && m.id !== message.id,+ );return sortMessages([...without, message]);});- appendCachedMessage(conversation.id, message, workspaceId).catch(() => {});+ appendCachedMessage(conversation.id, message, workspaceId).catch(+ () => {},+ );if (message.attachment_ids && message.attachment_ids.length > 0) {listArtifacts(conversation.id, workspaceId).then((arts) => setArtifacts(arts))- .catch(() => { });+ .catch(() => {});}setActiveTask(task);setTaskMessages([]);@@ -1596,11 +2266,11 @@ export function AgentChatView({setInput(content);setPendingFiles(filesToSend);toast.error(- err instanceof Error ? err.message : "Failed to send message"+ err instanceof Error ? err.message : "Failed to send message",);} finally {setSending(false);- textareaRef.current?.focus();+ composerRef.current?.focus();}};@@ -1612,63 +2282,75 @@ export function AgentChatView({startPolling(newTask.id, conversation.id);}, [activeTask, conversation, workspaceId, startPolling]);- const handleToggleFlag = useCallback(async (messageId: string) => {- const wasFlagged = flaggedIdsRef.current.has(messageId);- setFlaggedIds((prev) => {- const next = new Set(prev);- if (wasFlagged) next.delete(messageId);- else next.add(messageId);- return next;- });- if (wasFlagged) {- flagDecrement();- apiUnflagMessage(workspaceId, messageId)- .then(() => { flagRefresh(); })- .catch(() => {- setFlaggedIds((prev) => new Set(prev).add(messageId));- flagIncrement();- });- } else {- flagIncrement();- apiFlagMessage(workspaceId, messageId)- .then(() => { flagRefresh(); })- .catch(() => {- setFlaggedIds((prev) => {- const next = new Set(prev);- next.delete(messageId);- return next;+ const handleToggleFlag = useCallback(+ async (messageId: string) => {+ const wasFlagged = flaggedIdsRef.current.has(messageId);+ setFlaggedIds((prev) => {+ const next = new Set(prev);+ if (wasFlagged) next.delete(messageId);+ else next.add(messageId);+ return next;+ });+ if (wasFlagged) {+ flagDecrement();+ apiUnflagMessage(workspaceId, messageId)+ .then(() => {+ flagRefresh();+ })+ .catch(() => {+ setFlaggedIds((prev) => new Set(prev).add(messageId));+ flagIncrement();+ });+ } else {+ flagIncrement();+ apiFlagMessage(workspaceId, messageId)+ .then(() => {+ flagRefresh();+ })+ .catch(() => {+ setFlaggedIds((prev) => {+ const next = new Set(prev);+ next.delete(messageId);+ return next;+ });+ flagDecrement();});- flagDecrement();- });- }- }, [workspaceId, flagIncrement, flagDecrement, flagRefresh]);-- const openIssue = useCallback(async (issueId: string) => {- setSelectedIssueId(issueId);- setIssueSheetOpen(true);- setIssueDetailLoading(true);- setIssueTraceTasks(null);- setIssueActiveTask(null);- try {- const res = await getIssue(workspaceId, issueId);- setIssueDetail(res);- if (res.issue.latest_task_id) {- getTask(res.issue.latest_task_id, workspaceId)- .then(task => setIssueActiveTask(task))- .catch(() => setIssueActiveTask(null));}- if (res.issue.trace_id) {- getTrace(res.issue.trace_id, workspaceId)- .then(t => setIssueTraceTasks(t.tasks))- .catch(() => setIssueTraceTasks(null));+ },+ [workspaceId, flagIncrement, flagDecrement, flagRefresh],+ );++ const openIssue = useCallback(+ async (issueId: string) => {+ setSelectedIssueId(issueId);+ setIssueSheetOpen(true);+ setIssueDetailLoading(true);+ setIssueTraceTasks(null);+ setIssueActiveTask(null);+ try {+ const res = await getIssue(workspaceId, issueId);+ setIssueDetail(res);+ if (res.issue.latest_task_id) {+ getTask(res.issue.latest_task_id, workspaceId)+ .then((task) => setIssueActiveTask(task))+ .catch(() => setIssueActiveTask(null));+ }+ if (res.issue.trace_id) {+ getTrace(res.issue.trace_id, workspaceId)+ .then((t) => setIssueTraceTasks(t.tasks))+ .catch(() => setIssueTraceTasks(null));+ }+ } catch (err) {+ toast.error(+ err instanceof Error ? err.message : "Failed to load issue",+ );+ setIssueSheetOpen(false);+ } finally {+ setIssueDetailLoading(false);}- } catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to load issue");- setIssueSheetOpen(false);- } finally {- setIssueDetailLoading(false);- }- }, [workspaceId]);+ },+ [workspaceId],+ );const issueConvId = issueDetail?.issue?.conversation_id ?? null;const issueTaskId = issueDetail?.issue?.latest_task_id ?? null;@@ -1677,38 +2359,68 @@ export function AgentChatView({if (!issueSheetOpen || !selectedIssueId) return;return subscribeWs((msg: WsMessage) => {- if (msg.type === "task.updated" && issueTaskId && msg.taskId === issueTaskId) {+ if (+ msg.type === "task.updated" &&+ issueTaskId &&+ msg.taskId === issueTaskId+ ) {getTask(issueTaskId, workspaceId)- .then(task => setIssueActiveTask(task))+ .then((task) => setIssueActiveTask(task)).catch(() => {});}- if (msg.type === "conversation.message" && issueConvId && msg.conversationId === issueConvId) {- setIssueDetail(prev => {+ if (+ msg.type === "conversation.message" &&+ issueConvId &&+ msg.conversationId === issueConvId+ ) {+ setIssueDetail((prev) => {if (!prev) return prev;- if (prev.messages.some(m => m.id === msg.message.id)) return prev;+ if (prev.messages.some((m) => m.id === msg.message.id)) return prev;return { ...prev, messages: [...prev.messages, msg.message] };});- if (msg.message.role === "event" && msg.message.content.startsWith("Issue status changed:")) {+ if (+ msg.message.role === "event" &&+ msg.message.content.startsWith("Issue status changed:")+ ) {const match = msg.message.content.match(/-> (\w+)/);if (match) {- setIssueDetail(prev => prev ? { ...prev, issue: { ...prev.issue, status: match[1] as Issue["status"] } } : prev);+ setIssueDetail((prev) =>+ prev+ ? {+ ...prev,+ issue: {+ ...prev.issue,+ status: match[1] as Issue["status"],+ },+ }+ : prev,+ );}}}if (msg.type === "issue.comment" && msg.issueId === selectedIssueId) {- setIssueDetail(prev => {+ setIssueDetail((prev) => {if (!prev) return prev;- if (prev.comments.some(c => c.id === msg.comment.id)) return prev;+ if (prev.comments.some((c) => c.id === msg.comment.id)) return prev;return { ...prev, comments: [...prev.comments, msg.comment] };});}});- }, [issueSheetOpen, selectedIssueId, issueConvId, issueTaskId, workspaceId, subscribeWs]);+ }, [+ issueSheetOpen,+ selectedIssueId,+ issueConvId,+ issueTaskId,+ workspaceId,+ subscribeWs,+ ]);const [napping, setNapping] = useState(false);const currentConvHasMessages = useMemo(- () => !!conversation && messages.some((m) => m.conversation_id === conversation.id),+ () =>+ !!conversation &&+ messages.some((m) => m.conversation_id === conversation.id),[conversation, messages],);@@ -1720,11 +2432,19 @@ export function AgentChatView({clearInterval(pollRef.current);pollRef.current = null;}- const newConv = await createConversation(agentId, workspaceId, activeChannel);+ const newConv = await createConversation(+ agentId,+ workspaceId,+ activeChannel,+ );setNapMarkers((prev) => [...prev,- { agentName, created_at: newConv.created_at, id: `nap-${conversation.id}` },+ {+ agentName,+ created_at: newConv.created_at,+ id: `nap-${conversation.id}`,+ },]);setPreviousConversations((prev) => [@@ -1752,16 +2472,11 @@ export function AgentChatView({}};- const handleKeyDown = (e: React.KeyboardEvent) => {- if (mentionPopup.handleMentionKeyDown(e)) return;- if (slashCommand.handleSlashKeyDown(e)) return;- if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {- e.preventDefault();- handleSend();- }- };-- const isTaskActive = !!activeTask && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);+ const isTaskActive =+ !!activeTask &&+ !["completed", "failed", "cancelled", "superseded"].includes(+ activeTask.status,+ );if (messagesLoading) {return (@@ -1792,10 +2507,10 @@ export function AgentChatView({</div></div></div>- {/* Skeleton input area */}- <div className="px-3 md:px-5 py-3">+ {/* Skeleton input area — mirrors the real rounded pill */}+ <div className="px-3 md:px-5 pt-3 pb-5 md:pb-6"><div className="mx-auto max-w-2xl">- <Skeleton className="h-18 w-full rounded-xl" />+ <Skeleton className="h-12 w-full rounded-3xl" /></div></div></>@@ -1817,7 +2532,11 @@ export function AgentChatView({<buttontype="button"className="fixed z-50 flex items-center gap-1 px-2 py-1 rounded-md bg-popover border shadow-md text-xs text-popover-foreground hover:bg-accent transition-colors"- style={{ left: selectionPopup.x, top: selectionPopup.y, transform: "translate(-100%, -100%)" }}+ style={{+ left: selectionPopup.x,+ top: selectionPopup.y,+ transform: "translate(-100%, -100%)",+ }}onMouseDown={(e) => e.preventDefault()}onClick={handleQuoteSelection}>@@ -1833,12 +2552,12 @@ export function AgentChatView({onScroll={handleScroll}onClick={(e) => {const btn = (e.target as HTMLElement).closest(- '[data-streamdown="code-block-actions"] button'+ '[data-streamdown="code-block-actions"] button',);if (btn) toast.success("Copied to clipboard");}}>- <div className="mx-auto max-w-2xl py-6 space-y-4 min-w-0">+ <div className="mx-auto max-w-2xl pt-6 pb-[60px] min-w-0">{conversation && canLoadMore && !loadingMore && (<div className="flex justify-center py-2"><button@@ -1855,306 +2574,338 @@ export function AgentChatView({</div>)}- {messages.length === 0 && !activeTask && (() => {- const agent = agents.find(a => a.id === agentId);- const isNewAgent = agent?.created_at && (renderNow - new Date(agent.created_at).getTime() < 5 * 60 * 1000);- const hasEmailTask = (activeTaskCounts[agentId] ?? 0) > 0;+ {messages.length === 0 &&+ !activeTask &&+ (() => {+ const agent = agents.find((a) => a.id === agentId);+ const isNewAgent =+ agent?.created_at &&+ renderNow - new Date(agent.created_at).getTime() <+ 5 * 60 * 1000;+ const hasEmailTask = (activeTaskCounts[agentId] ?? 0) > 0;++ if (isNewAgent && hasEmailTask && activeChannel === "default") {+ return (+ <div className="flex flex-col items-center justify-center py-20 gap-3 animate-[fade-up_400ms_ease-out_both]">+ <div className="relative animate-bounce">+ <Mail className="size-8 text-primary" />+ <span className="absolute -top-1 -right-1 flex size-3">+ <span className="animate-ping absolute inline-flex size-full rounded-full bg-primary/60" />+ <span className="relative inline-flex size-3 rounded-full bg-primary" />+ </span>+ </div>+ <p className="text-sm text-muted-foreground text-center max-w-xs">+ Your agent is sending you a welcome email.+ </p>+ <p className="text-xs text-muted-foreground/60 text-center max-w-xs">+ Wait for the email task in the top-left to complete,+ then check your inbox. Or send a message below to start+ chatting.+ </p>+ </div>+ );+ }- if (isNewAgent && hasEmailTask && activeChannel === "default") {return (- <div className="flex flex-col items-center justify-center py-20 gap-3 animate-[fade-up_400ms_ease-out_both]">- <div className="relative animate-bounce">- <Mail className="size-8 text-primary" />- <span className="absolute -top-1 -right-1 flex size-3">- <span className="animate-ping absolute inline-flex size-full rounded-full bg-primary/60" />- <span className="relative inline-flex size-3 rounded-full bg-primary" />- </span>- </div>- <p className="text-sm text-muted-foreground text-center max-w-xs">- Your agent is sending you a welcome email.- </p>- <p className="text-xs text-muted-foreground/60 text-center max-w-xs">- Wait for the email task in the top-left to complete, then check your inbox. Or send a message below to start chatting.- </p>- </div>+ <p className="text-center text-muted-foreground py-20 text-sm">+ Send a message to start chatting with the agent.+ </p>);- }+ })()}- return (- <p className="text-center text-muted-foreground py-20 text-sm">- Send a message to start chatting with the agent.- </p>- );- })()}+ {timeline.map((item, idx) => {+ const pos = groupPositions[idx];+ const isGroupStart =+ pos === "first" || pos === "solo" || pos === null;+ const spacing = idx === 0 ? "" : isGroupStart ? "mt-4" : "mt-0.5";- {timeline.map((item) => {if (item.kind === "nap") {- return <NapSeparator key={item.data.id} agentName={agentName} />;+ return (+ <div key={item.data.id} className={spacing}>+ <NapSeparator agentName={agentName} />+ </div>+ );}if (item.kind === "artifact") {return (- <ArtifactCard- key={`artifact-${item.data.id}`}- artifact={item.data}- version={versionMap.get(item.data.id) ?? 1}- hasDuplicates={duplicateFilenames.has(item.data.filename)}- onClick={handleArtifactClick}- />+ <div key={`artifact-${item.data.id}`} className={spacing}>+ <ArtifactCard+ artifact={item.data}+ version={versionMap.get(item.data.id) ?? 1}+ hasDuplicates={duplicateFilenames.has(item.data.filename)}+ onClick={handleArtifactClick}+ />+ </div>);}const msg = item.data;return (- <MessageItem- key={msg.id}- msg={msg}- agents={agents}- artifacts={artifacts}- activeTask={activeTask}- taskMessages={taskMessages}- connectionLost={connectionLost}- isLastMessage={messages.length > 0 && messages[messages.length - 1].id === msg.id}- thinkingCount={msg.task_id ? (thinkingCounts[msg.task_id] ?? 0) : 0}- targetConvId={targetConvId}- workspaceId={workspaceId}- conversationType={conversation?.type}- pendingFilesByMessage={pendingFilesByMessage}- onArtifactClick={handleArtifactClick}- onEmailClick={(emailId) => {- setSelectedEmailId(emailId);- setEmailSheetOpen(true);- }}- onCalendarEventClick={(id) => {- setSelectedCalendarEventId(id);- setCalendarEventSheetOpen(true);- }}- onIssueClick={(issueId) => openIssue(issueId)}- onRetry={handleRetryTask}- mentionComponents={MENTION_COMPONENTS}- isFlagged={flaggedIds.has(msg.id)}- onToggleFlag={msg.role === "assistant" ? handleToggleFlag : undefined}- />+ <div key={msg.id} className={spacing}>+ <MessageItem+ msg={msg}+ agents={agents}+ artifacts={artifacts}+ activeTask={activeTask}+ taskMessages={taskMessages}+ connectionLost={connectionLost}+ isLastMessage={+ messages.length > 0 &&+ messages[messages.length - 1].id === msg.id+ }+ thinkingCount={+ msg.task_id ? (thinkingCounts[msg.task_id] ?? 0) : 0+ }+ targetConvId={targetConvId}+ workspaceId={workspaceId}+ conversationType={conversation?.type}+ pendingFilesByMessage={pendingFilesByMessage}+ onArtifactClick={handleArtifactClick}+ onEmailClick={(emailId) => {+ setSelectedEmailId(emailId);+ setEmailSheetOpen(true);+ }}+ onCalendarEventClick={(id) => {+ setSelectedCalendarEventId(id);+ setCalendarEventSheetOpen(true);+ }}+ onIssueClick={(issueId) => openIssue(issueId)}+ onRetry={handleRetryTask}+ mentionComponents={MENTION_COMPONENTS}+ isFlagged={flaggedIds.has(msg.id)}+ onToggleFlag={+ msg.role === "assistant" ? handleToggleFlag : undefined+ }+ groupPosition={pos ?? "solo"}+ />+ </div>);})}{/* Show trace while task is in progress (no assistant message yet) */}- {activeTask && activeTask.conversation_id === conversation?.id && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status) && (- <TaskStream- task={activeTask}- messages={taskMessages}- connectionLost={connectionLost}- />- )}+ {activeTask &&+ activeTask.conversation_id === conversation?.id &&+ !["completed", "failed", "cancelled", "superseded"].includes(+ activeTask.status,+ ) && (+ <div className="mt-4">+ <TaskStream+ task={activeTask}+ messages={taskMessages}+ connectionLost={connectionLost}+ />+ </div>+ )}</div></div><ScrollToBottomButton scrollRef={scrollRef} /></div>{/* Follow-up buffer indicator */}- {conversation && <FollowUpBuffer- bufferedMessages={bufferedMessages}- onDelete={(messageId) => {- const prev = bufferedMessages;- setBufferedMessages((cur) => cur.filter((m) => m.id !== messageId));- deleteBufferedMessage(conversation.id, messageId, workspaceId).catch(() => {- setBufferedMessages(prev);- toast.error("Failed to delete follow-up");- });- }}- />}+ {conversation && (+ <FollowUpBuffer+ bufferedMessages={bufferedMessages}+ onDelete={(messageId) => {+ const prev = bufferedMessages;+ setBufferedMessages((cur) => cur.filter((m) => m.id !== messageId));+ deleteBufferedMessage(+ conversation.id,+ messageId,+ workspaceId,+ ).catch(() => {+ setBufferedMessages(prev);+ toast.error("Failed to delete follow-up");+ });+ }}+ />+ )}{/* Input */}- <div className="px-3 md:px-5 py-3">+ <div className="relative z-10 px-3 md:px-5 pt-3 pb-5 md:pb-6"><div className="mx-auto max-w-2xl relative">- <div- className={cn(- "relative flex flex-col rounded-xl border bg-background/60 transition-colors duration-200",- "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",- sending && "opacity-50",- dragging && "border-ring ring-3 ring-ring/50"- )}- onDragEnter={handleDragEnter}- onDragLeave={handleDragLeave}- onDragOver={handleDragOver}- onDrop={handleDrop}- >- {dragging && (- <div className="absolute inset-0 z-10 flex items-center justify-center rounded-xl bg-background/80 border-2 border-dashed border-ring pointer-events-none">- <p className="text-sm text-muted-foreground font-medium">Drop files here</p>- </div>- )}- {slashCommand.activeSkill && (- <div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">- <div className="flex-1 min-w-0 flex items-center gap-2">- <span className="shrink-0 text-xs font-medium text-primary">/{slashCommand.activeSkill.name}</span>- {slashCommand.activeSkill.isGlobal && (- <span className="text-[10px] font-medium text-muted-foreground bg-muted rounded px-1 py-0.5">Global</span>- )}- <span className="text-xs text-muted-foreground truncate">- {slashCommand.activeSkill.description}- </span>- </div>- <button- type="button"- onClick={slashCommand.clearActiveSkill}- className="shrink-0 p-0.5 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"+ <div className="flex items-end gap-2">+ {/* Overflow "+" menu */}+ {!targetConvId && (+ <Popover>+ <PopoverTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className="shrink-0 self-end mb-2.5 size-8 rounded-full text-muted-foreground/60 hover:text-foreground transition-colors duration-200"+ />+ }>- <X className="size-3.5" />- </button>- </div>- )}- {quotedText && (- <div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">- <div className="flex-1 min-w-0 flex items-start gap-2">- <MessageSquareQuote className="size-3.5 shrink-0 mt-0.5 text-muted-foreground" />- <p className="text-xs text-muted-foreground truncate">- {quotedText.slice(0, 120)}{quotedText.length > 120 ? "..." : ""}- </p>- </div>- <button- type="button"- onClick={() => setQuotedText(null)}- className="shrink-0 p-0.5 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"+ <Plus className="size-4" />+ </PopoverTrigger>+ <PopoverContent+ side="top"+ align="start"+ className="w-auto p-1.5 flex flex-col gap-0.5">- <X className="size-3.5" />- </button>- </div>- )}- <MentionPopup- isOpen={mentionPopup.isOpen}- relatedAgents={mentionPopup.relatedAgents}- otherAgents={mentionPopup.otherAgents}- selectedIndex={mentionPopup.selectedIndex}- onSelect={mentionPopup.selectAgent}- anchorPos={mentionPopup.anchorPos}- />- <SlashCommandPopup- isOpen={slashCommand.isOpen}- skills={slashCommand.skills}- selectedIndex={slashCommand.selectedIndex}- onSelect={slashCommand.selectSkill}- anchorPos={slashCommand.anchorPos}- />- <div className="relative">- <div- aria-hidden- className="mention-backdrop absolute inset-0 px-3.5 py-2.5 text-base chat-input-line-height whitespace-pre-wrap wrap-break-word pointer-events-none overflow-y-auto thin-scrollbar"- dangerouslySetInnerHTML={{- __html: input- ? highlightMentions(- input.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),- agents,- )- .replace(/<mention[^>]*>/g, '<span class="mention-highlight">')- .replace(/<\/mention>/g, "</span>")- + (input.endsWith("\n") ? "\n" : "")- : "",- }}- />- <textarea- ref={textareaRef}- value={input}- enterKeyHint="send"- onChange={(e) => {- setInput(e.target.value);- setCaretIndex(e.target.selectionStart);- // Sync backdrop scroll after content change (handles paste/delete resize)- requestAnimationFrame(() => {- const backdrop = e.target.previousElementSibling as HTMLElement | null;- if (backdrop) backdrop.scrollTop = e.target.scrollTop;- });- }}- onKeyDown={handleKeyDown}- onPaste={handlePaste}- onKeyUp={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}- onClick={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}- onSelect={(e) => setCaretIndex((e.target as HTMLTextAreaElement).selectionStart)}- onScroll={(e) => {- const backdrop = (e.target as HTMLTextAreaElement).previousElementSibling;- if (backdrop) backdrop.scrollTop = (e.target as HTMLTextAreaElement).scrollTop;- }}- placeholder={isTaskActive ? "Type a follow-up..." : "Type a message or / for skills..."}- rows={1}- disabled={sending}- className={cn(- "relative field-sizing-content w-full resize-none bg-transparent px-3.5 py-2.5 text-base chat-input-line-height outline-none",- "placeholder:text-muted-foreground disabled:cursor-not-allowed",- "min-h-9.5 max-h-50 thin-scrollbar",- "caret-foreground textarea-text-hidden"- )}- />- </div>-- {/* Pending file pills */}- {pendingFiles.length > 0 && (- <div className="flex flex-wrap gap-1.5 px-3.5 pb-1">- {pendingFiles.map((file, i) => (- <span- key={`${file.name}-${i}`}- className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground"- >- <FileText className="size-3 shrink-0" />- <span className="truncate max-w-30">{file.name}</span>- <span className="text-muted-foreground/60">{formatSize(file.size)}</span>- <button- type="button"- onClick={() => removePendingFile(i)}- className="ml-0.5 rounded-sm p-0.5 hover:bg-muted-foreground/20 transition-colors"- >- <X className="size-3" />- </button>- </span>- ))}- </div>- )}-- <div className="flex items-center justify-between px-2 pb-2 pt-0.5">- <div className="flex items-center gap-1">- {!targetConvId && (<Tooltip>- <TooltipTrigger render={(props) => (- <span {...props} className={cn("inline-flex", props.className)}>- <Button- variant="ghost"- size="icon-sm"- onClick={handleNap}- disabled={napping || !conversation || !currentConvHasMessages || isTaskActive}- className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"+ <TooltipTrigger+ render={(props) => (+ <span+ {...props}+ className={cn("inline-flex", props.className)}>- {napping ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <BedDouble className="size-3.5" />- )}- </Button>- </span>- )} />- <TooltipContent side="top">- {isTaskActive ? "Wait for the task to finish" : currentConvHasMessages ? "Take a nap" : `${agentName} is well-rested and ready to go`}+ <Button+ variant="ghost"+ size="sm"+ onClick={handleNap}+ disabled={+ napping ||+ !conversation ||+ !currentConvHasMessages ||+ isTaskActive+ }+ className="w-full justify-start gap-2 rounded-md text-muted-foreground hover:text-foreground"+ >+ {napping ? (+ <Loader2 className="size-3.5 animate-spin" />+ ) : (+ <BedDouble className="size-3.5" />+ )}+ <span className="text-xs">Nap</span>+ </Button>+ </span>+ )}+ />+ <TooltipContent side="right">+ {isTaskActive+ ? "Wait for the task to finish"+ : currentConvHasMessages+ ? "Take a nap"+ : `${agentName} is well-rested and ready to go`}</TooltipContent></Tooltip>- )}- <Tooltip>- <TooltipTrigger render={- <Button- variant="ghost"- size="icon-sm"- onClick={() => { setArtifactSheetSource("agent"); setArtifactSheetOpen(true); }}- className="relative rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"- />- }>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => {+ setArtifactSheetSource("agent");+ setArtifactSheetOpen(true);+ }}+ className="relative w-full justify-start gap-2 rounded-md text-muted-foreground hover:text-foreground"+ ><Box className="size-3.5" />+ <span className="text-xs">Artifacts</span>{agentArtifacts.length > 0 && (- <span className="absolute -top-0.5 -right-0.5 flex size-3.5 items-center justify-center rounded-full bg-primary text-[9px] font-medium text-primary-foreground">+ <span className="ml-auto flex size-4 items-center justify-center rounded-full bg-primary text-[9px] font-medium text-primary-foreground">{agentArtifacts.length}</span>)}- </TooltipTrigger>- <TooltipContent side="top">Artifacts</TooltipContent>- </Tooltip>- </div>- <div className="flex items-center gap-1">+ </Button>+ </PopoverContent>+ </Popover>+ )}++ {/* Pill container */}+ <div+ className={cn(+ "relative flex-1 min-w-0 flex flex-col rounded-3xl border border-border/50 bg-background/90 transition-[border-radius] duration-200",+ "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50",+ (isMultiLine || quotedText || slashCommand.activeSkill) &&+ "rounded-2xl",+ sending && "opacity-50",+ dragging && "border-ring ring-3 ring-ring/50",+ )}+ onDragEnter={handleDragEnter}+ onDragLeave={handleDragLeave}+ onDragOver={handleDragOver}+ onDrop={handleDrop}+ >+ {dragging && (+ <div+ className={cn(+ "absolute inset-0 z-10 flex items-center justify-center bg-background/80 border-2 border-dashed border-ring pointer-events-none",+ isMultiLine || quotedText || slashCommand.activeSkill+ ? "rounded-2xl"+ : "rounded-3xl",+ )}+ >+ <p className="text-sm text-muted-foreground font-medium">+ Drop files here+ </p>+ </div>+ )}+ {slashCommand.activeSkill && (+ <div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">+ <div className="flex-1 min-w-0 flex items-center gap-2">+ <span className="shrink-0 text-xs font-medium text-primary">+ /{slashCommand.activeSkill.name}+ </span>+ {slashCommand.activeSkill.isGlobal && (+ <span className="text-[10px] font-medium text-muted-foreground bg-muted rounded px-1 py-0.5">+ Global+ </span>+ )}+ <span className="text-xs text-muted-foreground truncate">+ {slashCommand.activeSkill.description}+ </span>+ </div>+ <button+ type="button"+ onClick={slashCommand.clearActiveSkill}+ className="shrink-0 p-0.5 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"+ >+ <X className="size-3.5" />+ </button>+ </div>+ )}+ {quotedText && (+ <div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">+ <div className="flex-1 min-w-0 flex items-start gap-2">+ <MessageSquareQuote className="size-3.5 shrink-0 mt-0.5 text-muted-foreground" />+ <p className="text-xs text-muted-foreground truncate">+ {quotedText.slice(0, 120)}+ {quotedText.length > 120 ? "..." : ""}+ </p>+ </div>+ <button+ type="button"+ onClick={() => setQuotedText(null)}+ className="shrink-0 p-0.5 rounded-sm hover:bg-muted-foreground/20 transition-colors text-muted-foreground"+ >+ <X className="size-3.5" />+ </button>+ </div>+ )}+ <SlashCommandPopup+ isOpen={slashCommand.isOpen}+ skills={slashCommand.skills}+ selectedIndex={slashCommand.selectedIndex}+ onSelect={slashCommand.selectSkill}+ anchorPos={slashCommand.anchorPos}+ />+ {/* Pending file pills — above the input text, never disturbs the buttons */}+ {pendingFiles.length > 0 && (+ <div className="flex flex-wrap gap-1.5 px-3.5 pt-3 pb-0.5">+ {pendingFiles.map((file, i) => (+ <span+ key={`${file.name}-${i}`}+ className="inline-flex items-center gap-1.5 rounded-md bg-muted px-2 py-1 text-xs text-muted-foreground"+ >+ <FileText className="size-3 shrink-0" />+ <span className="truncate max-w-30">{file.name}</span>+ <span className="text-muted-foreground/60">+ {formatSize(file.size)}+ </span>+ <button+ type="button"+ onClick={() => removePendingFile(i)}+ className="ml-0.5 rounded-sm p-0.5 hover:bg-muted-foreground/20 transition-colors"+ >+ <X className="size-3" />+ </button>+ </span>+ ))}+ </div>+ )}+ {/* Composer + absolutely-positioned buttons */}+ <div className="relative"><inputref={fileInputRef}type="file"@@ -2162,31 +2913,62 @@ export function AgentChatView({className="hidden"onChange={handleFileSelect}/>+ {/* Padding wrapper: vertical breathing room lives here so it+ survives editor scrolling — the .tiptap element owns no padding. */}+ <div className="px-13 py-3">+ <ChatComposer+ ref={composerRef}+ value={input}+ onChange={setInput}+ onEditorState={(text, caret) => {+ setEditorText(text);+ setCaretIndex(caret);+ }}+ onSend={handleSend}+ placeholder={+ isTaskActive ? "Type a follow-up..." : "Type a task..."+ }+ disabled={sending}+ onMultiLineChange={setIsMultiLine}+ onFiles={addPendingFiles}+ agents={otherAgents}+ agentLinks={agentLinks}+ currentAgentId={agentId}+ slashIsOpen={slashCommand.isOpen}+ onSlashKeyDown={slashCommand.handleSlashKeyDown}+ />+ </div>+ {/* Attach button — fixed bottom-left */}<Tooltip>- <TooltipTrigger render={- <Button- variant="ghost"- size="icon-sm"- onPointerDown={(e) => e.preventDefault()}- onClick={() => fileInputRef.current?.click()}- disabled={sending}- className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"- />- }>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ onPointerDown={(e) => e.preventDefault()}+ onClick={() => fileInputRef.current?.click()}+ disabled={sending}+ className="absolute left-2 bottom-2 size-8 rounded-full text-muted-foreground/60 hover:text-foreground transition-colors duration-200"+ />+ }+ ><Paperclip className="size-3.5" /></TooltipTrigger><TooltipContent side="top">Attach files</TooltipContent></Tooltip>+ {/* Send / Stop button — fixed bottom-right */}{isTaskActive && !input.trim() && !sending ? (<Tooltip>- <TooltipTrigger render={- <Button- size="icon-sm"- onClick={handleStop}- disabled={cancelling}- className="rounded-lg bg-red-500/10 text-red-500 hover:bg-red-500/20 transition-colors duration-200"- />- }>+ <TooltipTrigger+ render={+ <Button+ size="icon-sm"+ onClick={handleStop}+ disabled={cancelling}+ className="absolute right-2 bottom-2 size-8 rounded-full bg-red-500/10 text-red-500 hover:bg-red-500/20 transition-colors duration-200"+ />+ }+ >{cancelling ? (<Loader2 className="size-3.5 animate-spin" />) : (@@ -2197,17 +2979,19 @@ export function AgentChatView({</Tooltip>) : (<Tooltip>- <TooltipTrigger render={- <Button- size="icon-sm"- onClick={handleSend}- disabled={!input.trim() || sending}- className={cn(- "rounded-lg transition-opacity duration-200",- !input.trim() && "opacity-40"- )}- />- }>+ <TooltipTrigger+ render={+ <Button+ size="icon-sm"+ onClick={handleSend}+ disabled={!input.trim() || sending}+ className={cn(+ "absolute right-2 bottom-2 size-8 rounded-full bg-primary text-primary-foreground transition-opacity duration-200",+ !input.trim() && "opacity-30",+ )}+ />+ }+ >{sending ? (<Loader2 className="size-3.5 animate-spin" />) : (@@ -2227,7 +3011,11 @@ export function AgentChatView({open={artifactSheetOpen}onOpenChange={(v) => {setArtifactSheetOpen(v);- if (!v) setTimeout(() => { setSelectedArtifact(null); setArtifactSheetSource(null); }, 300);+ if (!v)+ setTimeout(() => {+ setSelectedArtifact(null);+ setArtifactSheetSource(null);+ }, 300);}}artifacts={artifactSheetArtifacts}workspaceId={workspaceId}@@ -2261,20 +3049,25 @@ export function AgentChatView({open={issueSheetOpen}onOpenChange={(v) => {setIssueSheetOpen(v);- if (!v) setTimeout(() => {- setSelectedIssueId(null);- setIssueDetail(null);- setIssueActiveTask(null);- }, 300);+ if (!v)+ setTimeout(() => {+ setSelectedIssueId(null);+ setIssueDetail(null);+ setIssueActiveTask(null);+ }, 300);}}agents={agents}issue={issueDetail?.issue ?? null}- detail={issueDetail ? {- messages: issueDetail.messages,- comments: issueDetail.comments,- artifacts: issueDetail.artifacts,- traceId: issueDetail.issue.trace_id,- } : null}+ detail={+ issueDetail+ ? {+ messages: issueDetail.messages,+ comments: issueDetail.comments,+ artifacts: issueDetail.artifacts,+ traceId: issueDetail.issue.trace_id,+ }+ : null+ }detailLoading={issueDetailLoading}activeTask={issueActiveTask}traceTasks={issueTraceTasks}@@ -2283,17 +3076,41 @@ export function AgentChatView({onUpdate={async (issueId, patch) => {try {const updated = await updateIssue(workspaceId, issueId, patch);- setIssueDetail(prev => prev && prev.issue.id === issueId ? { ...prev, issue: { ...prev.issue, ...patch, updated_at: updated.updated_at } } : prev);+ setIssueDetail((prev) =>+ prev && prev.issue.id === issueId+ ? {+ ...prev,+ issue: {+ ...prev.issue,+ ...patch,+ updated_at: updated.updated_at,+ },+ }+ : prev,+ );} catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to update issue");+ toast.error(+ err instanceof Error ? err.message : "Failed to update issue",+ );}}}onStatusChange={async (issueId, status) => {try {- await updateIssue(workspaceId, issueId, { status: status as Issue["status"] });- setIssueDetail(prev => prev && prev.issue.id === issueId ? { ...prev, issue: { ...prev.issue, status: status as Issue["status"] } } : prev);+ await updateIssue(workspaceId, issueId, {+ status: status as Issue["status"],+ });+ setIssueDetail((prev) =>+ prev && prev.issue.id === issueId+ ? {+ ...prev,+ issue: { ...prev.issue, status: status as Issue["status"] },+ }+ : prev,+ );} catch (err) {- toast.error(err instanceof Error ? err.message : "Failed to update status");+ toast.error(+ err instanceof Error ? err.message : "Failed to update status",+ );}}}onCommented={() => {diff --git a/src/web/src/components/agent-chat/chat-composer.tsx b/src/web/src/components/agent-chat/chat-composer.tsxnew file mode 100644index 000000000..16d09549d--- /dev/null+++ b/src/web/src/components/agent-chat/chat-composer.tsx@@ -0,0 +1,435 @@+"use client";++import {+ forwardRef,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+} from "react";+import { useEditor, EditorContent } from "@tiptap/react";+import StarterKit from "@tiptap/starter-kit";+import Placeholder from "@tiptap/extension-placeholder";+import { Markdown } from "@tiptap/markdown";+import { createPortal } from "react-dom";+import { cn } from "@/lib/utils";+import { rankMentionAgents } from "@/lib/mention-agents";+import { buildChatMentionExtension } from "@/lib/chat-mention-extension";+import { decodeChatEntities } from "@/lib/chat-markdown";+import type { Agent, AgentLink } from "@alook/shared";+import type { PopupKeyEvent } from "@/hooks/use-slash-command";++/**+ * Imperative handle the parent (agent-chat-view) drives. The parent keeps+ * owning send / banners / persistence / slash-command state; the composer only+ * owns the TipTap editor and surfaces just enough to anchor the slash popup.+ */+export interface ChatComposerHandle {+ focus: () => void;+ clear: () => void;+ isEmpty: () => boolean;+ /** Viewport coords for a plain-text caret index — used to anchor the slash popup. */+ coordsAtTextIndex: (index: number) => { top: number; left: number } | null;+}++interface ChatComposerProps {+ /** Markdown string — the controlled source of truth (parent's `input`). */+ value: string;+ onChange: (markdown: string) => void;+ /** Reports the editor's plain text + caret index so the parent can drive slash. */+ onEditorState: (plainText: string, caretIndex: number) => void;+ /** Enter-to-send (only fires in a top-level paragraph, no popup open). */+ onSend: () => void;+ placeholder?: string;+ disabled?: boolean;+ /** Drives the rounded-3xl ↔ rounded-2xl pill switch. */+ onMultiLineChange?: (multiline: boolean) => void;+ /** Files extracted from paste/drop — parent validates + stages them. */+ onFiles?: (files: File[]) => void;++ // Mentions+ agents: Agent[];+ agentLinks: AgentLink[];+ currentAgentId: string;++ // Slash command (state owned by the parent's useSlashCommand)+ slashIsOpen: boolean;+ onSlashKeyDown: (e: PopupKeyEvent) => boolean;+}++// ── Mention suggestion popup (self-contained, mirrors markdown-editor.tsx) ──++type MentionSuggestionProps = {+ items: Agent[];+ command: (props: { id: string; label: string }) => void;+ clientRect?: (() => DOMRect | null) | null;+};++interface MentionPopupState {+ items: Agent[];+ selectedIndex: number;+ command: ((props: { id: string; label: string }) => void) | null;+ rect: DOMRect | null;+}++const EMPTY_MENTION_STATE: MentionPopupState = {+ items: [],+ selectedIndex: 0,+ command: null,+ rect: null,+};++function MentionList({ state }: { state: MentionPopupState }) {+ const listRef = useRef<HTMLDivElement>(null);+ const { items, selectedIndex, command, rect } = state;++ useEffect(() => {+ if (!listRef.current) return;+ const el = listRef.current.children[selectedIndex] as HTMLElement | undefined;+ el?.scrollIntoView({ block: "nearest" });+ }, [selectedIndex]);++ if (!rect || items.length === 0 || !command) return null;++ // Popup is w-64 (256px). Clamp left so it never overflows the right edge (mobile).+ const POPUP_WIDTH = 256;+ const VIEWPORT_MARGIN = 8;+ const maxLeft = typeof window !== "undefined"+ ? Math.max(VIEWPORT_MARGIN, window.innerWidth - POPUP_WIDTH - VIEWPORT_MARGIN)+ : rect.left;+ const clampedLeft = Math.min(rect.left, maxLeft);++ return createPortal(+ <div+ className="fixed z-100 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md"+ style={{ top: rect.top - 4, left: clampedLeft, transform: "translateY(-100%)" }}+ >+ <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">+ {items.map((agent, i) => (+ <button+ key={agent.id}+ type="button"+ className={cn(+ "flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm transition-colors",+ i === selectedIndex ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",+ )}+ onMouseDown={(e) => {+ e.preventDefault();+ command({ id: agent.id, label: agent.name });+ }}+ >+ <span className="truncate font-medium">{agent.name}</span>+ {agent.email_handle && (+ <span className="truncate text-xs text-muted-foreground">+ {agent.email_handle}@alook.ai+ </span>+ )}+ </button>+ ))}+ </div>+ </div>,+ document.body,+ );+}++export const ChatComposer = forwardRef<ChatComposerHandle, ChatComposerProps>(+ function ChatComposer(+ {+ value,+ onChange,+ onEditorState,+ onSend,+ placeholder,+ disabled,+ onMultiLineChange,+ onFiles,+ agents,+ agentLinks,+ currentAgentId,+ slashIsOpen,+ onSlashKeyDown,+ },+ ref,+ ) {+ const [mentionPopup, setMentionPopup] = useState<MentionPopupState>(EMPTY_MENTION_STATE);+ const mentionPopupRef = useRef(mentionPopup);+ useEffect(() => {+ mentionPopupRef.current = mentionPopup;+ }, [mentionPopup]);++ // The editor is built once, so anything its callbacks read must be a ref.+ const agentsRef = useRef(agents);+ const agentLinksRef = useRef(agentLinks);+ const currentAgentIdRef = useRef(currentAgentId);+ const onSendRef = useRef(onSend);+ const onEditorStateRef = useRef(onEditorState);+ const onChangeRef = useRef(onChange);+ const onFilesRef = useRef(onFiles);+ const slashIsOpenRef = useRef(slashIsOpen);+ const onSlashKeyDownRef = useRef(onSlashKeyDown);+ useEffect(() => { agentsRef.current = agents; }, [agents]);+ useEffect(() => { agentLinksRef.current = agentLinks; }, [agentLinks]);+ useEffect(() => { currentAgentIdRef.current = currentAgentId; }, [currentAgentId]);+ useEffect(() => { onSendRef.current = onSend; }, [onSend]);+ useEffect(() => { onEditorStateRef.current = onEditorState; }, [onEditorState]);+ useEffect(() => { onChangeRef.current = onChange; }, [onChange]);+ useEffect(() => { onFilesRef.current = onFiles; }, [onFiles]);+ useEffect(() => { slashIsOpenRef.current = slashIsOpen; }, [slashIsOpen]);+ useEffect(() => { onSlashKeyDownRef.current = onSlashKeyDown; }, [onSlashKeyDown]);++ // Report plain text + caret to the parent (it drives the slash-command+ // popup). NOTE: `selection.from - 1` only equals the true plain-text index+ // in a single-paragraph doc — it diverges across block boundaries. The only+ // consumer (slash commands, which trigger ONLY at the start of input) is in+ // a top-level paragraph, so the mapping holds there. Don't trust this index+ // for multi-block positions without revisiting.+ const reportState = (editor: NonNullable<ReturnType<typeof useEditor>>) => {+ onEditorStateRef.current(editor.getText(), editor.state.selection.from - 1);+ };++ // The mention extension is built once (refs read inside its callbacks fire+ // at suggestion-time, not render-time). Keeping it in a lazy state init+ // also stops it being rebuilt on every render. The .current reads below are+ // all inside suggestion callbacks invoked at runtime, never during render.+ // eslint-disable-next-line react-hooks/refs -- refs read in runtime callbacks, not render+ const [mentionExtension] = useState(() =>+ buildChatMentionExtension().configure({+ HTMLAttributes: { class: "mention-highlight" },+ renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`,+ suggestion: {+ char: "@",+ items: ({ query }: { query: string }) =>+ rankMentionAgents(+ agentsRef.current,+ agentLinksRef.current,+ currentAgentIdRef.current,+ query,+ ),+ render: () => ({+ onStart: (props: MentionSuggestionProps) => {+ setMentionPopup({+ items: props.items ?? [],+ selectedIndex: 0,+ command: props.command,+ rect: props.clientRect?.() ?? null,+ });+ },+ onUpdate: (props: MentionSuggestionProps) => {+ setMentionPopup((cur) => ({+ items: props.items ?? [],+ selectedIndex:+ cur.selectedIndex < (props.items?.length ?? 0) ? cur.selectedIndex : 0,+ command: props.command,+ rect: props.clientRect?.() ?? null,+ }));+ },+ onKeyDown: ({ event }: { event: KeyboardEvent }) => {+ // IME guard: while composing (CJK), Enter confirms the+ // composition — it must not select a mention. Mirrors the Enter+ // guards in the slash hook and the send path.+ if (event.isComposing) return false;+ const cur = mentionPopupRef.current;+ if (cur.items.length === 0) return false;+ if (event.key === "ArrowDown") {+ event.preventDefault();+ setMentionPopup((s) => ({+ ...s,+ selectedIndex: (s.selectedIndex + 1) % s.items.length,+ }));+ return true;+ }+ if (event.key === "ArrowUp") {+ event.preventDefault();+ setMentionPopup((s) => ({+ ...s,+ selectedIndex: (s.selectedIndex - 1 + s.items.length) % s.items.length,+ }));+ return true;+ }+ if (event.key === "Enter") {+ event.preventDefault();+ const agent = cur.items[cur.selectedIndex];+ if (agent && cur.command) cur.command({ id: agent.id, label: agent.name });+ setMentionPopup(EMPTY_MENTION_STATE);+ return true;+ }+ if (event.key === "Escape") {+ setMentionPopup(EMPTY_MENTION_STATE);+ return true;+ }+ return false;+ },+ onExit: () => setMentionPopup(EMPTY_MENTION_STATE),+ }),+ },+ }),+ );++ const editor = useEditor({+ immediatelyRender: false,+ content: value || undefined,+ contentType: "markdown",+ editable: !disabled,+ extensions: [+ StarterKit.configure({+ heading: false,+ blockquote: false,+ codeBlock: false,+ horizontalRule: false,+ bold: false,+ italic: false,+ strike: false,+ code: false,+ }),+ Placeholder.configure({ placeholder: placeholder ?? "" }),+ Markdown,+ mentionExtension,+ ],+ editorProps: {+ attributes: {+ class: "outline-none",+ enterkeyhint: "send",+ },+ handleKeyDown: (_view, event) => {+ // Precedence: mention suggestion > slash popup > Enter-to-send.+ //+ // editorProps.handleKeyDown runs BEFORE plugin keymaps in+ // ProseMirror, so the @tiptap/suggestion mention plugin does NOT get+ // first crack at Enter — we must explicitly bail here while the+ // mention popup is open, or Enter would send instead of selecting the+ // highlighted agent. (Arrow/Esc fall through fine; only Enter clashes.)+ const mentionOpen =+ mentionPopupRef.current.items.length > 0 && mentionPopupRef.current.command !== null;+ if (mentionOpen) return false;++ if (+ slashIsOpenRef.current &&+ onSlashKeyDownRef.current({+ key: event.key,+ isComposing: event.isComposing,+ preventDefault: () => event.preventDefault(),+ })+ ) {+ return true;+ }++ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {+ const inList =+ editor?.isActive("bulletList") ||+ editor?.isActive("orderedList") ||+ editor?.isActive("listItem");+ if (!inList && !slashIsOpenRef.current) {+ event.preventDefault();+ onSendRef.current();+ return true;+ }+ }+ return false;+ },+ handlePaste: (_view, event) => {+ const items = event.clipboardData?.items;+ if (!items) return false;+ const files: File[] = [];+ for (let i = 0; i < items.length; i++) {+ if (items[i].kind === "file") {+ const f = items[i].getAsFile();+ if (f) files.push(f);+ }+ }+ if (files.length === 0) return false; // let plain text paste normally+ event.preventDefault();+ onFilesRef.current?.(files);+ return true;+ },+ handleDrop: (_view, event) => {+ const dropped = (event as DragEvent).dataTransfer?.files;+ if (!dropped || dropped.length === 0) return false; // bubble to container+ event.preventDefault();+ onFilesRef.current?.(Array.from(dropped));+ return true;+ },+ },+ onUpdate: ({ editor }) => {+ onChangeRef.current(decodeChatEntities(editor.getMarkdown()));+ reportState(editor);+ },+ onSelectionUpdate: ({ editor }) => {+ reportState(editor);+ },+ });++ // Keep editable in sync with disabled.+ useEffect(() => {+ editor?.setEditable(!disabled);+ }, [editor, disabled]);++ // Controlled value: push external markdown changes (draft restore /+ // conversation switch / clear-after-send) into the editor.+ // contentType:"markdown" is required or lists silently break.+ // emitUpdate:false avoids a feedback loop.+ useEffect(() => {+ if (!editor) return;+ const incoming = (value || "").trim();+ // Decode so this matches the (decoded) markdown the parent stored via+ // onChange — otherwise text with < > & always mismatches and we'd reset+ // content (and the caret) on every keystroke.+ const current = decodeChatEntities(editor.getMarkdown() || "").trim();+ if (incoming === current) return;+ // Empty incoming → clearContent(). setContent("", {contentType:"markdown"})+ // does NOT reliably empty the doc (parsing an empty markdown string can+ // leave the prior content), which left the just-sent text in the input.+ if (!incoming) {+ editor.commands.clearContent();+ } else {+ editor.commands.setContent(value || "", {+ emitUpdate: false,+ contentType: "markdown",+ });+ }+ onEditorStateRef.current(editor.getText(), editor.state.selection.from - 1);+ }, [value, editor]);++ // Multi-line detection drives the pill rounding.+ const contentRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ if (!editor || !onMultiLineChange) return;+ const el = contentRef.current?.querySelector(".ProseMirror") as HTMLElement | null;+ if (!el) return;+ const check = () => onMultiLineChange(el.scrollHeight > 32);+ check();+ const observer = new ResizeObserver(check);+ observer.observe(el);+ return () => observer.disconnect();+ }, [editor, onMultiLineChange]);++ useImperativeHandle(+ ref,+ () => ({+ focus: () => editor?.commands.focus(),+ clear: () => editor?.commands.clearContent(),+ isEmpty: () => editor?.isEmpty ?? true,+ coordsAtTextIndex: (index: number) => {+ if (!editor) return null;+ try {+ // +1: plain-text index is 0-based; PM positions start at 1.+ const coords = editor.view.coordsAtPos(index + 1);+ return { top: coords.top, left: coords.left };+ } catch {+ return null;+ }+ },+ }),+ [editor],+ );++ return (+ <div ref={contentRef} className="chat-composer relative">+ <EditorContent+ editor={editor}+ className="max-h-44 overflow-y-auto thin-scrollbar pr-2 text-base chat-input-line-height"+ />+ <MentionList state={mentionPopup} />+ </div>+ );+ },+);diff --git a/src/web/src/components/agent-chat/fast-load-gate.test.ts b/src/web/src/components/agent-chat/fast-load-gate.test.tsnew file mode 100644index 000000000..597a7d328--- /dev/null+++ b/src/web/src/components/agent-chat/fast-load-gate.test.ts@@ -0,0 +1,97 @@+import { describe, it, expect } from "vitest";+import {+ createFastLoadGateState,+ fastLoadKey,+ shouldSkipFastLoad,+ markFastLoadCompleted,+} from "./fast-load-gate";++const ID = { workspaceId: "w1", agentId: "a1", targetConvId: "c1", scrollToTaskId: null };++describe("fastLoadKey", () => {+ it("returns null on the slow path (no targetConvId)", () => {+ expect(fastLoadKey({ ...ID, targetConvId: null })).toBeNull();+ expect(fastLoadKey({ ...ID, targetConvId: undefined })).toBeNull();+ });++ it("excludes channel — same identity always yields the same key", () => {+ const k1 = fastLoadKey(ID);+ const k2 = fastLoadKey(ID);+ expect(k1).toBe(k2);+ expect(k1).toContain("w1");+ expect(k1).toContain("a1");+ expect(k1).toContain("c1");+ });++ it("changes when agent / conv / scroll target change", () => {+ const base = fastLoadKey(ID);+ expect(fastLoadKey({ ...ID, agentId: "a2" })).not.toBe(base);+ expect(fastLoadKey({ ...ID, targetConvId: "c2" })).not.toBe(base);+ expect(fastLoadKey({ ...ID, scrollToTaskId: "t9" })).not.toBe(base);+ });+});++describe("fast-load gate lifecycle", () => {+ it("TODO 6: same key re-fire AFTER completion is skipped (no flash / no re-fetch)", () => {+ const state = createFastLoadGateState();+ const key = fastLoadKey(ID)!;++ // Run #1 starts then completes.+ expect(shouldSkipFastLoad(key, state)).toBe(false);+ markFastLoadCompleted(key, state);++ // Re-fire from a pure channel-dep change → same key, already completed → skip.+ expect(shouldSkipFastLoad(key, state)).toBe(true);+ });++ it("REGRESSION: cancelled-mid-flight run does NOT strand the skeleton — recovery run proceeds", () => {+ const state = createFastLoadGateState();+ const key = fastLoadKey(ID)!;++ // Run #1 starts (does NOT complete — it gets cancelled mid-load, so+ // markFastLoadCompleted is never called for it).+ expect(shouldSkipFastLoad(key, state)).toBe(false);++ // Run #2 (recovery) fires with the SAME key while #1 is still in flight.+ // It must NOT be skipped — otherwise nobody clears messagesLoading.+ expect(shouldSkipFastLoad(key, state)).toBe(false);++ // Run #2 completes and records the marker.+ markFastLoadCompleted(key, state);++ // Now a later pure channel re-fire is correctly deduped.+ expect(shouldSkipFastLoad(key, state)).toBe(true);+ });++ it("a cancelled run that already marked nothing leaves completedKey null", () => {+ const state = createFastLoadGateState();+ const key = fastLoadKey(ID)!;+ shouldSkipFastLoad(key, state); // start, clears marker+ // (run cancelled — markFastLoadCompleted NOT called)+ expect(state.completedKey).toBeNull();+ });++ it("starting a load clears a stale completed marker (different identity)", () => {+ const state = createFastLoadGateState();+ const k1 = fastLoadKey(ID)!;+ const k2 = fastLoadKey({ ...ID, targetConvId: "c2" })!;++ shouldSkipFastLoad(k1, state);+ markFastLoadCompleted(k1, state);+ expect(state.completedKey).toBe(k1);++ // Switching to a different conversation starts a new load → marker cleared+ // until the new run finishes (no false dedup across identities).+ expect(shouldSkipFastLoad(k2, state)).toBe(false);+ expect(state.completedKey).toBeNull();+ });++ it("slow path (null key) never skips and never records a marker", () => {+ const state = createFastLoadGateState();+ expect(shouldSkipFastLoad(null, state)).toBe(false);+ markFastLoadCompleted(null, state);+ expect(state.completedKey).toBeNull();+ // A subsequent null run also proceeds.+ expect(shouldSkipFastLoad(null, state)).toBe(false);+ });+});diff --git a/src/web/src/components/agent-chat/fast-load-gate.ts b/src/web/src/components/agent-chat/fast-load-gate.tsnew file mode 100644index 000000000..1bab9af5d--- /dev/null+++ b/src/web/src/components/agent-chat/fast-load-gate.ts@@ -0,0 +1,64 @@+/**+ * Dedup gate for the fast-path chat load (TODO 6 / stuck-skeleton regression fix).+ *+ * The chat load effect re-fires on channel-dep changes (activeChannel /+ * channelLoading). For a known conversation (fast path) those deps are+ * irrelevant, so a re-fire with the same identity should be skipped to avoid a+ * skeleton flash + re-fetch. BUT skipping must never strand the UI on the+ * loading skeleton: if the previous run for that identity was cancelled before+ * it finished, the re-fire is a *recovery* run and MUST proceed.+ *+ * The invariant: a fast-load key is recorded as "completed" only AFTER its+ * load() resolves (not when it starts). So:+ * - same key, prior run completed → skip (steady-state channel change)+ * - same key, prior run cancelled → do NOT skip (recovery; clears skeleton)+ *+ * This module is the pure decision logic, extracted so the lifecycle can be+ * unit-tested without rendering the component (the web test env is node-only,+ * no jsdom/RTL).+ */++export interface FastLoadGateState {+ /** The fast-load key whose load() has fully COMPLETED, or null. */+ completedKey: string | null;+}++export function createFastLoadGateState(): FastLoadGateState {+ return { completedKey: null };+}++/**+ * Build the fast-path key for a load identity, or null for the slow path+ * (no targetConvId). Channel is intentionally excluded — channel changes must+ * not change the key.+ */+export function fastLoadKey(opts: {+ workspaceId: string;+ agentId: string;+ targetConvId: string | null | undefined;+ scrollToTaskId: string | null | undefined;+}): string | null {+ if (!opts.targetConvId) return null;+ return `${opts.workspaceId}::${opts.agentId}::${opts.targetConvId}::${opts.scrollToTaskId ?? ""}`;+}++/**+ * Decide whether this effect run should skip starting a load. Returns true only+ * when a load for the same fast key has already completed. Mutates state to+ * clear the completed marker when a run is about to start (so an in-flight run+ * leaves no "done" marker if it gets cancelled).+ */+export function shouldSkipFastLoad(key: string | null, state: FastLoadGateState): boolean {+ if (key && state.completedKey === key) return true;+ // A new / recovery run is starting — until it finishes, nothing is "completed".+ state.completedKey = null;+ return false;+}++/**+ * Record that a load fully completed (call from the finally block when the run+ * was NOT superseded). A cancelled run must not call this.+ */+export function markFastLoadCompleted(key: string | null, state: FastLoadGateState): void {+ if (key) state.completedKey = key;+}diff --git a/src/web/src/components/agent-chat/mention-popup.tsx b/src/web/src/components/agent-chat/mention-popup.tsxdeleted file mode 100644index 4253cfae7..000000000--- a/src/web/src/components/agent-chat/mention-popup.tsx+++ /dev/null@@ -1,93 +0,0 @@-import React, { useRef, useEffect } from "react"-import type { Agent } from "@alook/shared"-import { cn } from "@/lib/utils"--interface MentionPopupProps {- isOpen: boolean- relatedAgents: Agent[]- otherAgents: Agent[]- selectedIndex: number- onSelect: (agent: Agent) => void- anchorPos: { top: number; left: number }-}--function AgentRow({- agent,- isSelected,- onSelect,-}: {- agent: Agent- isSelected: boolean- onSelect: (agent: Agent) => void-}) {- return (- <button- type="button"- data-mention-item- className={cn(- "flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm transition-colors",- isSelected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50",- )}- onMouseDown={(e) => {- e.preventDefault()- onSelect(agent)- }}- >- <span className="truncate font-medium">{agent.name}</span>- {agent.email_handle && (- <span className="truncate text-xs text-muted-foreground">- {agent.email_handle}@alook.ai- </span>- )}- </button>- )-}--export function MentionPopup({ isOpen, relatedAgents, otherAgents, selectedIndex, onSelect, anchorPos }: MentionPopupProps) {- const listRef = useRef<HTMLDivElement>(null)-- useEffect(() => {- if (!listRef.current) return- const items = listRef.current.querySelectorAll("[data-mention-item]")- const selected = items[selectedIndex] as HTMLElement | undefined- selected?.scrollIntoView({ block: "nearest" })- }, [selectedIndex])-- const totalCount = relatedAgents.length + otherAgents.length- if (!isOpen || totalCount === 0) return null-- const showDivider = relatedAgents.length > 0 && otherAgents.length > 0-- return (- <div- className="absolute z-50 w-64 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"- style={{- top: anchorPos.top - 4,- left: anchorPos.left,- transform: "translateY(-100%)",- }}- >- <div ref={listRef} className="max-h-50 overflow-y-auto py-1 thin-scrollbar">- {relatedAgents.map((agent, i) => (- <AgentRow- key={agent.id}- agent={agent}- isSelected={i === selectedIndex}- onSelect={onSelect}- />- ))}- {showDivider && (- <div className="mx-3 my-1 border-t border-border" />- )}- {otherAgents.map((agent, i) => (- <AgentRow- key={agent.id}- agent={agent}- isSelected={relatedAgents.length + i === selectedIndex}- onSelect={onSelect}- />- ))}- </div>- </div>- )-}diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsxindex 6c534e438..14a4c0cd0 100644--- a/src/web/src/components/agent-chat/message-list.tsx+++ b/src/web/src/components/agent-chat/message-list.tsx@@ -10,7 +10,7 @@ import { TaskStream } from "@/components/task-stream";import { HistoricalTaskThinking } from "@/components/agent-chat/historical-task-thinking";import { FileText, Calendar, CircleDot, Mail, Flag, Copy, Check } from "lucide-react";-import { getEventIconType } from "@/components/agent-chat/agent-chat-view";+import { getEventIconType, type GroupPosition } from "@/components/agent-chat/agent-chat-view";import { toast } from "sonner";import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";@@ -38,6 +38,7 @@ export interface MessageItemProps {mentionComponents: Record<string, React.ComponentType<Record<string, unknown> & { children?: React.ReactNode }>>;isFlagged?: boolean;onToggleFlag?: (messageId: string) => void;+ groupPosition?: GroupPosition;}function EventMessageIcon({ content, conversationType }: { content: string; conversationType?: string | null }) {@@ -106,6 +107,13 @@ function PendingFileChips({);}+const USER_BUBBLE_RADIUS: Record<GroupPosition, string> = {+ solo: "rounded-2xl",+ first: "rounded-tl-2xl rounded-tr-2xl rounded-bl-2xl rounded-br-md",+ middle: "rounded-tl-2xl rounded-tr-md rounded-bl-2xl rounded-br-md",+ last: "rounded-tl-2xl rounded-tr-md rounded-bl-2xl rounded-br-2xl",+};+export const MessageItem = memo(function MessageItem({msg,agents,@@ -127,6 +135,7 @@ export const MessageItem = memo(function MessageItem({mentionComponents,isFlagged,onToggleFlag,+ groupPosition = "solo",}: MessageItemProps) {const { copy, copied } = useCopyToClipboard();@@ -216,10 +225,11 @@ export const MessageItem = memo(function MessageItem({return (<div className="flex justify-end" data-message-id={msg.id} {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}><div className={cn(- "max-w-[80%] rounded-lg px-4 py-2 bg-primary text-primary-foreground text-base relative",+ "max-w-[80%] px-4 py-2 bg-primary text-primary-foreground text-base relative",+ USER_BUBBLE_RADIUS[groupPosition],)}>{awaitingRun && (- <div className="absolute inset-0 rounded-lg animate-pulse pointer-events-none" style={{ boxShadow: "0 0 0 2px var(--bubble-glow)" }} />+ <div className={cn("absolute inset-0 animate-pulse pointer-events-none", USER_BUBBLE_RADIUS[groupPosition])} style={{ boxShadow: "0 0 0 2px var(--bubble-glow)" }} />)}{skillName && (<span className="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium bg-primary-foreground/15 text-primary-foreground mb-1">diff --git a/src/web/src/components/agent-chat/slash-command-popup.tsx b/src/web/src/components/agent-chat/slash-command-popup.tsxindex dbe4796d6..8a7d833de 100644--- a/src/web/src/components/agent-chat/slash-command-popup.tsx+++ b/src/web/src/components/agent-chat/slash-command-popup.tsx@@ -61,12 +61,20 @@ export function SlashCommandPopup({ isOpen, skills, selectedIndex, onSelect, ancif (!isOpen || skills.length === 0) return null+ // Popup is w-70 (280px). Clamp left so it never overflows the right edge (mobile).+ const POPUP_WIDTH = 280+ const VIEWPORT_MARGIN = 8+ const maxLeft = typeof window !== "undefined"+ ? Math.max(VIEWPORT_MARGIN, window.innerWidth - POPUP_WIDTH - VIEWPORT_MARGIN)+ : anchorPos.left+ const clampedLeft = Math.min(anchorPos.left, maxLeft)+return (<div- className="absolute z-50 w-70 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"+ className="fixed z-100 w-70 rounded-lg border border-border bg-popover text-popover-foreground shadow-md transition-opacity duration-150"style={{top: anchorPos.top - 4,- left: anchorPos.left,+ left: clampedLeft,transform: "translateY(-100%)",}}>diff --git a/src/web/src/components/canvas/agent-chat-sheet.tsx b/src/web/src/components/canvas/agent-chat-sheet.tsxindex 84ded5250..63ca41ca7 100644--- a/src/web/src/components/canvas/agent-chat-sheet.tsx+++ b/src/web/src/components/canvas/agent-chat-sheet.tsx@@ -23,6 +23,12 @@ import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltipinterface AgentChatSheetProps {open: boolean;onOpenChange: (open: boolean) => void;+ /**+ * Raw agent id — known before the resolved `agent` object. The chat body+ * mounts on this so it paints from cache without waiting for the agents array+ * to load (Part 2-b). The `agent` object is only used for the header.+ */+ agentId: string | null;agent: Agent | null;targetConvId?: string | null;scrollToTaskId?: string | null;@@ -33,7 +39,7 @@ const MIN_WIDTH = 320;const MAX_WIDTH_RATIO = 0.8;const DEFAULT_WIDTH = 480;-export function AgentChatSheet({ open, onOpenChange, agent, targetConvId, scrollToTaskId, scrollToMessageId }: AgentChatSheetProps) {+export function AgentChatSheet({ open, onOpenChange, agentId, agent, targetConvId, scrollToTaskId, scrollToMessageId }: AgentChatSheetProps) {const { runtimes, activeTaskCounts } = useAgentContext();const { slug } = useWorkspace();const router = useRouter();@@ -55,13 +61,13 @@ export function AgentChatSheet({ open, onOpenChange, agent, targetConvId, scroll{/* Top-right action buttons */}<div className="absolute top-3 right-3 z-10 flex items-center gap-1">- {agent && (() => {+ {agentId && (() => {const params = new URLSearchParams();if (scrollToTaskId) params.set("task", scrollToTaskId);if (scrollToMessageId) params.set("msg", scrollToMessageId);if (targetConvId) params.set("conv", targetConvId);const qs = params.toString();- const fullPageUrl = `/w/${slug}/agents/${agent.id}${qs ? `?${qs}` : ""}`;+ const fullPageUrl = `/w/${slug}/agents/${agentId}${qs ? `?${qs}` : ""}`;return (<Tooltip><TooltipTrigger@@ -120,11 +126,11 @@ export function AgentChatSheet({ open, onOpenChange, agent, targetConvId, scroll</div>)}- {agent && (+ {agentId && (<div className="flex-1 overflow-hidden flex flex-col"><AgentChatView- key={`${agent.id}-${targetConvId ?? ""}`}- agentId={agent.id}+ key={`${agentId}-${targetConvId ?? ""}`}+ agentId={agentId}targetConvId={targetConvId}scrollToTaskId={scrollToTaskId}scrollToMessageId={scrollToMessageId}diff --git a/src/web/src/contexts/agent-chat-sheet-context.tsx b/src/web/src/contexts/agent-chat-sheet-context.tsxindex 2d5a0acb8..3469ed229 100644--- a/src/web/src/contexts/agent-chat-sheet-context.tsx+++ b/src/web/src/contexts/agent-chat-sheet-context.tsx@@ -81,6 +81,7 @@ export function AgentChatSheetProvider({ children }: { children: ReactNode }) {<AgentChatSheetopen={open}onOpenChange={handleOpenChange}+ agentId={agentId}agent={agent}targetConvId={targetConvId}scrollToTaskId={scrollToTaskId}diff --git a/src/web/src/hooks/use-mention-popup.ts b/src/web/src/hooks/use-mention-popup.tsdeleted file mode 100644index 6057e49c3..000000000--- a/src/web/src/hooks/use-mention-popup.ts+++ /dev/null@@ -1,222 +0,0 @@-import { useState, useCallback, useMemo, useRef, useEffect } from "react"-import type { Agent, AgentLink } from "@alook/shared"--export interface MentionPopupState {- isOpen: boolean- query: string- selectedIndex: number- anchorPos: { top: number; left: number }- relatedAgents: Agent[]- otherAgents: Agent[]- allAgents: Agent[]- handleMentionKeyDown: (e: React.KeyboardEvent) => boolean- selectAgent: (agent: Agent) => void-}--interface UseMentionPopupParams {- input: string- caretIndex: number | null- textareaRef: React.RefObject<HTMLTextAreaElement | null>- agents: Agent[]- agentLinks: AgentLink[]- currentAgentId: string- onInputChange: (value: string) => void-}--const MAX_QUERY_LENGTH = 30--function findMentionTrigger(input: string, caretIndex: number): { start: number; query: string } | null {- let i = caretIndex - 1- while (i >= 0 && caretIndex - i <= MAX_QUERY_LENGTH) {- const ch = input.charCodeAt(i)- if (ch === 64) { // '@'- return { start: i, query: input.slice(i + 1, caretIndex) }- }- if (ch === 10 || ch === 13) return null- i--- }- return null-}--const POPUP_WIDTH = 256 // w-64--function getCaretCoordinates(textarea: HTMLTextAreaElement, position: number): { top: number; left: number } {- const mirror = document.createElement("div")- const style = window.getComputedStyle(textarea)-- const props = [- "fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing",- "textTransform", "wordSpacing", "textIndent", "lineHeight",- "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",- "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth",- "boxSizing", "whiteSpace", "wordWrap", "overflowWrap",- ] as const-- mirror.style.position = "absolute"- mirror.style.top = "-9999px"- mirror.style.left = "-9999px"- mirror.style.visibility = "hidden"- mirror.style.overflow = "hidden"- mirror.style.width = `${textarea.offsetWidth}px`-- for (const prop of props) {- (mirror.style as unknown as Record<string, string>)[prop] = style.getPropertyValue(- prop.replace(/([A-Z])/g, "-$1").toLowerCase()- )- }-- const textBefore = textarea.value.slice(0, position)- mirror.textContent = textBefore- const marker = document.createElement("span")- marker.textContent = ""- mirror.appendChild(marker)-- document.body.appendChild(mirror)- const top = marker.offsetTop - textarea.scrollTop- const left = Math.max(0, Math.min(marker.offsetLeft, textarea.offsetWidth - POPUP_WIDTH))- document.body.removeChild(mirror)-- return { top, left }-}--export function useMentionPopup({- input,- caretIndex,- textareaRef,- agents,- agentLinks,- currentAgentId,- onInputChange,-}: UseMentionPopupParams): MentionPopupState {- const [isOpen, setIsOpen] = useState(false)- const [query, setQuery] = useState("")- const [selectedIndex, setSelectedIndex] = useState(0)- const [anchorPos, setAnchorPos] = useState({ top: 0, left: 0 })- const triggerStartRef = useRef<number | null>(null)-- const relatedAgentIds = useMemo(() => {- const ids = new Set<string>()- for (const link of agentLinks) {- if (link.source_agent_id === currentAgentId) ids.add(link.target_agent_id)- if (link.target_agent_id === currentAgentId) ids.add(link.source_agent_id)- }- return ids- }, [agentLinks, currentAgentId])-- const { relatedAgents, otherAgents, allAgents } = useMemo(() => {- if (!isOpen) return { relatedAgents: [], otherAgents: [], allAgents: [] }-- const filterByQuery = (list: Agent[]) => {- if (!query) return list.slice(0, 20)- const q = query.toLowerCase()- const startsWith: Agent[] = []- const includes: Agent[] = []- for (const a of list) {- const name = a.name.toLowerCase()- if (name.startsWith(q)) startsWith.push(a)- else if (name.includes(q)) includes.push(a)- }- return [...startsWith, ...includes]- }-- const related: Agent[] = []- const other: Agent[] = []- for (const a of agents) {- if (relatedAgentIds.has(a.id)) related.push(a)- else other.push(a)- }-- const filteredRelated = filterByQuery(related)- const filteredOther = filterByQuery(other)-- return {- relatedAgents: filteredRelated,- otherAgents: filteredOther,- allAgents: [...filteredRelated, ...filteredOther],- }- }, [isOpen, query, agents, relatedAgentIds])-- useEffect(() => {- setSelectedIndex(0)- }, [allAgents.length, query])-- useEffect(() => {- if (caretIndex === null) {- setIsOpen(false)- return- }-- const trigger = findMentionTrigger(input, caretIndex)- if (trigger) {- triggerStartRef.current = trigger.start- setQuery(trigger.query)- setIsOpen(true)-- if (textareaRef.current) {- const coords = getCaretCoordinates(textareaRef.current, trigger.start)- setAnchorPos(coords)- }- } else {- setIsOpen(false)- triggerStartRef.current = null- }- }, [input, caretIndex, textareaRef])-- const selectAgent = useCallback((agent: Agent) => {- if (caretIndex === null || triggerStartRef.current === null) return-- const before = input.slice(0, triggerStartRef.current)- const after = input.slice(caretIndex)- const newInput = `${before}@${agent.name} ${after}`- onInputChange(newInput)- setIsOpen(false)-- const newCaretPos = before.length + 1 + agent.name.length + 1- requestAnimationFrame(() => {- const ta = textareaRef.current- if (ta) {- ta.focus()- ta.setSelectionRange(newCaretPos, newCaretPos)- }- })- }, [input, caretIndex, textareaRef, onInputChange])-- const handleMentionKeyDown = useCallback((e: React.KeyboardEvent): boolean => {- if (!isOpen || allAgents.length === 0) return false- if (e.nativeEvent.isComposing) return false-- if (e.key === "ArrowDown") {- e.preventDefault()- setSelectedIndex(i => (i + 1) % allAgents.length)- return true- }- if (e.key === "ArrowUp") {- e.preventDefault()- setSelectedIndex(i => (i - 1 + allAgents.length) % allAgents.length)- return true- }- if (e.key === "Enter") {- e.preventDefault()- selectAgent(allAgents[selectedIndex])- return true- }- if (e.key === "Escape") {- e.preventDefault()- setIsOpen(false)- return true- }- return false- }, [isOpen, allAgents, selectedIndex, selectAgent])-- return {- isOpen,- query,- selectedIndex,- anchorPos,- relatedAgents,- otherAgents,- allAgents,- handleMentionKeyDown,- selectAgent,- }-}diff --git a/src/web/src/hooks/use-slash-command.ts b/src/web/src/hooks/use-slash-command.tsindex 50bc48398..59c870945 100644--- a/src/web/src/hooks/use-slash-command.ts+++ b/src/web/src/hooks/use-slash-command.ts@@ -1,6 +1,17 @@import { useState, useCallback, useMemo, useRef, useEffect } from "react"import type { SkillEntry } from "@alook/shared"+/**+ * Minimal keyboard-event shape the popup hooks need. Both React synthetic+ * events and native KeyboardEvents (from TipTap's editorProps.handleKeyDown,+ * wrapped) satisfy it, so the same hook drives the textarea and the composer.+ */+export interface PopupKeyEvent {+ key: string+ isComposing: boolean+ preventDefault: () => void+}+export interface SlashCommandPopupState {isOpen: booleanquery: string@@ -8,7 +19,7 @@ export interface SlashCommandPopupState {anchorPos: { top: number; left: number }skills: SkillEntry[]activeSkill: SkillEntry | null- handleSlashKeyDown: (e: React.KeyboardEvent) => boolean+ handleSlashKeyDown: (e: PopupKeyEvent) => booleanselectSkill: (skill: SkillEntry) => voidclearActiveSkill: () => voidsetActiveSkill: (skill: SkillEntry | null) => void@@ -17,14 +28,20 @@ export interface SlashCommandPopupState {interface UseSlashCommandParams {input: stringcaretIndex: number | null- textareaRef: React.RefObject<HTMLTextAreaElement | null>skills: SkillEntry[]onInputChange: (value: string) => voidinitialActiveSkill?: SkillEntry | null+ /**+ * Resolve the popup anchor position (viewport-relative top/left) for the+ * slash trigger at `triggerStart`. The TipTap composer computes this from+ * `editor.view.coordsAtPos`; returns null if it cannot be resolved yet.+ */+ getAnchorPos: (triggerStart: number) => { top: number; left: number } | null+ /** Called after a skill is selected so the caller can re-focus its editor. */+ onAfterSelect?: () => void}const MAX_QUERY_LENGTH = 30-const POPUP_WIDTH = 280function findSlashTrigger(input: string, caretIndex: number): { start: number; query: string } | null {if (!input.startsWith("/")) return null@@ -41,52 +58,14 @@ function findSlashTrigger(input: string, caretIndex: number): { start: number; qreturn null}-function getCaretCoordinates(textarea: HTMLTextAreaElement, position: number): { top: number; left: number } {- const mirror = document.createElement("div")- const style = window.getComputedStyle(textarea)-- const props = [- "fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing",- "textTransform", "wordSpacing", "textIndent", "lineHeight",- "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",- "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth",- "boxSizing", "whiteSpace", "wordWrap", "overflowWrap",- ] as const-- mirror.style.position = "absolute"- mirror.style.top = "-9999px"- mirror.style.left = "-9999px"- mirror.style.visibility = "hidden"- mirror.style.overflow = "hidden"- mirror.style.width = `${textarea.offsetWidth}px`-- for (const prop of props) {- (mirror.style as unknown as Record<string, string>)[prop] = style.getPropertyValue(- prop.replace(/([A-Z])/g, "-$1").toLowerCase()- )- }-- const textBefore = textarea.value.slice(0, position)- mirror.textContent = textBefore- const marker = document.createElement("span")- marker.textContent = ""- mirror.appendChild(marker)-- document.body.appendChild(mirror)- const top = marker.offsetTop - textarea.scrollTop- const left = Math.max(0, Math.min(marker.offsetLeft, textarea.offsetWidth - POPUP_WIDTH))- document.body.removeChild(mirror)-- return { top, left }-}-export function useSlashCommand({input,caretIndex,- textareaRef,skills,onInputChange,initialActiveSkill,+ getAnchorPos,+ onAfterSelect,}: UseSlashCommandParams): SlashCommandPopupState {const [isOpen, setIsOpen] = useState(false)const [query, setQuery] = useState("")@@ -130,37 +109,28 @@ export function useSlashCommand({setQuery(trigger.query)setIsOpen(true)- if (textareaRef.current) {- const coords = getCaretCoordinates(textareaRef.current, trigger.start)- setAnchorPos(coords)- }+ const coords = getAnchorPos(trigger.start)+ if (coords) setAnchorPos(coords)} else {setIsOpen(false)triggerStartRef.current = null}- }, [input, caretIndex, textareaRef, activeSkill])+ }, [input, caretIndex, getAnchorPos, activeSkill])const selectSkill = useCallback((skill: SkillEntry) => {setActiveSkill(skill)onInputChange("")setIsOpen(false)-- requestAnimationFrame(() => {- const ta = textareaRef.current- if (ta) {- ta.focus()- ta.setSelectionRange(0, 0)- }- })- }, [textareaRef, onInputChange])+ onAfterSelect?.()+ }, [onInputChange, onAfterSelect])const clearActiveSkill = useCallback(() => {setActiveSkill(null)}, [])- const handleSlashKeyDown = useCallback((e: React.KeyboardEvent): boolean => {+ const handleSlashKeyDown = useCallback((e: PopupKeyEvent): boolean => {if (!isOpen || filteredSkills.length === 0) return false- if (e.nativeEvent.isComposing) return false+ if (e.isComposing) return falseif (e.key === "ArrowDown") {e.preventDefault()diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.tsindex 57d683b17..341f2e702 100644--- a/src/web/src/lib/api.test.ts+++ b/src/web/src/lib/api.test.ts@@ -219,6 +219,41 @@ describe("apiFetch", () => {});});+describe("conversationInit — message_count serialization", () => {+ function okJson() {+ return { ok: true, status: 200, json: async () => ({}) };+ }++ function lastUrl(): string {+ const call = mockFetch.mock.calls.at(-1);+ return String(call?.[0] ?? "");+ }++ it("omits message_count when the count is 0 (treated as unknown)", async () => {+ mockFetch.mockResolvedValueOnce(okJson());+ const { conversationInit } = await getApiFetch();+ await conversationInit("conv_1", "w1", { messageCount: 0 });+ expect(lastUrl()).not.toContain("message_count");+ // Critically: never sends the truthy string "0", which would make the+ // server's `serverMessageCount === 0` compare fail for non-empty convs.+ expect(lastUrl()).not.toContain("message_count=0");+ });++ it("includes message_count when the count is greater than 0", async () => {+ mockFetch.mockResolvedValueOnce(okJson());+ const { conversationInit } = await getApiFetch();+ await conversationInit("conv_1", "w1", { messageCount: 12 });+ expect(lastUrl()).toContain("message_count=12");+ });++ it("omits message_count when not provided", async () => {+ mockFetch.mockResolvedValueOnce(okJson());+ const { conversationInit } = await getApiFetch();+ await conversationInit("conv_1", "w1");+ expect(lastUrl()).not.toContain("message_count");+ });+});+describe("apiFetch — mock network delay", () => {afterEach(() => {process.env.NODE_ENV = "test";diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex a3fec5da9..b714d0d0a 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -310,7 +310,11 @@ export const conversationInit = () => {const extra: Record<string, string> = {};if (opts?.newestMessageId) extra.newest_message_id = opts.newestMessageId;- if (opts?.messageCount != null) extra.message_count = String(opts.messageCount);+ // Omit a 0 count: the server treats the param as a count to compare against,+ // and the string "0" is truthy server-side, so sending it forces+ // `serverMessageCount === 0` to fail for every non-empty conversation. 0 here+ // means "unknown count" — rely on newestMessageId for the freshness compare.+ if (opts?.messageCount) extra.message_count = String(opts.messageCount);return apiFetch<ConversationInitResponse>(`/api/conversations/${conversationId}/init${wsQuery(workspaceId, extra)}`,);diff --git a/src/web/src/lib/chat-cache.test.ts b/src/web/src/lib/chat-cache.test.tsindex 56b5d4cbd..1a8af6415 100644--- a/src/web/src/lib/chat-cache.test.ts+++ b/src/web/src/lib/chat-cache.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, beforeEach } from "vitest";import "fake-indexeddb/auto";+import { openDB } from "idb";import type { Message } from "@alook/shared";import {openCacheDB,@@ -12,6 +13,9 @@ import {invalidateCache,evictLRU,clearAllCache,+ getLastOpenConversation,+ setLastOpenConversation,+ clearLastOpenForConversation,} from "./chat-cache";const WORKSPACE_ID = "ws_test";@@ -42,6 +46,7 @@ describe("chat-cache", () => {const db = await p!;expect(db.objectStoreNames.contains("messages")).toBe(true);expect(db.objectStoreNames.contains("cache_meta")).toBe(true);+ expect(db.objectStoreNames.contains("last_open")).toBe(true);});});@@ -231,6 +236,95 @@ describe("chat-cache", () => {const meta = await getCacheMeta("conv_1", WORKSPACE_ID);expect(meta).toBeNull();});++ it("clears any last_open pointer referencing the invalidated conversation", async () => {+ await mergeCachedMessages("conv_1", [makeMessage({ id: "m1", conversation_id: "conv_1" })], false, WORKSPACE_ID);+ await setLastOpenConversation("agent_a", "chan", {+ conversation_id: "conv_1",+ newestMessageId: "m1",+ serverMessageCount: 1,+ }, WORKSPACE_ID);++ await invalidateCache("conv_1", WORKSPACE_ID);++ expect(await getLastOpenConversation("agent_a", "chan", WORKSPACE_ID)).toBeNull();+ });+ });++ describe("last_open pointer", () => {+ it("set then get round-trips for the same agent+channel", async () => {+ await setLastOpenConversation("agent_a", "chan_x", {+ conversation_id: "conv_1",+ newestMessageId: "m9",+ serverMessageCount: 12,+ }, WORKSPACE_ID);++ const entry = await getLastOpenConversation("agent_a", "chan_x", WORKSPACE_ID);+ expect(entry).not.toBeNull();+ expect(entry!.conversation_id).toBe("conv_1");+ expect(entry!.newestMessageId).toBe("m9");+ expect(entry!.serverMessageCount).toBe(12);+ });++ it("is scoped by channel — a different channel returns null", async () => {+ await setLastOpenConversation("agent_a", "chan_x", {+ conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,+ }, WORKSPACE_ID);++ expect(await getLastOpenConversation("agent_a", "chan_y", WORKSPACE_ID)).toBeNull();+ expect((await getLastOpenConversation("agent_a", "chan_x", WORKSPACE_ID))?.conversation_id).toBe("conv_1");+ });++ it("is scoped by agent — agent A channel x and agent B channel x are independent", async () => {+ await setLastOpenConversation("agent_a", "chan_x", {+ conversation_id: "conv_a", newestMessageId: "ma", serverMessageCount: 1,+ }, WORKSPACE_ID);+ await setLastOpenConversation("agent_b", "chan_x", {+ conversation_id: "conv_b", newestMessageId: "mb", serverMessageCount: 1,+ }, WORKSPACE_ID);++ expect((await getLastOpenConversation("agent_a", "chan_x", WORKSPACE_ID))?.conversation_id).toBe("conv_a");+ expect((await getLastOpenConversation("agent_b", "chan_x", WORKSPACE_ID))?.conversation_id).toBe("conv_b");+ });++ it("null and undefined channel resolve to the same entry", async () => {+ await setLastOpenConversation("agent_a", null, {+ conversation_id: "conv_default", newestMessageId: "m1", serverMessageCount: 3,+ }, WORKSPACE_ID);++ const viaUndefined = await getLastOpenConversation("agent_a", undefined, WORKSPACE_ID);+ expect(viaUndefined?.conversation_id).toBe("conv_default");++ // Writing via undefined overwrites the same row read via null.+ await setLastOpenConversation("agent_a", undefined, {+ conversation_id: "conv_default2", newestMessageId: "m2", serverMessageCount: 4,+ }, WORKSPACE_ID);+ const viaNull = await getLastOpenConversation("agent_a", null, WORKSPACE_ID);+ expect(viaNull?.conversation_id).toBe("conv_default2");+ });++ it("returns null on cache miss", async () => {+ expect(await getLastOpenConversation("agent_missing", "chan", WORKSPACE_ID)).toBeNull();+ });++ it("clearLastOpenForConversation removes only the matching rows", async () => {+ await setLastOpenConversation("agent_a", "chan_x", {+ conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,+ }, WORKSPACE_ID);+ await setLastOpenConversation("agent_b", "chan_y", {+ conversation_id: "conv_1", newestMessageId: "m1", serverMessageCount: 1,+ }, WORKSPACE_ID);+ await setLastOpenConversation("agent_c", "chan_z", {+ conversation_id: "conv_2", newestMessageId: "m2", serverMessageCount: 1,+ }, WORKSPACE_ID);++ await clearLastOpenForConversation("conv_1", WORKSPACE_ID);++ expect(await getLastOpenConversation("agent_a", "chan_x", WORKSPACE_ID)).toBeNull();+ expect(await getLastOpenConversation("agent_b", "chan_y", WORKSPACE_ID)).toBeNull();+ // Pointer to conv_2 is untouched.+ expect((await getLastOpenConversation("agent_c", "chan_z", WORKSPACE_ID))?.conversation_id).toBe("conv_2");+ });});describe("evictLRU", () => {@@ -266,6 +360,37 @@ describe("chat-cache", () => {expect(meta3).not.toBeNull();expect(meta4).not.toBeNull();});++ it("prunes last_open pointers for evicted conversations (no dangling id)", async () => {+ const db = await openCacheDB(WORKSPACE_ID)!;++ for (let i = 0; i < 5; i++) {+ await db.put("messages", makeMessage({ id: `m_${i}`, conversation_id: `conv_${i}`, created_at: `2024-01-0${i + 1}T00:00:00Z` }));+ await db.put("cache_meta", {+ conversation_id: `conv_${i}`,+ lastFetchedAt: Date.now(),+ lastAccessedAt: i * 1000,+ messageCount: 1,+ newestMessageId: `m_${i}`,+ hasMore: false,+ serverMessageCount: 1,+ });+ await setLastOpenConversation(`agent_${i}`, "chan", {+ conversation_id: `conv_${i}`,+ newestMessageId: `m_${i}`,+ serverMessageCount: 1,+ }, WORKSPACE_ID);+ }++ await evictLRU(3);++ // conv_0 and conv_1 were evicted — their last_open pointers must be gone.+ expect(await getLastOpenConversation("agent_0", "chan", WORKSPACE_ID)).toBeNull();+ expect(await getLastOpenConversation("agent_1", "chan", WORKSPACE_ID)).toBeNull();+ // Survivors keep their pointers.+ expect((await getLastOpenConversation("agent_2", "chan", WORKSPACE_ID))?.conversation_id).toBe("conv_2");+ expect((await getLastOpenConversation("agent_4", "chan", WORKSPACE_ID))?.conversation_id).toBe("conv_4");+ });});describe("getCachedMessagesBefore", () => {@@ -420,6 +545,59 @@ describe("chat-cache", () => {});});+ describe("v2 → v3 migration", () => {+ it("upgrades an existing v2 DB to v3, adding last_open and preserving messages/cache_meta", async () => {+ // Use a dedicated workspace so we don't collide with the shared beforeEach DB.+ const MIGRATE_WS = "ws_migrate";+ await clearAllCache();++ // Build a v2-shaped DB by hand (only messages + cache_meta, version 2).+ const v2 = await openDB(`alook-chat-cache-${MIGRATE_WS}`, 2, {+ upgrade(db) {+ const msgStore = db.createObjectStore("messages", { keyPath: ["conversation_id", "id"] });+ msgStore.createIndex("by-conversation", "conversation_id", { unique: false });+ msgStore.createIndex("by-created", ["conversation_id", "created_at"], { unique: false });+ db.createObjectStore("cache_meta", { keyPath: "conversation_id" });+ },+ });+ await v2.put("messages", makeMessage({ id: "m1", conversation_id: "conv_old", created_at: "2024-01-01T00:00:00Z" }));+ await v2.put("cache_meta", {+ conversation_id: "conv_old",+ lastFetchedAt: 1,+ lastAccessedAt: 1,+ messageCount: 1,+ newestMessageId: "m1",+ hasMore: false,+ serverMessageCount: 1,+ });+ expect(v2.version).toBe(2);+ expect(v2.objectStoreNames.contains("last_open")).toBe(false);+ v2.close();++ // Open via the production code path — should upgrade to v3.+ const db = await openCacheDB(MIGRATE_WS)!;+ expect(db.version).toBe(3);+ expect(db.objectStoreNames.contains("last_open")).toBe(true);++ // Existing data is intact.+ const cached = await getCachedMessages("conv_old", MIGRATE_WS);+ expect(cached).toHaveLength(1);+ expect(cached![0].id).toBe("m1");+ const meta = await getCacheMeta("conv_old", MIGRATE_WS);+ expect(meta!.newestMessageId).toBe("m1");+ expect(meta!.serverMessageCount).toBe(1);++ // New store works.+ await setLastOpenConversation("agent_x", null, {+ conversation_id: "conv_old", newestMessageId: "m1", serverMessageCount: 1,+ }, MIGRATE_WS);+ expect((await getLastOpenConversation("agent_x", null, MIGRATE_WS))?.conversation_id).toBe("conv_old");++ await clearAllCache();+ openCacheDB(WORKSPACE_ID);+ });+ });+describe("clearAllCache", () => {it("removes everything", async () => {await mergeCachedMessages(diff --git a/src/web/src/lib/chat-cache.ts b/src/web/src/lib/chat-cache.tsindex 1fa7ebed3..e61bdb860 100644--- a/src/web/src/lib/chat-cache.ts+++ b/src/web/src/lib/chat-cache.ts@@ -11,6 +11,23 @@ export interface CacheMeta {serverMessageCount: number;}+/**+ * Pointer to the last-open conversation for a given agent+channel, used to+ * render the multi-conversation chat page cache-first (without a gating+ * network round-trip to resolve "which conversation is this?").+ *+ * The DB is already scoped per-workspace (`alook-chat-cache-${workspaceId}`),+ * so the key only needs to encode agent + channel.+ */+export interface LastOpenEntry {+ /** `${agentId}::${channel == null ? "" : channel}` — see {@link lastOpenKey} */+ key: string;+ conversation_id: string;+ newestMessageId: string | null;+ serverMessageCount: number;+ updatedAt: number;+}+interface ChatCacheDB {messages: {key: [string, string];@@ -24,9 +41,16 @@ interface ChatCacheDB {key: string;value: CacheMeta;};+ last_open: {+ key: string;+ value: LastOpenEntry;+ indexes: {+ "by-conversation": string;+ };+ };}-const DB_VERSION = 2;+const DB_VERSION = 3;const MAX_CONVERSATIONS = 50;let dbPromise: Promise<IDBPDatabase<ChatCacheDB>> | null = null;@@ -51,6 +75,14 @@ export function openCacheDB(workspaceId: string): Promise<IDBPDatabase<ChatCache}// v1 → v2: serverMessageCount field added to cache_meta entries.// No schema migration needed — the field is added at write time with default 0.+ if (oldVersion < 3) {+ // v2 → v3: last-open conversation pointer per agent+channel. Existing+ // `messages`/`cache_meta` stores are untouched; this store starts empty,+ // so the first param-less open is a clean cache miss (today's behavior),+ // then it populates.+ const lastOpenStore = db.createObjectStore("last_open", { keyPath: "key" });+ lastOpenStore.createIndex("by-conversation", "conversation_id", { unique: false });+ }},});@@ -274,15 +306,100 @@ export async function getCacheMeta(conversationId: string, workspaceId?: string)}}+/**+ * Build the `last_open` key. `null` and `undefined` channel both normalize to+ * `""`, so the param-less "default channel" maps to one stable entry.+ */+function lastOpenKey(agentId: string, channel: string | null | undefined): string {+ return `${agentId}::${channel == null ? "" : channel}`;+}++/**+ * Read the last-open conversation pointer for an agent+channel. IndexedDB only,+ * no network. Returns null on cache miss, error, or SSR (no indexedDB).+ *+ * Note: `null` and `undefined` channel resolve to the same entry (see+ * {@link lastOpenKey}).+ */+export async function getLastOpenConversation(+ agentId: string,+ channel: string | null | undefined,+ workspaceId?: string+): Promise<LastOpenEntry | null> {+ const p = getDB(workspaceId);+ if (!p) return null;++ try {+ const db = await p;+ return (await db.get("last_open", lastOpenKey(agentId, channel))) ?? null;+ } catch {+ return null;+ }+}++/**+ * Write the last-open conversation pointer for an agent+channel. Should only be+ * called with server-confirmed values (newest id / count) so the next open's+ * freshness compare is accurate.+ */+export async function setLastOpenConversation(+ agentId: string,+ channel: string | null | undefined,+ entry: Pick<LastOpenEntry, "conversation_id" | "newestMessageId" | "serverMessageCount">,+ workspaceId?: string+): Promise<void> {+ const p = getDB(workspaceId);+ if (!p) return;++ try {+ const db = await p;+ await db.put("last_open", {+ key: lastOpenKey(agentId, channel),+ conversation_id: entry.conversation_id,+ newestMessageId: entry.newestMessageId,+ serverMessageCount: entry.serverMessageCount,+ updatedAt: Date.now(),+ });+ } catch {+ // Graceful degradation+ }+}++/**+ * Remove any `last_open` pointer(s) referencing the given conversation. Used+ * when invalidating a conversation so we don't render then immediately wipe.+ */+export async function clearLastOpenForConversation(+ conversationId: string,+ workspaceId?: string+): Promise<void> {+ const p = getDB(workspaceId);+ if (!p) return;++ try {+ const db = await p;+ const tx = db.transaction("last_open", "readwrite");+ const store = tx.objectStore("last_open");+ const keys = await store.index("by-conversation").getAllKeys(conversationId);+ for (const key of keys) {+ await store.delete(key);+ }+ await tx.done;+ } catch {+ // Graceful degradation+ }+}+export async function invalidateCache(conversationId: string, workspaceId?: string): Promise<void> {const p = getDB(workspaceId);if (!p) return;try {const db = await p;- const tx = db.transaction(["messages", "cache_meta"], "readwrite");+ const tx = db.transaction(["messages", "cache_meta", "last_open"], "readwrite");const msgStore = tx.objectStore("messages");const metaStore = tx.objectStore("cache_meta");+ const lastOpenStore = tx.objectStore("last_open");const keys = await msgStore.index("by-conversation").getAllKeys(conversationId);for (const key of keys) {@@ -290,6 +407,13 @@ export async function invalidateCache(conversationId: string, workspaceId?: stri}await metaStore.delete(conversationId);+ // Drop any last-open pointer to this conversation so a later param-less+ // open doesn't briefly render the invalidated conversation.+ const lastOpenKeys = await lastOpenStore.index("by-conversation").getAllKeys(conversationId);+ for (const key of lastOpenKeys) {+ await lastOpenStore.delete(key);+ }+await tx.done;} catch {// Graceful degradation@@ -308,9 +432,10 @@ export async function evictLRU(maxConversations = MAX_CONVERSATIONS): Promise<voallMeta.sort((a, b) => a.lastAccessedAt - b.lastAccessedAt);const toEvict = allMeta.slice(0, allMeta.length - maxConversations);- const tx = db.transaction(["messages", "cache_meta"], "readwrite");+ const tx = db.transaction(["messages", "cache_meta", "last_open"], "readwrite");const msgStore = tx.objectStore("messages");const metaStore = tx.objectStore("cache_meta");+ const lastOpenStore = tx.objectStore("last_open");for (const meta of toEvict) {const keys = await msgStore.index("by-conversation").getAllKeys(meta.conversation_id);@@ -318,6 +443,13 @@ export async function evictLRU(maxConversations = MAX_CONVERSATIONS): Promise<voawait msgStore.delete(key);}await metaStore.delete(meta.conversation_id);++ // Prune any last-open pointers to the evicted conversation so we never+ // keep a dangling id that would resolve to an empty cache.+ const lastOpenKeys = await lastOpenStore.index("by-conversation").getAllKeys(meta.conversation_id);+ for (const key of lastOpenKeys) {+ await lastOpenStore.delete(key);+ }}await tx.done;diff --git a/src/web/src/lib/chat-markdown.test.ts b/src/web/src/lib/chat-markdown.test.tsnew file mode 100644index 000000000..7c95322bd--- /dev/null+++ b/src/web/src/lib/chat-markdown.test.ts@@ -0,0 +1,38 @@+import { describe, it, expect } from "vitest";+import { decodeChatEntities } from "./chat-markdown";++/**+ * `@tiptap/markdown` HTML-entity-encodes `<` `>` `&` in plain text when+ * serializing. The chat wire format must stay the raw typed string (parity with+ * the old textarea), so the composer decodes exactly those three. These tests+ * lock that behavior and guard the `&`-last ordering.+ */+describe("decodeChatEntities", () => {+ it("decodes the three HTML entities the serializer emits", () => {+ expect(decodeChatEntities("a < b && c > d")).toBe("a < b && c > d");+ });++ it("decodes <Component /> style text", () => {+ expect(decodeChatEntities("use <Component /> here")).toBe("use <Component /> here");+ });++ it("leaves text without entities untouched", () => {+ expect(decodeChatEntities("plain @Alice - list 1. item")).toBe(+ "plain @Alice - list 1. item",+ );+ });++ it("decodes & last so a literal typed entity round-trips", () => {+ // User types the literal text "<". The serializer escapes the `&` to+ // "&lt;". Decoding & LAST yields "<" (the typed text), not "<".+ expect(decodeChatEntities("&lt;")).toBe("<");+ });++ it("does not touch markdown punctuation", () => {+ expect(decodeChatEntities("a*b_c`d# heading")).toBe("a*b_c`d# heading");+ });++ it("handles empty string", () => {+ expect(decodeChatEntities("")).toBe("");+ });+});diff --git a/src/web/src/lib/chat-markdown.ts b/src/web/src/lib/chat-markdown.tsnew file mode 100644index 000000000..554237eb5--- /dev/null+++ b/src/web/src/lib/chat-markdown.ts@@ -0,0 +1,18 @@+/**+ * The chat wire format is a plain string and must stay byte-identical to what+ * the old textarea sent. But `@tiptap/markdown`'s serializer HTML-entity-encodes+ * the three HTML-significant characters in plain text — `<`→`<`, `>`→`>`,+ * `&`→`&` — so `getMarkdown()` of "x < 5 && y > 3" returns+ * "x < 5 && y > 3". Markdown punctuation (`*` `_` `` ` `` `#`) is+ * left literal, which is what we want; only these HTML entities leak in.+ *+ * We decode exactly those three back so the outgoing content matches the typed+ * text. `&` is decoded LAST so a literal "<" the user typed (which the+ * serializer emits as "&lt;") round-trips to "<", not "<".+ */+export function decodeChatEntities(markdown: string): string {+ return markdown+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replaceAll("&", "&");+}diff --git a/src/web/src/lib/chat-mention-extension.test.ts b/src/web/src/lib/chat-mention-extension.test.tsnew file mode 100644index 000000000..767168fcb--- /dev/null+++ b/src/web/src/lib/chat-mention-extension.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect } from "vitest";+import { MarkdownManager } from "@tiptap/markdown";+import StarterKit from "@tiptap/starter-kit";+import { buildChatMentionExtension } from "./chat-mention-extension";++/**+ * TODO #0 acceptance (highest-risk assumption): a Mention node must serialize+ * to byte-exact `@Name` in markdown — the wire format the backend already+ * expects. This guards against a TipTap upgrade silently regressing the+ * serializer back to `[@ id=... label=...]` or adding `\@` escaping.+ */++// StarterKit is a bundle; the MarkdownManager wants flat extensions.+function flatten(ext: ReturnType<typeof StarterKit.configure>) {+ const out: unknown[] = [];+ const visit = (e: { config?: { addExtensions?: () => unknown[] } }) => {+ if (e?.config?.addExtensions) {+ try {+ for (const c of e.config.addExtensions.call(e)) visit(c as typeof e);+ } catch {+ /* ignore bundles that can't expand without an editor */+ }+ }+ out.push(e);+ };+ visit(ext as never);+ return out;+}++function serialize(doc: object): string {+ const extensions = [+ ...flatten(StarterKit.configure({})),+ buildChatMentionExtension(),+ ];+ const mgr = new MarkdownManager({ extensions: extensions as never });+ return mgr.serialize(doc as never);+}++function para(...content: object[]) {+ return { type: "doc", content: [{ type: "paragraph", content }] };+}++const mention = (id: string, label: string) => ({+ type: "mention",+ attrs: { id, label },+});+const text = (t: string) => ({ type: "text", text: t });++describe("chat mention markdown serialization", () => {+ it("serializes a mention to byte-exact @Name", () => {+ expect(serialize(para(text("hi "), mention("a1", "Alice"), text(" there")))).toBe(+ "hi @Alice there",+ );+ });++ it("does not escape the @ (no \\@)", () => {+ const md = serialize(para(mention("a1", "Alice")));+ expect(md).toBe("@Alice");+ expect(md).not.toContain("\\@");+ });++ it("falls back to id when label is null/undefined", () => {+ // renderMarkdown uses `label ?? id`, so a null label (never the case for+ // real agent mentions, but defensive) serializes to the id.+ const md = serialize(+ para({ type: "mention", attrs: { id: "agent-7", label: null } }),+ );+ expect(md).toBe("@agent-7");+ });++ it("serializes multiple mentions in one line", () => {+ expect(+ serialize(+ para(mention("a1", "Alice"), text(" and "), mention("b2", "Bob"), text(" hi")),+ ),+ ).toBe("@Alice and @Bob hi");+ });+});diff --git a/src/web/src/lib/chat-mention-extension.ts b/src/web/src/lib/chat-mention-extension.tsnew file mode 100644index 000000000..69f9a9963--- /dev/null+++ b/src/web/src/lib/chat-mention-extension.ts@@ -0,0 +1,23 @@+import Mention from "@tiptap/extension-mention";++/**+ * Mention configured to serialize to byte-exact `@Name` in markdown.+ *+ * `@tiptap/markdown` reads `renderMarkdown` off the extension config via+ * getExtensionField (keyed on the node name "mention"). Spike-verified: without+ * it the manager emits `[@ id="..." label="..."]`; with it (and no escaping)+ * `getMarkdown()` of "hi @Alice" === "hi @Alice". `renderText` keeps copy /+ * getText() in sync. See plans/chat-input-tiptap-migration.md TODO #0.+ *+ * These two fields aren't in TipTap's NodeConfig types (the markdown plugin+ * reads them dynamically), so the config is cast to the extend param type.+ */+type MentionExtendConfig = Parameters<typeof Mention.extend>[0];++export function buildChatMentionExtension() {+ return Mention.extend({+ markdownName: "mention",+ renderMarkdown: (node: { attrs: { id: string; label?: string | null } }) =>+ `@${node.attrs.label ?? node.attrs.id}`,+ } as MentionExtendConfig);+}diff --git a/src/web/src/lib/mention-agents.test.ts b/src/web/src/lib/mention-agents.test.tsnew file mode 100644index 000000000..107bd2957--- /dev/null+++ b/src/web/src/lib/mention-agents.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect } from "vitest";+import type { Agent, AgentLink } from "@alook/shared";+import { relatedAgentIdSet, filterAgentsByQuery, rankMentionAgents } from "./mention-agents";++const agent = (id: string, name: string): Agent =>+ ({ id, name } as Agent);++const link = (source: string, target: string): AgentLink =>+ ({ source_agent_id: source, target_agent_id: target } as AgentLink);++describe("relatedAgentIdSet", () => {+ it("collects linked agents in both directions", () => {+ const links = [link("me", "alice"), link("bob", "me"), link("x", "y")];+ const set = relatedAgentIdSet(links, "me");+ expect([...set].sort()).toEqual(["alice", "bob"]);+ });++ it("returns empty when no links touch the current agent", () => {+ expect(relatedAgentIdSet([link("x", "y")], "me").size).toBe(0);+ });+});++describe("filterAgentsByQuery", () => {+ const list = [agent("1", "Alice"), agent("2", "Albert"), agent("3", "Bob"), agent("4", "Calbert")];++ it("returns the list unchanged for an empty query", () => {+ expect(filterAgentsByQuery(list, "")).toBe(list);+ });++ it("ranks prefix matches before substring matches", () => {+ // query "al": Alice/Albert start with it; Calbert only contains it+ const names = filterAgentsByQuery(list, "al").map((a) => a.name);+ expect(names).toEqual(["Alice", "Albert", "Calbert"]);+ });++ it("is case-insensitive", () => {+ expect(filterAgentsByQuery(list, "BOB").map((a) => a.name)).toEqual(["Bob"]);+ });+});++describe("rankMentionAgents", () => {+ const agents = [agent("alice", "Alice"), agent("bob", "Bob"), agent("carol", "Carol")];+ const links = [link("me", "carol")]; // carol is related to me++ it("puts related agents first, then others", () => {+ const out = rankMentionAgents(agents, links, "me", "").map((a) => a.name);+ expect(out[0]).toBe("Carol");+ expect(out.slice(1).sort()).toEqual(["Alice", "Bob"]);+ });++ it("applies the query within both groups", () => {+ const out = rankMentionAgents(+ [agent("ca", "Cara"), agent("co", "Cody"), agent("al", "Alan")],+ [link("me", "ca")],+ "me",+ "c",+ ).map((a) => a.name);+ // related first (Cara), then other matches (Cody); Alan filtered out+ expect(out).toEqual(["Cara", "Cody"]);+ });++ it("respects the limit", () => {+ const many = Array.from({ length: 30 }, (_, i) => agent(`a${i}`, `Agent${i}`));+ expect(rankMentionAgents(many, [], "me", "", 20)).toHaveLength(20);+ });+});diff --git a/src/web/src/lib/mention-agents.ts b/src/web/src/lib/mention-agents.tsnew file mode 100644index 000000000..df282cc4d--- /dev/null+++ b/src/web/src/lib/mention-agents.ts@@ -0,0 +1,60 @@+import type { Agent, AgentLink } from "@alook/shared"++/**+ * Build the set of agent ids that are "related" to the current agent — i.e.+ * directly linked in either direction. Shared by the textarea mention popup+ * hook and the TipTap composer suggestion so both rank related agents first.+ */+export function relatedAgentIdSet(+ agentLinks: AgentLink[],+ currentAgentId: string,+): Set<string> {+ const ids = new Set<string>()+ for (const link of agentLinks) {+ if (link.source_agent_id === currentAgentId) ids.add(link.target_agent_id)+ if (link.target_agent_id === currentAgentId) ids.add(link.source_agent_id)+ }+ return ids+}++/**+ * Filter a list of agents by a query, ranking name-prefix matches before+ * substring matches. Empty query returns the list untouched (caller slices).+ */+export function filterAgentsByQuery(list: Agent[], query: string): Agent[] {+ if (!query) return list+ const q = query.toLowerCase()+ const startsWith: Agent[] = []+ const includes: Agent[] = []+ for (const a of list) {+ const name = a.name.toLowerCase()+ if (name.startsWith(q)) startsWith.push(a)+ else if (name.includes(q)) includes.push(a)+ }+ return [...startsWith, ...includes]+}++/**+ * Produce the mention-suggestion order: related agents first (query-filtered),+ * then everyone else (query-filtered), capped at `limit` total. This is the+ * grouped order the TipTap composer feeds into its suggestion list.+ */+export function rankMentionAgents(+ agents: Agent[],+ agentLinks: AgentLink[],+ currentAgentId: string,+ query: string,+ limit = 20,+): Agent[] {+ const related = relatedAgentIdSet(agentLinks, currentAgentId)+ const inRelated: Agent[] = []+ const other: Agent[] = []+ for (const a of agents) {+ if (related.has(a.id)) inRelated.push(a)+ else other.push(a)+ }+ return [+ ...filterAgentsByQuery(inRelated, query),+ ...filterAgentsByQuery(other, query),+ ].slice(0, limit)+}