Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(chat): annotate agent replies into the next message (MUL-8979) (#10315)

Jiayuan Zhang6deee6599a5d
diff --git a/packages/core/issues/stores/comment-draft-store.test.ts b/packages/core/issues/stores/comment-draft-store.test.ts
index 8a0e241f76..dcf6f938ef 100644
--- a/packages/core/issues/stores/comment-draft-store.test.ts
+++ b/packages/core/issues/stores/comment-draft-store.test.ts
@@ -396,6 +396,15 @@ describe("reply annotations", () => {
expect(useCommentDraftStore.getState().addAnnotation("edit:issue:comment", annotation)).toBeUndefined();
});
+ it("keeps chat annotation drafts without text or a reply target", () => {
+ const store = useCommentDraftStore.getState();
+ expect(store.addAnnotation("chat:session-1", { ...annotation, sourceCommentId: "message-1" })).toBe("a");
+ expect(store.getAnnotations("chat:session-1")[0]?.sourceCommentId).toBe("message-1");
+ expect(useCommentDraftStore.getState().drafts["chat:session-1"]?.replyTarget).toBeUndefined();
+ store.removeAnnotation("chat:session-1", "a");
+ expect(useCommentDraftStore.getState().drafts["chat:session-1"]).toBeUndefined();
+ });
+
it("reopens duplicate ranges, bounds collection, and changes identity only on actual edits", () => {
const store = useCommentDraftStore.getState();
expect(store.addAnnotation(key, annotation)).toBe("a");
diff --git a/packages/core/issues/stores/comment-draft-store.ts b/packages/core/issues/stores/comment-draft-store.ts
index 4cd86c94d9..6047910b72 100644
--- a/packages/core/issues/stores/comment-draft-store.ts
+++ b/packages/core/issues/stores/comment-draft-store.ts
@@ -37,7 +37,8 @@ import type { Attachment } from "../../types";
export type CommentDraftKey =
| `new:${string}` // top-level CommentInput, key = `new:${issueId}`
| `reply:${string}:${string}` // ReplyInput inside a thread, key = `reply:${issueId}:${rootCommentId}`
- | `edit:${string}:${string}`; // inline edit on existing comment, key = `edit:${issueId}:${commentId}`
+ | `edit:${string}:${string}` // inline edit on existing comment, key = `edit:${issueId}:${commentId}`
+ | `chat:${string}`; // chat composer annotations only, key = `chat:${sessionId}`; text lives in the chat store
interface CommentDraft {
content: string;
@@ -243,7 +244,7 @@ export const useCommentDraftStore = create<CommentDraftStore>()(
}),
getAnnotations: (key) => get().drafts[key]?.annotations ?? EMPTY_REPLY_ANNOTATIONS,
addAnnotation: (key, annotation) => {
- if ((!key.startsWith("reply:") && !key.startsWith("new:")) || !annotation.note.trim() || !annotation.quote.trim() || annotation.quote.length > MAX_ANNOTATION_QUOTE_LENGTH) return undefined;
+ if ((!key.startsWith("reply:") && !key.startsWith("new:") && !key.startsWith("chat:")) || !annotation.note.trim() || !annotation.quote.trim() || annotation.quote.length > MAX_ANNOTATION_QUOTE_LENGTH) return undefined;
const current = get().getAnnotations(key);
const duplicate = current.find((a) => a.sourceCommentId === annotation.sourceCommentId &&
a.start === annotation.start && a.quote === annotation.quote && a.prefix === annotation.prefix && a.suffix === annotation.suffix);
diff --git a/packages/views/chat/chat-page.tsx b/packages/views/chat/chat-page.tsx
index 36a8d4983d..32e78b8be2 100644
--- a/packages/views/chat/chat-page.tsx
+++ b/packages/views/chat/chat-page.tsx
@@ -30,6 +30,7 @@ import { ChatSessionHeader } from "./components/chat-session-header";
import { EmptyState } from "./components/chat-empty-state";
import { NewChatButton } from "./components/new-chat-button";
import { useChatController } from "./components/use-chat-controller";
+import { useChatAnnotations } from "./components/use-chat-annotations";
import { OfflineBanner } from "./components/offline-banner";
import { NoAgentBanner } from "./components/no-agent-banner";
import { ArchivedAgentBanner } from "./components/archived-agent-banner";
@@ -81,6 +82,11 @@ export function ChatPage() {
// Toast when an accepted refresh later fails in the daemon (async half).
useQuickActionsFailureToast(c.activeSessionId ?? null);
const regenerateQuickActions = useRegenerateChatQuickActions();
+ const annotations = useChatAnnotations({
+ sessionId: c.activeSessionId,
+ agentName: c.activeAgent?.name,
+ enabled: !c.isSessionArchived && !c.isAgentArchived && !c.isAgentAccessRevoked && c.isAgentRuntimeBound && !c.noAgent,
+ });
const urlSession = searchParams.get("session") || null;
const urlAgent = searchParams.get("agent") || null;
@@ -350,6 +356,7 @@ export function ChatPage() {
: undefined
}
quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}
+ annotations={annotations}
/>
) : (
<EmptyState
@@ -416,6 +423,7 @@ export function ChatPage() {
onProjectChange={changeProjectContext}
isProjectUpdating={c.isProjectUpdating}
focusRequest={c.focusInputRequest}
+ annotations={annotations}
/>
</div>
);
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index 43b6c341db..665742ee64 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -7,6 +7,7 @@ import type { DraftUpload } from "@multica/core/drafts";
import enCommon from "../../locales/en/common.json";
import enChat from "../../locales/en/chat.json";
import enEditor from "../../locales/en/editor.json";
+import enIssues from "../../locales/en/issues.json";
// Uploads flow through the module-level coordinator, which calls
// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2). Tests drive uploads by
@@ -54,7 +55,7 @@ function makeUpload(overrides: Partial<UploadResult> & { id: string; link: strin
};
}
-const TEST_RESOURCES = { en: { common: enCommon, chat: enChat, editor: enEditor } };
+const TEST_RESOURCES = { en: { common: enCommon, chat: enChat, editor: enEditor, issues: enIssues } };
// Track drop-zone callbacks so the test can simulate a real drop.
const dropHandlers = vi.hoisted(() => ({
@@ -248,6 +249,8 @@ vi.mock("@multica/core/chat", () => {
import { ChatInput } from "./chat-input";
import { useChatStore } from "@multica/core/chat";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { composeAnnotatedReply } from "@multica/core/drafts/reply-annotation";
type ChatInputOnSend = React.ComponentProps<typeof ChatInput>["onSend"];
type ChatInputCommit = Parameters<ChatInputOnSend>[2];
@@ -382,6 +385,68 @@ function element(props: Partial<React.ComponentProps<typeof ChatInput>>) {
);
}
+describe("ChatInput annotations", () => {
+ const key = "chat:session-1" as const;
+ const annotation = {
+ id: "ann-1", sourceCommentId: "msg-1", sourceActorName: "Multica",
+ quote: "Use the cache.", note: "Why not the DB?", start: 0, prefix: "", suffix: "",
+ };
+ const slot = { draftKey: key, composer: undefined, editAnnotation: () => true };
+ function lastButton() {
+ const buttons = screen.getAllByRole("button");
+ return buttons[buttons.length - 1]!;
+ }
+
+ beforeEach(() => {
+ (useChatStore.getState() as unknown as { activeSessionId: string | null }).activeSessionId = "session-1";
+ useCommentDraftStore.setState({ drafts: {} });
+ useCommentDraftStore.getState().addAnnotation(key, annotation);
+ });
+
+ it("sends saved annotations on their own, then drops the sent ones", async () => {
+ const onSend = vi.fn<ChatInputOnSend>((_content, _ids, commitInput) => {
+ commitInput();
+ return true;
+ });
+ renderInput({ onSend, annotations: slot });
+
+ expect(screen.getByRole("button", { name: "1 annotation" })).toBeInTheDocument();
+ await waitFor(() => expect(lastButton()).not.toBeDisabled());
+ fireEvent.click(lastButton());
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0]![0]).toBe(composeAnnotatedReply("", [annotation]));
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toEqual([]);
+ expect(screen.queryByRole("button", { name: "1 annotation" })).not.toBeInTheDocument();
+ });
+
+ it("quotes annotations ahead of the typed text and keeps them when the send is rejected", async () => {
+ const onSend = vi.fn<ChatInputOnSend>(() => false);
+ renderInput({ onSend, annotations: slot });
+
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "Also check retries" } });
+ fireEvent.click(lastButton());
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ const sent = onSend.mock.calls[0]![0];
+ expect(sent).toBe(composeAnnotatedReply("Also check retries", [annotation]));
+ expect(sent.startsWith("> Use the cache")).toBe(true);
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(1);
+ });
+
+ it("leaves sends untouched without an annotation slot", async () => {
+ const onSend = vi.fn<ChatInputOnSend>(() => true);
+ renderInput({ onSend });
+
+ fireEvent.change(screen.getByTestId("editor"), { target: { value: "plain" } });
+ fireEvent.click(lastButton());
+
+ await waitFor(() => expect(onSend).toHaveBeenCalledTimes(1));
+ expect(onSend.mock.calls[0]![0]).toBe("plain");
+ expect(useCommentDraftStore.getState().getAnnotations(key)).toHaveLength(1);
+ });
+});
+
// MUL-4864: an uncreated chat has ONE draft per workspace. `selectedAgentId`
// picks where the first send goes; it does not own the draft. Switching agent
// mid-compose must therefore change nothing the user can see.
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index 2c85f9cbb2..c7cd0b266c 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -31,6 +31,10 @@ import type { Attachment, Project } from "@multica/core/types";
import { ProjectPicker } from "../../projects/components/project-picker";
import { ClearablePillButton } from "../../common/pill-button";
import { useT } from "../../i18n";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";
+import { ReplyAnnotations } from "../../issues/components/reply-annotations";
+import type { ChatAnnotations } from "./use-chat-annotations";
const logger = createLogger("chat.ui");
const EMPTY_UPLOADS: DraftUpload[] = [];
@@ -146,6 +150,8 @@ interface ChatInputProps {
*/
draftKeyOverride?: string;
editorKeyOverride?: string;
+ /** Saved quotes from this session's replies, sent ahead of the typed text. */
+ annotations?: Pick<ChatAnnotations, "draftKey" | "composer" | "editAnnotation">;
}
export function ChatInput({
@@ -174,6 +180,7 @@ export function ChatInput({
focusRequest,
draftKeyOverride,
editorKeyOverride,
+ annotations: annotationSlot,
}: ChatInputProps) {
const { t } = useT("chat");
const { t: tEditor } = useT("editor");
@@ -228,7 +235,11 @@ export function ChatInput({
// restored or parked one, or any persisted draft the user typed in another
// session) still enables the button. A false enable costs nothing: handleSend
// reads the live editor and bails when it is empty.
- const hasNothingToSend = isEmpty && !inputDraft.trim();
+ const annotationDraftKey = annotationSlot?.draftKey;
+ const annotations = useCommentDraftStore((s) =>
+ annotationDraftKey ? s.getAnnotations(annotationDraftKey) : EMPTY_REPLY_ANNOTATIONS);
+ // Saved annotations always carry a note, so they are sendable on their own.
+ const hasNothingToSend = isEmpty && !inputDraft.trim() && annotations.length === 0;
const appliedRestoreIdRef = useRef<string | null>(null);
const appliedConversationStarterIdRef = useRef<number | null>(null);
const editorKey = editorKeyOverride ?? CHAT_COMPOSER_EDITOR_KEY;
@@ -453,8 +464,19 @@ export function ChatInput({
// the same place), except when the commit left the editor alone — see
// `editorScrubbedRef`.
afterAccepted: () => (editorScrubbedRef.current ? "refocus" : "none"),
+ normalize: (raw) => {
+ const current = annotationDraftKey
+ ? useCommentDraftStore.getState().getAnnotations(annotationDraftKey)
+ : EMPTY_REPLY_ANNOTATIONS;
+ return hasReplyIntent(raw, current) ? composeAnnotatedReply(raw, current) : "";
+ },
onSubmit: async (content: string): Promise<boolean> => {
editorScrubbedRef.current = false;
+ // Same tick as `normalize`, so this is exactly what `content` quotes.
+ const annotationKeyAtSend = annotationDraftKey;
+ const sentAnnotationIds = annotationKeyAtSend
+ ? useCommentDraftStore.getState().getAnnotations(annotationKeyAtSend).map((a) => a.id)
+ : [];
// These states disable the SubmitButton, but Mod+Enter bypasses it — so a
// read-only or busy composer must still refuse the keyboard path.
if (disabled || noAgent || (isRunning && !allowSubmitWhileRunning)) {
@@ -533,6 +555,12 @@ export function ChatInput({
for (const key of options?.extraDraftKeys ?? []) {
if (key !== keyAtSend) clearInputDraft(key);
}
+ // The quotes are in the sent message (and in any restore of it); only
+ // annotations saved during the request stay for the next turn.
+ if (annotationKeyAtSend) {
+ const store = useCommentDraftStore.getState();
+ for (const id of sentAnnotationIds) store.removeAnnotation(annotationKeyAtSend, id);
+ }
};
logger.info("input.send", {
contentLength: content.length,
@@ -629,8 +657,14 @@ export function ChatInput({
!submitting &&
!isProjectUpdating;
const selectedProject = projects.find((project) => project.id === projectId);
+ const canSubmitNow = !disabled && !noAgent && (!isRunning || !!allowSubmitWhileRunning);
return (
+ <>
+ {annotationSlot?.composer?.render(canSubmitNow ? {
+ submit, submitting, uploading: gate.uploading, restart: false,
+ recipients: null, draftContent: inputDraft, annotations,
+ } : undefined)}
<div
ref={composerRef}
className={cn(
@@ -677,6 +711,12 @@ export function ChatInput({
)}
aria-disabled={noAgent || undefined}
>
+ {annotationDraftKey && annotations.length > 0 && (
+ <div className="px-3 pt-2">
+ <ReplyAnnotations draftKey={annotationDraftKey} annotations={annotations} disabled={submitting}
+ onEditAnnotation={(id) => annotationSlot.editAnnotation(id, true)} />
+ </div>
+ )}
{selectedProject && (
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 px-3 pt-2">
<div
@@ -803,5 +843,6 @@ export function ChatInput({
{uploadEnabled && isDragOver && <FileDropOverlay />}
</div>
</div>
+ </>
);
}
diff --git a/packages/views/chat/components/chat-message-list.test.tsx b/packages/views/chat/components/chat-message-list.test.tsx
index e6fdf4060c..d41aee9472 100644
--- a/packages/views/chat/components/chat-message-list.test.tsx
+++ b/packages/views/chat/components/chat-message-list.test.tsx
@@ -397,6 +397,53 @@ describe("ChatMessageList live timeline (MUL-3960 regression)", () => {
expect(screen.getByText("3 steps")).toBeInTheDocument();
expect(screen.queryByText("Intermediate narration")).not.toBeInTheDocument();
});
+
+ it("marks only the settled answer as an annotation source, without remounting it", async () => {
+ const qc = new QueryClient();
+ qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
+ taskMsg(0, "tool_use", { tool: "Read", input: { path: "/tmp/x" } }),
+ taskMsg(1, "text", { content: "Stable final answer" }),
+ ]);
+ const revealSourceRef: { current: ((messageId: string) => boolean) | null } = { current: null };
+ const annotations = {
+ cardRef: () => {},
+ captureProps: {
+ "data-annotation-thread": "chat:session-1" as const,
+ onPointerUp: () => {}, onKeyUp: () => {}, onKeyDown: () => {},
+ },
+ popup: <></>,
+ revealSourceRef,
+ };
+ const view = (
+ messages: Parameters<typeof ChatMessageList>[0]["messages"],
+ pendingTask: Parameters<typeof ChatMessageList>[0]["pendingTask"],
+ ) => (
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <QueryClientProvider client={qc}>
+ <ChatMessageList messages={messages} pendingTask={pendingTask} availability="online" annotations={annotations} />
+ </QueryClientProvider>
+ </I18nProvider>
+ );
+
+ const { rerender, container } = render(view([], { task_id: TASK_ID, status: "running" }));
+ const answerBefore = await screen.findByText("Stable final answer");
+ expect(container.querySelector("[data-comment-content]")).toBeNull();
+ expect(revealSourceRef.current?.("persisted-answer")).toBe(false);
+
+ rerender(view([{
+ id: "persisted-answer",
+ chat_session_id: "session-1",
+ role: "assistant",
+ content: "Stable final answer",
+ task_id: TASK_ID,
+ created_at: "2026-09-17T00:00:00Z",
+ }], null));
+
+ const answer = await screen.findByText("Stable final answer");
+ expect(answer).toBe(answerBefore);
+ expect(answer.closest("[data-comment-content]")?.getAttribute("data-comment-content")).toBe("persisted-answer");
+ expect(answer.closest("[data-annotation-thread]")).not.toBeNull();
+ });
});
describe("ChatMessageList tool rows (#8835 regression)", () => {
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index 9a627e1bb4..3d2f29da58 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -59,6 +59,7 @@ import {
} from "../lib/copy-text";
import { stripChatQuickActionsProtocol } from "../lib/quick-actions";
import { useT } from "../../i18n";
+import { isAnnotatableChatMessage, type ChatAnnotations } from "./use-chat-annotations";
// ─── Public component ────────────────────────────────────────────────────
@@ -103,6 +104,8 @@ interface ChatMessageListProps {
* that reply until chat:quick_actions resolves it.
*/
quickActionsPendingMessageId?: string | null;
+ /** Lets the reader annotate settled assistant replies into the next message. */
+ annotations?: Pick<ChatAnnotations, "cardRef" | "captureProps" | "popup" | "revealSourceRef">;
}
// ─── Virtuoso chrome ─────────────────────────────────────────────────────
@@ -202,6 +205,7 @@ export function ChatMessageList({
quickActionsDisabled = false,
onRegenerateQuickActions,
quickActionsPendingMessageId = null,
+ annotations,
}: ChatMessageListProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const [scrollContainerEl, setScrollContainerEl] = useState<HTMLDivElement | null>(null);
@@ -216,7 +220,7 @@ export function ChatMessageList({
const pinToLiveEnd = useCallback(() => {
virtuosoRef.current?.scrollToIndex({ index: "LAST", align: "end" });
}, []);
- const { isFollowing, onContentHeightChanged, hasReachedLiveEnd } = useStickToBottom(
+ const { isFollowing, onContentHeightChanged, disengage, hasReachedLiveEnd } = useStickToBottom(
scrollContainerEl,
pinToLiveEnd,
active,
@@ -296,6 +300,19 @@ export function ChatMessageList({
return items;
}, [messages, hasLive, pendingTaskId]);
+ const revealSourceRef = annotations?.revealSourceRef;
+ useEffect(() => {
+ if (!revealSourceRef) return;
+ revealSourceRef.current = (messageId) => {
+ const index = renderItems.findIndex((item) => item.kind === "message" && item.message.id === messageId);
+ if (index < 0) return false;
+ disengage();
+ virtuosoRef.current?.scrollToIndex({ index, align: "center" });
+ return true;
+ };
+ return () => { revealSourceRef.current = null; };
+ }, [revealSourceRef, renderItems, disengage]);
+
const firstIndex = renderItems.length > 0 ? firstItemIndex : 0;
const tailItem = renderItems[renderItems.length - 1];
const liveEndKey = tailItem?.key ?? null;
@@ -340,7 +357,8 @@ export function ChatMessageList({
<PreviewSequenceProvider items={previewSequence}>
{/* Positioning box for the floating "Jump to latest" button, so it stays
* pinned above the composer instead of scrolling with the rows. */}
- <div className="relative flex min-h-0 flex-1 flex-col">
+ <div ref={annotations?.cardRef} {...annotations?.captureProps} className="relative flex min-h-0 flex-1 flex-col">
+ {annotations?.popup}
<div
ref={setScrollContainerRef}
data-tab-scroll-root
@@ -421,6 +439,7 @@ export function ChatMessageList({
latestAssistantMessageId={latestAssistantMessageId}
quickActionsPendingMessageId={quickActionsPendingMessageId}
starterCardsMessageId={starterCardsMessageId}
+ annotatable={!!annotations}
/>
</div>
)}
@@ -494,6 +513,7 @@ const MessageBubble = memo(function MessageBubble({
latestAssistantMessageId,
quickActionsPendingMessageId,
starterCardsMessageId,
+ annotatable,
}: {
item: ChatRenderItem;
isPending: boolean;
@@ -504,6 +524,7 @@ const MessageBubble = memo(function MessageBubble({
latestAssistantMessageId: string | null;
quickActionsPendingMessageId: string | null;
starterCardsMessageId: string | null;
+ annotatable: boolean;
}) {
// The live row and the persisted assistant row both land here under one key,
// and both render <AssistantMessage> — same component type, same position —
@@ -559,6 +580,7 @@ const MessageBubble = memo(function MessageBubble({
canRegenerateQuickActions={message.id === latestAssistantMessageId}
quickActionsPending={quickActionsPendingMessageId === message.id}
showStarterCards={message.id === starterCardsMessageId}
+ sourceId={annotatable && isAnnotatableChatMessage(message) ? message.id : undefined}
/>
);
});
@@ -591,6 +613,7 @@ function AssistantMessage({
canRegenerateQuickActions = false,
quickActionsPending = false,
showStarterCards = false,
+ sourceId,
}: {
taskId: string | null;
message?: ChatMessage;
@@ -603,6 +626,8 @@ function AssistantMessage({
quickActionsPending?: boolean;
/** This turn is Mika's onboarding opening — render starter cards, not chips. */
showStarterCards?: boolean;
+ /** Annotation source id for the settled answer text. */
+ sourceId?: string;
}) {
const canFetchTaskMessages = isTaskMessageTaskId(taskId);
@@ -663,18 +688,21 @@ function AssistantMessage({
phase={phase}
isStreaming={!message}
settledContent={canonicalAnswer}
+ sourceId={sourceId}
/>
)}
{isNoResponse ? (
<NoResponseNotice />
) : message && timeline.length === 0 ? (
- <RichContent
- content={settledContent ?? message.content}
- attachments={message.attachments}
- density="compact"
- phase="settled"
- className="leading-relaxed"
- />
+ <div data-comment-content={sourceId}>
+ <RichContent
+ content={settledContent ?? message.content}
+ attachments={message.attachments}
+ density="compact"
+ phase="settled"
+ className="leading-relaxed"
+ />
+ </div>
) : null}
{message && (
<>
@@ -1121,12 +1149,14 @@ function TimelineView({
attachments,
phase = "settled",
settledContent,
+ sourceId,
}: {
items: ChatTimelineItem[];
isStreaming?: boolean;
attachments?: import("@multica/core/types").Attachment[];
phase?: "streaming" | "settled";
settledContent?: string;
+ sourceId?: string;
}) {
if (phase === "settled" && settledContent !== undefined) {
const { preface, middle } = splitTimeline(items);
@@ -1143,14 +1173,15 @@ function TimelineView({
stepCount={middle.length}
/>
)}
- <RichContent
- key="answer"
- content={settledContent}
- attachments={attachments}
- density="compact"
- phase="settled"
- className="leading-relaxed"
- />
+ <div key="answer" data-comment-content={sourceId}>
+ <RichContent
+ content={settledContent}
+ attachments={attachments}
+ density="compact"
+ phase="settled"
+ className="leading-relaxed"
+ />
+ </div>
</>
);
}
@@ -1179,14 +1210,16 @@ function TimelineView({
/>
)}
{final.length > 0 && (
- <RichContent
- key="answer"
- content={final.map((t) => t.content ?? "").join("")}
- attachments={attachments}
- density="compact"
- phase={phase}
- className="leading-relaxed"
- />
+ // Same element type as the settled answer so the handoff keeps it mounted.
+ <div key="answer">
+ <RichContent
+ content={final.map((t) => t.content ?? "").join("")}
+ attachments={attachments}
+ density="compact"
+ phase={phase}
+ className="leading-relaxed"
+ />
+ </div>
)}
</>
);
diff --git a/packages/views/chat/components/chat-window-messages.tsx b/packages/views/chat/components/chat-window-messages.tsx
index 1454bd1bd5..23fe6e9e4a 100644
--- a/packages/views/chat/components/chat-window-messages.tsx
+++ b/packages/views/chat/components/chat-window-messages.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, type ReactNode } from "react";
+import { useEffect, type ComponentProps, type ReactNode } from "react";
import { useInfiniteQuery } from "@tanstack/react-query";
import { motion, useIsPresent } from "motion/react";
import type { AgentAvailability } from "@multica/core/agents";
@@ -22,6 +22,7 @@ export function ChatWindowMessages({
quickActionsDisabled,
quickActionsPendingMessageId,
onReady,
+ annotations,
children,
}: {
sessionId: string | null;
@@ -33,6 +34,7 @@ export function ChatWindowMessages({
quickActionsPendingMessageId: string | null;
/** This area has something to show — the window can fade in around it. */
onReady?: () => void;
+ annotations?: ComponentProps<typeof ChatMessageList>["annotations"];
children: ReactNode;
}) {
const isPresent = useIsPresent();
@@ -94,6 +96,7 @@ export function ChatWindowMessages({
? regenerateQuickActions.mutateAsync({ sessionId, messageId: message.id })
: undefined}
quickActionsPendingMessageId={quickActionsPendingMessageId}
+ annotations={annotations}
/>
) : children}
</motion.div>
diff --git a/packages/views/chat/components/chat-window.tsx b/packages/views/chat/components/chat-window.tsx
index 17422447af..341b1bbf9e 100644
--- a/packages/views/chat/components/chat-window.tsx
+++ b/packages/views/chat/components/chat-window.tsx
@@ -73,6 +73,7 @@ import { useChatInputFocus } from "./use-chat-input-focus";
import { useChatOpenReveal } from "./use-chat-open-reveal";
import { ChatWindowMessages } from "./chat-window-messages";
import { ChatInput } from "./chat-input";
+import { useChatAnnotations } from "./use-chat-annotations";
import { ChatQueue } from "./chat-queue";
import { ChatAppRequests } from "../../common/app-requests";
import { EmptyState } from "./chat-empty-state";
@@ -261,6 +262,11 @@ export function ChatWindow() {
// (server confirmed: zero usable agents) drives the disabled UI.
const agentAvailability = useWorkspaceAgentAvailability();
const noAgent = agentAvailability === "none";
+ const annotations = useChatAnnotations({
+ sessionId: activeSessionId,
+ agentName: activeAgent?.name,
+ enabled: !isSessionArchived && !isAgentArchived && !isAgentAccessRevoked && activeAgentRuntimeBound && !noAgent,
+ });
// Presence drives both the avatar status dot (via ActorAvatar) and the
// OfflineBanner / TaskStatusPill availability copy. `useAgentPresenceDetail`
@@ -920,6 +926,7 @@ export function ChatWindow() {
}
quickActionsPendingMessageId={quickActionsPending?.message_id ?? null}
onReady={markContentReady}
+ annotations={annotations}
>
<EmptyState
agent={activeAgent}
@@ -1010,6 +1017,7 @@ export function ChatWindow() {
}
contextItems={contextItems}
focusRequest={focusRequest}
+ annotations={annotations}
/>
</motion.div>
);
diff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.ts
index 4dad8bc280..67127c3d82 100644
--- a/packages/views/chat/components/stick-to-bottom.ts
+++ b/packages/views/chat/components/stick-to-bottom.ts
@@ -130,6 +130,8 @@ export interface StickToBottom {
isFollowing(): boolean;
/** Wire to Virtuoso's `totalListHeightChanged`: the content resized. */
onContentHeightChanged(): void;
+ /** Release the follow before scrolling to an older row on the reader's behalf. */
+ disengage(): void;
/**
* False until the newest message has actually arrived at the bottom of the
* viewport. Keep the list hidden until then: Virtuoso opens it by scrolling
@@ -354,6 +356,7 @@ export function useStickToBottom(
() => ({
isFollowing: () => follow.isFollowing(),
onContentHeightChanged: onResize,
+ disengage: () => follow.disengage(),
hasReachedLiveEnd,
}),
[follow, onResize, hasReachedLiveEnd],
diff --git a/packages/views/chat/components/use-chat-annotations.test.tsx b/packages/views/chat/components/use-chat-annotations.test.tsx
new file mode 100644
index 0000000000..c3c01014ec
--- /dev/null
+++ b/packages/views/chat/components/use-chat-annotations.test.tsx
@@ -0,0 +1,131 @@
+import { act, fireEvent, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useState, type ReactElement } from "react";
+import { QueryClient, QueryClientProvider, useInfiniteQuery } from "@tanstack/react-query";
+import { chatKeys, chatMessagesPageOptions } from "@multica/core/chat/queries";
+import { useCommentDraftStore } from "@multica/core/issues/stores";
+import type { ChatMessage, ChatMessagesPage } from "@multica/core/types";
+import { toast } from "sonner";
+import { renderWithI18n } from "../../test/i18n";
+import { ChatMessageList } from "./chat-message-list";
+import { useChatAnnotations } from "./use-chat-annotations";
+
+vi.mock("sonner", () => ({ toast: { error: vi.fn() } }));
+
+const listChatMessagesPage = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/api", async (original) => {
+ const actual = await original<typeof import("@multica/core/api")>();
+ return { ...actual, api: { ...actual.api, listChatMessagesPage } };
+});
+
+// jsdom never lays out Virtuoso rows; render every row like the list tests do.
+vi.mock("react-virtuoso", () => ({
+ Virtuoso: ({ data, itemContent, computeItemKey }: {
+ data: unknown[];
+ itemContent: (i: number, item: unknown) => ReactElement;
+ computeItemKey: (i: number, item: unknown) => string;
+ }) => <div>{data.map((item, i) => <div key={computeItemKey(i, item)}>{itemContent(i, item)}</div>)}</div>,
+}));
+
+vi.mock("../../editor/content-editor", async () => {
+ const { forwardRef, useRef, useImperativeHandle } = await import("react");
+ return { ContentEditor: forwardRef(function Editor({ defaultValue, ariaLabel }: {
+ defaultValue?: string; ariaLabel?: string;
+ }, ref) {
+ const input = useRef<HTMLTextAreaElement>(null);
+ useImperativeHandle(ref, () => ({
+ getMarkdown: () => input.current?.value ?? "",
+ focus: () => input.current?.focus(), hasActiveUploads: () => false,
+ }));
+ return <textarea ref={input} aria-label={ariaLabel} defaultValue={defaultValue} />;
+ }) };
+});
+
+const SESSION = "session-1";
+const key = `chat:${SESSION}` as const;
+
+function assistant(id: string, content: string, createdAt: string): ChatMessage {
+ return { id, chat_session_id: SESSION, role: "assistant", content, task_id: null, created_at: createdAt } as ChatMessage;
+}
+
+const newest: ChatMessagesPage = {
+ messages: [assistant("msg-new", "Newest answer", "2026-11-10T02:00:00Z")],
+ limit: 50,
+ has_more: true,
+ next_cursor: { created_at: "2026-11-10T02:00:00Z", id: "msg-new" },
+};
+const older: ChatMessagesPage = {
+ messages: [assistant("msg-old", "Old answer text", "2026-11-10T01:00:00Z")],
+ limit: 50,
+ has_more: false,
+};
+
+function Harness() {
+ const annotations = useChatAnnotations({ sessionId: SESSION, agentName: "Agent", enabled: true });
+ const { data } = useInfiniteQuery(chatMessagesPageOptions(SESSION));
+ const messages = [...(data?.pages ?? [])].reverse().flatMap((page) => page.messages);
+ return <>
+ <ChatMessageList messages={messages} pendingTask={null} availability="online" annotations={annotations} />
+ {annotations.composer?.render()}
+ <button onClick={() => annotations.editAnnotation("ann-old", true)}>Open saved annotation</button>
+ </>;
+}
+
+function renderHarness() {
+ function Root() {
+ const [client] = useState(() => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ qc.setQueryData(chatKeys.messagesPage(SESSION), { pages: [newest], pageParams: [null] });
+ return qc;
+ });
+ return <QueryClientProvider client={client}><Harness /></QueryClientProvider>;
+ }
+ return renderWithI18n(<Root />);
+}
+
+describe("useChatAnnotations", () => {
+ beforeEach(() => {
+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 10, 600, 400));
+ Range.prototype.getBoundingClientRect = vi.fn(() => new DOMRect(10, 10, 120, 20));
+ Element.prototype.scrollIntoView = vi.fn();
+ listChatMessagesPage.mockReset();
+ vi.mocked(toast.error).mockClear();
+ // A restored draft: the quoted reply is not in the newest page.
+ useCommentDraftStore.setState({ drafts: {} });
+ useCommentDraftStore.getState().addAnnotation(key, {
+ id: "ann-old", sourceCommentId: "msg-old", sourceActorName: "Agent",
+ quote: "Old answer", note: "Saved note", start: 0, prefix: "", suffix: " text",
+ });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("loads the older page holding a restored annotation's source, then opens its note", async () => {
+ listChatMessagesPage.mockResolvedValue(older);
+ renderHarness();
+ expect(await screen.findByText("Newest answer")).toBeInTheDocument();
+ expect(screen.queryByText("Old answer text")).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Open saved annotation" }));
+
+ // jsdom gives the list's scroll container a zero clip rect, so the popup
+ // stays visibility:hidden and has no accessible name; query by label.
+ expect(await screen.findByLabelText("Comment")).toHaveValue("Saved note");
+ expect(listChatMessagesPage).toHaveBeenCalledTimes(1);
+ expect(listChatMessagesPage).toHaveBeenCalledWith(SESSION, expect.objectContaining({ before: newest.next_cursor }));
+ expect(screen.getByText("Old answer text")).toBeInTheDocument();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("reports the source as unavailable once history runs out without it", async () => {
+ listChatMessagesPage.mockResolvedValue({ ...older, messages: [assistant("msg-other", "Other", "2026-11-10T01:00:00Z")] });
+ renderHarness();
+ await screen.findByText("Newest answer");
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Open saved annotation" }));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
+ expect(screen.queryByLabelText("Comment")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/views/chat/components/use-chat-annotations.ts b/packages/views/chat/components/use-chat-annotations.ts
new file mode 100644
index 0000000000..133e6436e8
--- /dev/null
+++ b/packages/views/chat/components/use-chat-annotations.ts
@@ -0,0 +1,121 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { useInfiniteQuery, type InfiniteData, type UseInfiniteQueryResult } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { chatMessagesPageOptions } from "@multica/core/chat/queries";
+import { useCommentDraftStore, type CommentDraftKey } from "@multica/core/issues/stores";
+import type { ChatMessage, ChatMessagesPage } from "@multica/core/types";
+import { useCommentAnnotations } from "../../issues/components/use-comment-annotations";
+import { useT } from "../../i18n";
+
+/** Persisted assistant answers are the only annotatable chat text. */
+export function isAnnotatableChatMessage(message: ChatMessage): boolean {
+ return message.role === "assistant" && !message.failure_reason &&
+ message.message_kind !== "no_response" && !!message.content.trim();
+}
+
+/**
+ * Registered by the message list: releases the bottom follow and scrolls the
+ * message's row into Virtuoso's window. False when the message is not listed.
+ */
+type RevealChatMessage = (messageId: string) => boolean;
+
+const REVEAL_RETRY_FRAMES = 30;
+
+type MessagesQuery = UseInfiniteQueryResult<InfiniteData<ChatMessagesPage>>;
+
+function hasMessage(pages: readonly ChatMessagesPage[] | undefined, messageId: string): boolean {
+ return !!pages?.some((page) => page.messages.some((message) => message.id === messageId));
+}
+
+/** Page older history in until the message is loaded or history runs out. */
+async function loadOlderUntil(query: MessagesQuery, messageId: string): Promise<boolean> {
+ let result = query;
+ while (!hasMessage(result.data?.pages, messageId) && result.hasNextPage) {
+ // Join a page load the list already started rather than cancelling it.
+ result = await result.fetchNextPage({ cancelRefetch: false });
+ if (result.isFetchNextPageError) return false;
+ }
+ return hasMessage(result.data?.pages, messageId);
+}
+
+export type ChatAnnotations = ReturnType<typeof useChatAnnotations>;
+
+/** Issue reply annotations, sourced from one chat session's assistant replies. */
+export function useChatAnnotations({ sessionId, agentName, enabled }: {
+ sessionId: string | null;
+ agentName: string | undefined;
+ enabled: boolean;
+}) {
+ const { t } = useT("issues");
+ const query = useInfiniteQuery(chatMessagesPageOptions(sessionId ?? ""));
+ const queryRef = useRef(query);
+ queryRef.current = query;
+ const pages = sessionId ? query.data?.pages : undefined;
+ const sources = useMemo(
+ () => (pages ?? []).flatMap((page) => page.messages)
+ .filter(isAnnotatableChatMessage)
+ .map((message) => ({ id: message.id, name: agentName ?? "" })),
+ [pages, agentName],
+ );
+ const draftKey: CommentDraftKey = `chat:${sessionId ?? ""}`;
+ // The floating chat window is z-50; markers default below it.
+ const annotations = useCommentAnnotations({ draftKey, sources, enabled: enabled && !!sessionId, markerZIndex: 50 });
+ const revealSourceRef = useRef<RevealChatMessage | null>(null);
+ const editRef = useRef(annotations.editAnnotation);
+ editRef.current = annotations.editAnnotation;
+ const retryFrame = useRef<number | null>(null);
+ // Bumped by every navigation so a slow page load cannot open a stale note.
+ const attemptRef = useRef(0);
+ const cancelRetry = useCallback(() => {
+ attemptRef.current += 1;
+ if (retryFrame.current !== null) cancelAnimationFrame(retryFrame.current);
+ retryFrame.current = null;
+ }, []);
+ useEffect(() => cancelRetry, [draftKey, cancelRetry]);
+
+ // Rows mount a frame or more after their data lands, and virtualized rows
+ // leave the DOM once scrolled away: retry until the source can anchor.
+ const openWhenMounted = useCallback((id: string, messageId: string, revealed: boolean) => {
+ const attempt = attemptRef.current;
+ let frames = 0;
+ const retry = () => {
+ retryFrame.current = null;
+ if (attempt !== attemptRef.current) return;
+ if (!revealed) revealed = !!revealSourceRef.current?.(messageId);
+ if (revealed && editRef.current(id, true)) return;
+ if (++frames >= REVEAL_RETRY_FRAMES) {
+ toast.error(t(($) => $.reply.annotations.source_changed));
+ return;
+ }
+ retryFrame.current = requestAnimationFrame(retry);
+ };
+ retryFrame.current = requestAnimationFrame(retry);
+ }, [t]);
+
+ const editAnnotation = useCallback((id: string, scrollToSource = false): boolean => {
+ cancelRetry();
+ const annotation = useCommentDraftStore.getState().getAnnotations(draftKey).find((a) => a.id === id);
+ if (!annotation) return false;
+ if (!scrollToSource) return editRef.current(id);
+ const messageId = annotation.sourceCommentId;
+ // A restored draft can quote a reply older than the pages loaded so far.
+ if (!hasMessage(queryRef.current.data?.pages, messageId)) {
+ if (!queryRef.current.hasNextPage) return editRef.current(id, true);
+ const attempt = attemptRef.current;
+ void loadOlderUntil(queryRef.current, messageId).then((found) => {
+ if (attempt !== attemptRef.current) return;
+ if (found) openWhenMounted(id, messageId, false);
+ else toast.error(t(($) => $.reply.annotations.source_changed));
+ });
+ return true;
+ }
+ if (!revealSourceRef.current?.(messageId)) return editRef.current(id, true);
+ if (editRef.current(id, true)) return true;
+ openWhenMounted(id, messageId, true);
+ return true;
+ }, [draftKey, t, cancelRetry, openWhenMounted]);
+
+ return { ...annotations, draftKey, editAnnotation, revealSourceRef };
+}
diff --git a/packages/views/issues/components/annotation-composer.tsx b/packages/views/issues/components/annotation-composer.tsx
index ac4ab695ae..8fcd4e4183 100644
--- a/packages/views/issues/components/annotation-composer.tsx
+++ b/packages/views/issues/components/annotation-composer.tsx
@@ -41,7 +41,7 @@ export function AnnotationComposer({
issueId, owner, annotation, existing, number, editorRef, controls,
sourceMissing, sourceChanged, canSave, onChange, onSave, onRemove, onBusyChange,
}: {
- issueId: string;
+ issueId?: string;
owner: string;
annotation: ReplyAnnotation;
existing: boolean;
diff --git a/packages/views/issues/components/comment-selection-bubble.tsx b/packages/views/issues/components/comment-selection-bubble.tsx
index 876bcdc8ce..57e2aa5f24 100644
--- a/packages/views/issues/components/comment-selection-bubble.tsx
+++ b/packages/views/issues/components/comment-selection-bubble.tsx
@@ -5,12 +5,13 @@ import { createPortal } from "react-dom";
import { autoUpdate, computePosition, flip, hide, offset, shift } from "@floating-ui/dom";
/** Match the description's EditorBubbleMenu geometry for readonly selections. */
-export function CommentSelectionBubble({ range, source, children, owner, markerRanges, onPositioned, keepVisibleWhenDetached = false }: {
+export function CommentSelectionBubble({ range, source, children, owner, markerRanges, markerZIndex = 20, onPositioned, keepVisibleWhenDetached = false }: {
range: Range;
source: HTMLElement;
children: ReactNode;
owner: string;
markerRanges?: Range[];
+ markerZIndex?: number;
/** Called after the popup has a visible, usable position. */
onPositioned?: () => void;
keepVisibleWhenDetached?: boolean;
@@ -70,7 +71,7 @@ export function CommentSelectionBubble({ range, source, children, owner, markerR
return createPortal(
<div ref={ref} data-reply-annotation-overlay={owner} data-editor-overlay-owner={owner}
- style={{ position: "fixed", zIndex: marker ? 20 : 50, visibility: "hidden", width: "max-content" }}>
+ style={{ position: "fixed", zIndex: marker ? markerZIndex : 50, visibility: "hidden", width: "max-content" }}>
{children}
</div>,
document.body,
diff --git a/packages/views/issues/components/use-comment-annotations.tsx b/packages/views/issues/components/use-comment-annotations.tsx
index 69febbda61..d2e0b2a698 100644
--- a/packages/views/issues/components/use-comment-annotations.tsx
+++ b/packages/views/issues/components/use-comment-annotations.tsx
@@ -17,8 +17,8 @@ import type { ContentEditorRef } from "../../editor/content-editor";
type CapturedSelection = NonNullable<ReturnType<typeof captureCommentSelection>>;
type SourceAnchor = { id: string; range: Range; root: HTMLElement };
-export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onAdded, onOpen, editable = false }: {
- issueId: string;
+export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onAdded, onOpen, editable = false, markerZIndex }: {
+ issueId?: string;
draftKey: CommentDraftKey;
sources: { id: string; name: string; revision?: number }[];
enabled: boolean;
@@ -26,9 +26,18 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
/** Editable descriptions use their existing toolbar to call addSelection. */
editable?: boolean;
onOpen?: () => void;
+ /** Markers must stack above a floating host such as the chat window. */
+ markerZIndex?: number;
}) {
const { t } = useT("issues");
- const cardRef = useRef<HTMLDivElement>(null);
+ const cardRef = useRef<HTMLDivElement | null>(null);
+ // The source container may mount after this hook (chat lists render behind
+ // a skeleton), so anchoring must re-run when it appears.
+ const [card, setCard] = useState<HTMLDivElement | null>(null);
+ const setCardRef = useCallback((node: HTMLDivElement | null) => {
+ cardRef.current = node;
+ setCard(node);
+ }, []);
const inputRef = useRef<ContentEditorRef>(null);
const submittingRef = useRef<string | null>(null);
const pendingFocusId = useRef<string | null>(null);
@@ -137,8 +146,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
setAnchors((current) => current.length ? [] : current);
return;
}
- if (!cardRef.current) return;
- const card = cardRef.current;
+ if (!card) return;
const canHighlight = typeof Highlight !== "undefined" && typeof CSS !== "undefined" && !!CSS.highlights;
const update = () => {
const next = annotationsRef.current.flatMap((a) => {
@@ -178,7 +186,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
});
observer.observe(card, { childList: true, subtree: true, characterData: true });
return () => { observer.disconnect(); if (canHighlight) CSS.highlights.delete(highlightName); };
- }, [anchorKey, highlightName, draftKey, editable, enabled, editingId]);
+ }, [anchorKey, highlightName, draftKey, editable, enabled, editingId, card]);
useEffect(() => {
if (!selection || (editor?.existing && !annotations.some((a) => a.id === editingId))) {
@@ -285,7 +293,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
};
return {
- cardRef,
+ cardRef: setCardRef,
editAnnotation,
addSelection,
composer: editing ? { pending: editing, render: renderComposer } : undefined,
@@ -311,7 +319,7 @@ export function useCommentAnnotations({ issueId, draftKey, sources, enabled, onA
const index = annotations.findIndex((a) => a.id === anchor.id);
if (index < 0) return null;
return <CommentSelectionBubble key={anchor.id} range={anchor.range} source={anchor.root} owner={draftKey}
- markerRanges={markerRanges.get(anchor.root)}>
+ markerRanges={markerRanges.get(anchor.root)} markerZIndex={markerZIndex}>
<IconButton variant="brandSubtle" size="icon-sm" className="size-6 text-caption tabular-nums aria-expanded:ring-2 aria-expanded:ring-brand"
aria-expanded={editingId === anchor.id}
label={t(($) => $.reply.annotations.edit, { number: index + 1 })}