diff --git a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx index 9280b9cbc065c..250b83fecdd83 100644 --- a/apps/web/src/components/chat/AssistantSelectionToolbar.tsx +++ b/apps/web/src/components/chat/AssistantSelectionToolbar.tsx @@ -2,9 +2,13 @@ import { ASSISTANT_CITATION_MAX_TEXT_LENGTH, MessageId, type AssistantCitation, + type OrchestrationV2ProjectedTurnItem, + type RunId, type ScopedThreadRef, + type ThreadId, } from "@t3tools/contracts"; -import { QuoteIcon } from "lucide-react"; +import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; +import { GitForkIcon, QuoteIcon } from "lucide-react"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { @@ -17,24 +21,41 @@ import { resolveSelectionActionPosition, type SelectionActionPoint, } from "~/lib/selectionActions"; +import { useV2ItemSupport } from "~/state/v2ItemSupport"; +import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; +type ForkFromRun = (input: { + readonly sourceThreadId: ThreadId; + readonly runId: RunId; + readonly citation?: AssistantCitation; +}) => Promise; + export function AssistantSelectionToolbar({ viewport, threadRef, onCite, + findProjectedItem, + onForkFromRun, }: { viewport: HTMLElement | null; threadRef: ScopedThreadRef; onCite: (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => boolean; + findProjectedItem?: (messageId: MessageId) => OrchestrationV2ProjectedTurnItem | undefined; + onForkFromRun?: ForkFromRun | undefined; }) { const [selection, setSelection] = useState<{ citation: AssistantCitation; position: SelectionActionPoint; sourceAnchor: AssistantCitationSourceAnchor; } | null>(null); - const toolbarRef = useRef(null); + const [forking, setForking] = useState(false); + const toolbarRef = useRef(null); const actionsRef = useRef | null>(null); + const tooLong = + selection !== null && selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH; + const projectedItem = + selection === null || tooLong ? undefined : findProjectedItem?.(selection.citation.messageId); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the toolbar DOM node and clamps its position inside the window before paint useLayoutEffect(() => { @@ -43,7 +64,8 @@ export function AssistantSelectionToolbar({ const rect = toolbar.getBoundingClientRect(); toolbar.style.left = `${Math.max(8, Math.min(selection.position.x, window.innerWidth - rect.width - 8))}px`; toolbar.style.top = `${Math.max(8, Math.min(selection.position.y, window.innerHeight - rect.height - 8))}px`; - }, [selection]); + // No deps: Follow up can appear or vanish without a new selection, changing the width. + }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to document selectionchange and keydown to track text selections in the viewport useEffect(() => { @@ -158,10 +180,11 @@ export function AssistantSelectionToolbar({ ) { return; } - if (toolbar.disabled) return; + const action = toolbar.querySelector("button:not(:disabled)"); + if (!action) return; event.preventDefault(); event.stopPropagation(); - toolbar.focus({ preventScroll: true }); + action.focus({ preventScroll: true }); }; document.addEventListener("keydown", focusActions, true); document.addEventListener("selectionchange", actions.selectionChanged); @@ -174,7 +197,6 @@ export function AssistantSelectionToolbar({ }, [threadRef, viewport]); if (!selection) return null; - const tooLong = selection.citation.text.length > ASSISTANT_CITATION_MAX_TEXT_LENGTH; const dismiss = () => { actionsRef.current?.cancel(); setSelection(null); @@ -186,17 +208,11 @@ export function AssistantSelectionToolbar({ return true; }; return createPortal( - , + + {projectedItem && onForkFromRun ? ( + { + setForking(true); + void onForkFromRun({ + sourceThreadId: projectedItem.sourceThreadId, + runId, + citation: selection.citation, + }).finally(() => { + setForking(false); + window.getSelection()?.removeAllRanges(); + dismiss(); + }); + }} + /> + ) : null} + , document.body, ); } + +function FollowUpButton({ + environmentId, + projectedItem, + busy, + onFollowUp, +}: { + environmentId: ScopedThreadRef["environmentId"]; + projectedItem: OrchestrationV2ProjectedTurnItem; + busy: boolean; + onFollowUp: (runId: RunId) => void; +}) { + const support = useV2ItemSupport({ + environmentId, + sourceThreadId: projectedItem.sourceThreadId, + sourceItemId: projectedItem.sourceItemId, + }); + const runId = projectedItem.item.runId; + if ( + runId === null || + !canForkProjectedAssistantItem({ + projectedItem, + capabilities: support.providerSession?.capabilities, + }) + ) { + return null; + } + return ( + + ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 212f3e253ce01..4144b2f9fe997 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -532,7 +532,87 @@ const CITATION_REQUEST = { }, } satisfies NonNullable; +function forkableAnswer(): Entry { + const runId = RunId.make("run-answer"); + const entry = message("the selected answer", { role: "assistant", runId }, "answer"); + const itemId = TurnItemId.make("item-answer"); + const now = DateTime.makeUnsafe(CREATED_AT); + if (entry.kind !== "message") throw new Error("Expected a message entry"); + return { + ...entry, + projectedItem: { + position: 0, + visibility: "local", + sourceThreadId: ThreadId.make("thread-source"), + sourceItemId: itemId, + item: { + id: itemId, + threadId: ThreadId.make("thread-source"), + runId, + nodeId: "node-answer" as never, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "assistant_message", + messageId: MessageId.make("answer"), + text: "the selected answer", + streaming: false, + }, + }, + }; +} + +async function selectAssistantText() { + const source = document.querySelector("[data-assistant-citation-source]"); + if (!source) throw new Error("Missing assistant citation source"); + window.getSelection()?.selectAllChildren(source); + await expect + .element(page.getByRole("button", { name: "Cite selection in composer" })) + .toBeVisible(); +} + describe("MessagesTimeline citations", () => { + it("follows up on a selection by forking its response with the selection cited", async () => { + const onForkFromRun = vi.fn(async () => {}); + await using _screen = await renderTimeline([forkableAnswer()], { + onCiteAssistantText: () => true, + onForkFromRun, + }); + await selectAssistantText(); + await page.getByRole("button", { name: "Follow up in a fork of this response" }).click(); + expect(onForkFromRun).toHaveBeenCalledWith({ + sourceThreadId: ThreadId.make("thread-source"), + runId: RunId.make("run-answer"), + citation: expect.objectContaining({ + messageId: MessageId.make("answer"), + text: "the selected answer", + }), + }); + }); + + it("offers no follow-up on a finished message while its run is still active", async () => { + await using _screen = await renderTimeline([forkableAnswer()], { + onCiteAssistantText: () => true, + latestRun: { + runId: RunId.make("run-answer"), + status: "running", + startedAt: CREATED_AT, + completedAt: null, + }, + }); + await selectAssistantText(); + await expect + .element(page.getByRole("button", { name: "Follow up in a fork of this response" })) + .not.toBeInTheDocument(); + }); + it("lands a citation present at mount under StrictMode", async () => { await using _screen = await renderElement( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 8c779ee950d67..b2935b62ae391 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -262,6 +262,8 @@ interface MessagesTimelineProps { onForkFromRun?: (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId; + /** Pre-fills the fork's composer with this citation. */ + readonly citation?: AssistantCitation; }) => Promise; supportsConversationRollback: boolean; threadStartCheckpointReady?: boolean; @@ -1304,6 +1306,17 @@ const ConversationTimeline = memo(function ConversationTimeline({ viewport={timelineViewportElement} threadRef={citationThreadRef} onCite={onCiteAssistantText} + findProjectedItem={(messageId) => { + const row = rows.find( + (candidate) => + candidate.kind === "message" && candidate.message.id === messageId, + ); + // The server refuses to fork a run that is still active. + return row?.kind === "message" && !row.assistantCopyStreaming + ? row.projectedItem + : undefined; + }} + onForkFromRun={onForkFromRun} /> ) : null} diff --git a/apps/web/src/components/chat/useTimelineRewind.ts b/apps/web/src/components/chat/useTimelineRewind.ts index c0661af66c03e..60650371af446 100644 --- a/apps/web/src/components/chat/useTimelineRewind.ts +++ b/apps/web/src/components/chat/useTimelineRewind.ts @@ -5,6 +5,7 @@ import type { SessionPhase } from "../../types"; import { useStableCallback } from "../../hooks/useStableCallback"; import { AuthOrchestrationOperateScope, + type AssistantCitation, type EnvironmentId, type MessageId, type ScopedThreadRef, @@ -23,6 +24,7 @@ import { type ChatMessage } from "../../types"; import { newThreadId } from "~/lib/utils"; import { buildThreadRouteParams } from "../../threadRoutes"; import { useComposerDraftStore } from "../../composerDraftStore"; +import { formatAssistantCitationForComposer } from "../../composer-logic"; import { threadEnvironment } from "../../state/threads"; import { waitForThreadShell } from "../../state/entities"; import { openRevertConfirm } from "./ChatOverlayHosts"; @@ -174,6 +176,7 @@ export function useTimelineRewind(input: TimelineRewindInput) { const onForkFromRun = async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId; + readonly citation?: AssistantCitation; }) => { if (!activeThread || activeEnvironmentUnavailable) return; const targetThreadId = newThreadId(); @@ -205,6 +208,15 @@ export function useTimelineRewind(input: TimelineRewindInput) { ); return; } + if (input.citation) { + // The fork tags its copy of the cited response with its own thread id. + useComposerDraftStore + .getState() + .setPrompt( + targetThreadRef, + formatAssistantCitationForComposer({ ...input.citation, threadId: targetThreadId }), + ); + } await navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(targetThreadRef), diff --git a/docs/user/composer.md b/docs/user/composer.md index 714572dfd5005..cf5d5025a0f33 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -120,6 +120,11 @@ On web and desktop, select text within one assistant response and choose **Cite in composer**. You can add a comment about the quote and write instructions around it. +To explore the quote without adding to the current conversation, choose +**Follow up** instead. It forks the thread from that response and opens the fork +with the quote already in its composer. Follow up is available once the response's +turn has finished. + Select the quote in a draft or sent message to return to its source. If the source is unavailable or has changed, the saved quote remains readable.