feat(artifacts): quote and rewrite selected passages (#8212)

* feat(artifacts): quote and rewrite selected passages

* fix(artifacts): verify rewrite spans and clear discarded edits

* fix(artifacts): require explicit rewrite submission in side chat

* fix(artifacts): honor cleared rewrite references on all origins

* docs(artifacts): remove committed selection screenshots

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
Wenchao An 2026-11-17 16:41:29 +08:00 committed by GitHub
parent 16c8e01a99
commit c87e238ddd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 1756 additions and 25 deletions

View File

@ -15,6 +15,39 @@ without requiring sign-in.
Deployments can add binary readers through the optional `artifactPreviews` browser
contribution; see the [plugin contract](../full-stack-plugins.md#artifact-previews).
## Quote and rewrite a passage
Select text in a Markdown artifact or its source editor to open the selection
toolbar. **Add to conversation** attaches the passage to the main composer;
**Ask in side chat** opens a follow-up alongside the conversation. Both carry
the selected text and file path, plus the source line range when available. You can
add several quotations before sending your question. Assistant replies already
offer the same two quotation actions.
For a writable output file, **Rewrite selection** opens side chat with that
passage. Describe the change and choose **Rewrite selection** in the side-chat
composer. Use the regular send action to ask a question about the passage and
end the pending rewrite. Once the rewrite finishes, choose
**Review replacement**, inspect or adjust the proposed text, and choose
**Apply to draft**. This replaces exactly the selected source range and opens
the file's editor. **Save** publishes the draft using the existing revision
check. Everything before and after the selected range stays unchanged.
The edit survives switching from the artifact panel to side chat. Changing
the draft, changing its saved revision, or starting a run prevents stale edits
from being applied or saved. Edits stay in memory for the current conversation.
Switching conversations, discarding the side chat, or clearing its selected
references cancels the pending rewrite.
Nothing writes to the file until you explicitly save it.
Selections support up to 12,000 characters. Markdown may hide formatting markers,
so a rendered selection is rewritable only when the renderer can verify its
exact source range. For other selections, quote the passage or switch to
**View source** to choose an exact range. HTML and CSV/TSV use source selections;
binary previews do not expose text selections. Truncated previews can be quoted
but require **Load full file** before rewriting. Read-only artifacts, demos,
and files outside the output directory cannot be rewritten.
## Office artifact preview extension
The optional [Office preview package](../../examples/deerflow-extension-office-preview/README.md)

View File

@ -71,6 +71,15 @@ pnpm catalog:sync # after a change to the capability catalog
`@`. Typed slash text is still submitted as a normal message, which the backend
and the IM channels rely on.
## Artifact selection
- **Artifact rewrite state outlives its panel.** Opening side chat unmounts the
file detail. Keep the source range and revision in the sidecar provider, apply
through the shared draft store, and preserve the revision-checked Save path.
- **Verify the source span before rewriting Markdown.** Use positions from the
complete static parse with unchanged preprocessing and literal rendered text.
For other rendered selections, offer quotation and direct rewrites to View source.
## Delimited preview
- **CSV parsing runs in the worker only**, with bounded input, cancellation of

View File

@ -80,6 +80,7 @@ import {
} from "./artifact-file-preview";
import { useArtifacts } from "./context";
import { PluginArtifactPreview } from "./plugin-artifact-preview";
import { useArtifactSelection } from "./use-artifact-selection";
const WRITE_FILE_PREVIEW_REFRESH_INTERVAL_MS = 3000;
@ -271,15 +272,38 @@ export function ArtifactFileDetail({
}, [content, filepath, isWriteFile, setDrafts, sha256, truncated]);
const [viewMode, setViewMode] = useState<"code" | "preview">(
artifactViewState.initialViewMode,
isEditing ? "code" : artifactViewState.initialViewMode,
);
const [isInstalling, setIsInstalling] = useState(false);
const isLoadingFullContent = fullContentRequested && isLoading;
const effectiveViewMode =
truncated && language === "html" ? "code" : viewMode;
const selection = useArtifactSelection({
filepath,
threadId,
ownerId: user?.id,
source: editorContent,
revision: activeDraft.baselineSha256,
enabled:
isCodeFile &&
!isWriteFile &&
!isSkillFile &&
!isMock &&
!isLoading &&
!error &&
!thread.isLoading &&
!isSaving &&
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY !== "true",
editable:
canEdit &&
!thread.isLoading &&
!isSaving &&
!activeDraft.conflict &&
activeDraft.baselineSha256 === sha256,
});
useEffect(() => {
setViewMode(artifactViewState.initialViewMode);
}, [artifactViewState.initialViewMode, filepathFromProps]);
setViewMode(isEditing ? "code" : artifactViewState.initialViewMode);
}, [artifactViewState.initialViewMode, filepathFromProps, isEditing]);
const confirmDiscard = useCallback(() => {
return !isDirty || window.confirm(t.artifactEditing.discardChanges);
@ -669,6 +693,7 @@ export function ArtifactFileDetail({
</div>
</ArtifactHeader>
<ArtifactContent className="flex flex-col p-0">
{selection.toolbar}
{truncated && !(isTabular && effectiveViewMode === "preview") && (
<div className="border-border bg-muted/40 flex shrink-0 items-center justify-between gap-3 border-b px-4 py-2 text-sm">
<span className="text-muted-foreground">
@ -712,6 +737,7 @@ export function ArtifactFileDetail({
url={url}
truncated={truncated}
active={effectiveViewMode === "preview" && !isLoading}
onTextSelection={selection.onTextSelection}
/>
)}
{isCodeFile &&
@ -735,6 +761,7 @@ export function ArtifactFileDetail({
}));
}}
onSave={() => void handleSave()}
onSelectionChange={selection.onSourceSelection}
language={language}
/>
)}

View File

@ -14,6 +14,7 @@ import {
createHtmlPreviewScrollKey,
HTML_PREVIEW_SCROLL_MESSAGE_SOURCE,
} from "@/core/artifacts/preview";
import { rehypeArtifactSourceRanges } from "@/core/artifacts/selection-dom";
import {
type ArtifactImageContext,
resolveArtifactImageURL,
@ -126,6 +127,7 @@ export function ArtifactFilePreview({
artifact,
truncated = false,
active = true,
onTextSelection,
}: {
content: string;
language: string;
@ -134,8 +136,17 @@ export function ArtifactFilePreview({
artifact?: ArtifactImageContext;
truncated?: boolean;
active?: boolean;
onTextSelection?: (container: HTMLElement) => void;
}) {
const { t } = useI18n();
const selectionPlugins = useMemo(
() =>
[
...(artifactMarkdownPlugins.rehypePlugins ?? []),
[rehypeArtifactSourceRanges, { source: content }],
] as typeof artifactMarkdownPlugins.rehypePlugins,
[content],
);
const { filepath, threadId, isMock } = artifact ?? {};
const transformUrl = useCallback<UrlTransform>(
(src, key, node) =>
@ -265,12 +276,24 @@ export function ArtifactFilePreview({
}
if (language === "markdown") {
return (
<div className="size-full overflow-auto px-4 py-3">
<div
className="size-full overflow-auto px-4 py-3"
onMouseUp={(event) => onTextSelection?.(event.currentTarget)}
onKeyUp={(event) => onTextSelection?.(event.currentTarget)}
onTouchEnd={(event) => onTextSelection?.(event.currentTarget)}
data-testid="artifact-markdown-preview"
>
<SafeStreamdown
// Streamdown memoizes blocks by content, not the image URL resolver.
key={JSON.stringify([scrollKey, filepath, threadId, Boolean(isMock)])}
className="min-w-0"
{...artifactMarkdownPlugins}
mode={onTextSelection ? "static" : undefined}
rehypePlugins={
onTextSelection
? selectionPlugins
: artifactMarkdownPlugins.rehypePlugins
}
urlTransform={transformUrl}
components={toStreamdownComponents({ a: ArtifactLink })}
>

View File

@ -0,0 +1,211 @@
"use client";
import {
MessageSquareTextIcon,
PencilIcon,
QuoteIcon,
XIcon,
} from "lucide-react";
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
artifactSelectionContext,
MAX_SELECTION_LENGTH,
sourceSelectionOffsets,
type SourceSelection,
} from "@/core/artifacts/selection";
import { readArtifactSelection } from "@/core/artifacts/selection-dom";
import { useI18n } from "@/core/i18n/hooks";
import { uuid } from "@/core/utils/uuid";
import { useMaybeSidecar } from "../sidecar/context";
type Selection = {
text: string;
range: SourceSelection | null;
exact: SourceSelection | null;
rect: { left: number; bottom: number };
};
export function useArtifactSelection(options: {
filepath: string;
threadId: string;
ownerId?: string;
source: string;
revision: string | null;
enabled: boolean;
editable: boolean;
}) {
const { t } = useI18n();
const sidecar = useMaybeSidecar();
const [selection, setSelection] = useState<Selection | null>(null);
useEffect(() => {
setSelection(null);
}, [
options.filepath,
options.threadId,
options.ownerId,
options.source,
options.enabled,
]);
useEffect(() => {
if (!selection) return;
const escape = (event: KeyboardEvent) => {
if (event.key === "Escape") setSelection(null);
};
const dismiss = (event: Event) => {
if (
!(event.target instanceof Element) ||
!event.target.closest('[data-testid="artifact-selection-toolbar"]')
)
setSelection(null);
};
document.addEventListener("keydown", escape);
document.addEventListener("pointerdown", dismiss);
document.addEventListener("scroll", dismiss, true);
return () => {
document.removeEventListener("keydown", escape);
document.removeEventListener("pointerdown", dismiss);
document.removeEventListener("scroll", dismiss, true);
};
}, [selection]);
const accept = (next: Selection | null) => {
if (!options.enabled || !sidecar || !next?.text.trim()) {
setSelection(null);
return;
}
if (next.text.length > MAX_SELECTION_LENGTH) {
setSelection(null);
toast.error(t.artifactSelection.limit);
return;
}
setSelection(next);
};
const dismiss = () => {
setSelection(null);
window.getSelection()?.removeAllRanges();
};
const context = selection
? artifactSelectionContext(
options.filepath,
options.source,
selection.text,
selection.exact ?? selection.range,
)
: null;
const rewrite = () => {
if (
!selection?.exact ||
!context ||
!sidecar ||
!options.editable ||
!options.revision
)
return;
sidecar.beginArtifactEdit({
id: uuid(),
context,
filepath: options.filepath,
threadId: options.threadId,
ownerId: options.ownerId,
source: options.source,
revision: options.revision,
...selection.exact,
});
dismiss();
};
return {
onTextSelection:
options.enabled && sidecar
? (container: HTMLElement) =>
accept(readArtifactSelection(container, options.source))
: undefined,
onSourceSelection: (
next: (SourceSelection & { rect: Selection["rect"] }) | null,
) => {
if (!next) return accept(null);
const exact = sourceSelectionOffsets(options.source, next);
accept({
text: options.source.slice(exact.from, exact.to),
range: exact,
exact,
rect: next.rect,
});
},
toolbar:
selection && context && sidecar && options.enabled
? createPortal(
<div
role="toolbar"
aria-label={t.sidecar.reference}
data-testid="artifact-selection-toolbar"
className="bg-popover text-popover-foreground fixed z-50 flex max-w-[calc(100vw-16px)] flex-wrap gap-1 rounded-lg border p-1 shadow-lg"
style={{
left: Math.max(
8,
Math.min(selection.rect.left, window.innerWidth - 460),
),
top: Math.max(
8,
Math.min(selection.rect.bottom + 8, window.innerHeight - 90),
),
}}
onMouseDown={(event) => event.preventDefault()}
>
<Button
size="sm"
variant="ghost"
onClick={() => {
sidecar.addContextToConversation(context);
dismiss();
}}
>
<QuoteIcon />
{t.sidecar.addToConversation}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => {
sidecar.openContext(context);
dismiss();
}}
>
<MessageSquareTextIcon />
{t.sidecar.askInSideChat}
</Button>
{options.editable && (
<Button
size="sm"
variant="ghost"
disabled={!selection.exact}
title={
!selection.exact
? t.artifactSelection.exactRequired
: undefined
}
onClick={rewrite}
>
<PencilIcon />
{t.artifactSelection.rewrite}
</Button>
)}
<Button
size="icon-sm"
variant="ghost"
aria-label={t.common.close}
onClick={dismiss}
>
<XIcon />
</Button>
</div>,
document.body,
)
: null,
};
}

View File

@ -21,6 +21,7 @@ export function CodeEditor({
onSave,
settings,
language,
onSelectionChange,
}: {
className?: string;
placeholder?: string;
@ -32,6 +33,13 @@ export function CodeEditor({
onSave?: () => void;
settings?: unknown;
language?: string;
onSelectionChange?: (
selection: {
from: number;
to: number;
rect: { left: number; bottom: number };
} | null,
) => void;
}) {
const {
thread: { isLoading },
@ -83,7 +91,12 @@ export function CodeEditor({
/>
) : (
<CodeMirror
editable={readonly !== true && disabled !== true}
// Keep the source focusable for keyboard selection. readOnly below
// still prevents edits until the user explicitly enters edit mode.
editable={
disabled !== true &&
(readonly !== true || onSelectionChange !== undefined)
}
readOnly={readonly === true || disabled === true}
placeholder={placeholder}
className={cn(
@ -102,6 +115,23 @@ export function CodeEditor({
}}
autoFocus={autoFocus}
onChange={onChange}
onUpdate={(update) => {
if (
!onSelectionChange ||
(!update.selectionSet && !update.docChanged)
)
return;
const range = update.state.selection.main;
const rect = update.view.coordsAtPos(range.to);
onSelectionChange(
!update.docChanged &&
!range.empty &&
update.state.selection.ranges.length === 1 &&
rect
? { from: range.from, to: range.to, rect }
: null,
);
}}
value={value}
/>
)}

View File

@ -0,0 +1,189 @@
"use client";
import type { Message } from "@langchain/langgraph-sdk";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { useArtifactContent } from "@/core/artifacts/hooks";
import {
artifactReplacement,
applyArtifactSelectionDraft,
MAX_REPLACEMENT_LENGTH,
type ArtifactSelectionEdit,
} from "@/core/artifacts/selection";
import { useAuth } from "@/core/auth/AuthProvider";
import { useI18n } from "@/core/i18n/hooks";
import { useArtifacts } from "../artifacts/context";
import { useThread } from "../messages/context";
import { useSidecar } from "./context";
export function ArtifactRewriteReview({
edit,
messages,
disabled,
onCancel,
}: {
edit: ArtifactSelectionEdit;
messages: Message[];
disabled: boolean;
onCancel: () => void;
}) {
const { t } = useI18n();
const { user } = useAuth();
const { thread } = useThread();
const sidecar = useSidecar();
const clearArtifactEdit = sidecar.clearArtifactEdit;
const {
drafts,
setDrafts,
setEditingPath,
select,
setOpen: openArtifacts,
} = useArtifacts();
const authorized =
edit.ownerId === user?.id && edit.threadId === sidecar.parentThreadId;
const artifact = useArtifactContent({
filepath: edit.filepath,
threadId: edit.threadId,
enabled: authorized,
});
const canApply =
authorized &&
!disabled &&
!thread.isLoading &&
!artifact.isLoading &&
!artifact.error &&
artifact.sha256 === edit.revision;
const draft = drafts[edit.filepath];
const changed =
!draft ||
draft.conflict ||
draft.draftContent !== edit.source ||
draft.baselineSha256 !== edit.revision ||
(artifact.sha256 !== undefined && artifact.sha256 !== edit.revision);
const [open, setOpen] = useState(false);
const [replacement, setReplacement] = useState("");
const candidate = disabled ? null : artifactReplacement(messages, edit.id);
useEffect(() => {
if (!authorized) clearArtifactEdit(edit.id);
}, [authorized, edit.id, clearArtifactEdit]);
if (!authorized) return null;
return (
<>
<div
className="bg-muted/40 mx-3 space-y-2 rounded-lg border p-3 text-sm"
data-testid="artifact-rewrite-review"
>
<p className="truncate font-medium" title={edit.context.label}>
{edit.context.label}
</p>
<p className="text-muted-foreground">
{t.artifactSelection.instructions}
</p>
<div className="flex gap-2">
<Button
size="sm"
disabled={candidate === null}
onClick={() => {
setReplacement(candidate ?? "");
setOpen(true);
}}
>
{t.artifactSelection.review}
</Button>
<Button size="sm" variant="ghost" onClick={onCancel}>
{t.common.cancel}
</Button>
</div>
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{t.artifactSelection.review}</DialogTitle>
<DialogDescription className="break-all">
{edit.context.label}
</DialogDescription>
</DialogHeader>
<label className="space-y-2 text-sm">
<span>{t.artifactSelection.original}</span>
<Textarea
aria-label={t.artifactSelection.original}
readOnly
value={edit.context.content}
className="max-h-36"
/>
</label>
<label className="space-y-2 text-sm">
<span>{t.artifactSelection.replacement}</span>
<Textarea
aria-label={t.artifactSelection.replacement}
value={replacement}
onChange={(event) => setReplacement(event.target.value)}
maxLength={MAX_REPLACEMENT_LENGTH}
className="max-h-72 min-h-40 font-mono"
/>
</label>
<DialogFooter>
{changed && (
<p role="alert" className="text-destructive text-sm">
{t.artifactSelection.changed}
</p>
)}
<Button variant="outline" onClick={() => setOpen(false)}>
{t.common.cancel}
</Button>
<Button
disabled={
!canApply ||
changed ||
replacement.length > MAX_REPLACEMENT_LENGTH
}
onClick={() => {
const next = applyArtifactSelectionDraft(
drafts[edit.filepath],
edit,
replacement,
);
if (!canApply || !next) {
toast.error(t.artifactSelection.changed);
return;
}
setDrafts((current) => {
const updated = applyArtifactSelectionDraft(
current[edit.filepath],
edit,
replacement,
);
return updated
? { ...current, [edit.filepath]: updated }
: current;
});
toast.success(t.artifactSelection.applied);
setOpen(false);
onCancel();
select(edit.filepath);
setEditingPath(edit.filepath);
sidecar.close();
openArtifacts(true);
}}
>
{t.artifactSelection.apply}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
);
}

View File

@ -12,6 +12,7 @@ import {
type ReactNode,
} from "react";
import type { ArtifactSelectionEdit } from "@/core/artifacts/selection";
import {
appendSidecarReference,
buildMessageSidecarContext,
@ -25,6 +26,9 @@ import type { ThreadStreamOptions } from "@/core/threads/hooks";
export type SidecarReference = SidecarReferenceStateItem;
type SidecarContextValue = {
artifactEdit: ArtifactSelectionEdit | null;
beginArtifactEdit: (edit: ArtifactSelectionEdit) => void;
clearArtifactEdit: (id?: string) => void;
open: boolean;
activeReferences: SidecarReference[];
conversationQuotes: SidecarReference[];
@ -64,6 +68,20 @@ export function SidecarProvider({
isMock?: boolean;
}) {
const [open, setOpen] = useState(false);
const [artifactEdit, setArtifactEdit] =
useState<ArtifactSelectionEdit | null>(null);
const clearArtifactEdit = useCallback(
(id?: string) => {
if (id && artifactEdit?.id !== id) return;
setArtifactEdit(null);
setActiveReferences((references) =>
references.filter(
(reference) => reference.context !== artifactEdit?.context,
),
);
},
[artifactEdit],
);
const [activeReferences, setActiveReferences] = useState<SidecarReference[]>(
[],
);
@ -104,6 +122,7 @@ export function SidecarProvider({
setSidecarContext(context);
updateSidecarThreadId(null);
setConversationQuotes([]);
setArtifactEdit(null);
}, [context, parentThreadId, updateSidecarThreadId]);
const restoreSidecarThread = useCallback(
@ -190,6 +209,14 @@ export function SidecarProvider({
[createReference],
);
const beginArtifactEdit = useCallback(
(edit: ArtifactSelectionEdit) => {
setArtifactEdit(edit);
openContext(edit.context);
},
[openContext],
);
const clearConversationQuotes = useCallback((ids?: number[]) => {
if (!ids) {
setConversationQuotes([]);
@ -228,6 +255,9 @@ export function SidecarProvider({
const value = useMemo<SidecarContextValue>(
() => ({
artifactEdit,
beginArtifactEdit,
clearArtifactEdit,
open,
activeReferences,
conversationQuotes,
@ -247,6 +277,9 @@ export function SidecarProvider({
close,
}),
[
artifactEdit,
beginArtifactEdit,
clearArtifactEdit,
activeReferences,
addContextToConversation,
clearActiveReferences,

View File

@ -12,7 +12,13 @@ import {
XIcon,
ZapIcon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
useCallback,
useEffect,
useMemo,
useState,
type FormEvent,
} from "react";
import { toast } from "sonner";
import { ConversationEmptyState } from "@/components/ai-elements/conversation";
@ -48,6 +54,10 @@ import {
DropdownMenuGroup,
DropdownMenuLabel,
} from "@/components/ui/dropdown-menu";
import {
isArtifactRewriteClarification,
type ArtifactSelectionEdit,
} from "@/core/artifacts/selection";
import { useAuth } from "@/core/auth/AuthProvider";
import { hasPermission, PERMISSIONS } from "@/core/auth/permissions";
import { useI18n } from "@/core/i18n/hooks";
@ -70,6 +80,7 @@ import {
buildParentConversationContext,
buildReferenceMessageMetadata,
buildSidecarContextPrompt,
isSameSidecarContext,
} from "@/core/sidecar";
import { createSidecarThread } from "@/core/sidecar/api";
import {
@ -98,6 +109,7 @@ import {
} from "../model-picker-content";
import { Tooltip } from "../tooltip";
import { ArtifactRewriteReview } from "./artifact-rewrite-review";
import { type SidecarReference, useSidecar } from "./context";
import { ReferenceAttachmentSummary } from "./reference-attachments";
@ -143,6 +155,8 @@ export function SidecarPanel({ className }: { className?: string }) {
const [queuedSubmit, setQueuedSubmit] = useState<{
message: PromptInputMessage;
references: SidecarReference[];
artifactEdit: ArtifactSelectionEdit | null;
onSent: () => void;
// Settles the composer's submit with the queued send's outcome.
resolve: () => void;
reject: (error: unknown) => void;
@ -343,17 +357,31 @@ export function SidecarPanel({ className }: { className?: string }) {
threadId: string,
message: PromptInputMessage,
references: SidecarReference[],
artifactEdit: ArtifactSelectionEdit | null,
onSent?: () => void,
additionalKwargs?: Record<string, unknown>,
) => {
const contexts = references.map((reference) => reference.context);
const referencedContexts = references.map(
(reference) => reference.context,
);
const contexts = artifactEdit
? [
artifactEdit.context,
...referencedContexts.filter(
(context) => !isSameSidecarContext(context, artifactEdit.context),
),
]
: referencedContexts;
const parentConversation = buildParentConversationContext(
parentThread.messages,
);
const hiddenContextPrompt =
let hiddenContextPrompt =
contexts.length > 0 || parentConversation.length > 0
? buildSidecarContextPrompt(contexts, { parentConversation })
: null;
if (artifactEdit) {
hiddenContextPrompt = `${hiddenContextPrompt ?? ""}\n\nRewrite only the first referenced passage (the artifact selection) according to the user's request. Other references provide context. Return the replacement text itself, without explanations or an enclosing code fence. Preserve surrounding Markdown structure when relevant. The user will review the replacement and apply it to the original file's draft; do not write or recreate that file in this side chat.`;
}
await sendMessage(threadId, message, undefined, {
additionalInputMessages: hiddenContextPrompt
? [
@ -365,6 +393,7 @@ export function SidecarPanel({ className }: { className?: string }) {
: [],
additionalKwargs: {
sidecar_visible_message: true,
...(artifactEdit ? { artifact_selection_edit: artifactEdit.id } : {}),
...(contexts.length > 0
? buildReferenceMessageMetadata(contexts)
: {}),
@ -384,6 +413,7 @@ export function SidecarPanel({ className }: { className?: string }) {
let sent = false;
const pendingReferences = [...sidecar.activeReferences];
const edit = sidecar.artifactEdit;
await submitToSidecarThread(
sidecar.sidecarThreadId,
{
@ -391,6 +421,14 @@ export function SidecarPanel({ className }: { className?: string }) {
files: [],
},
pendingReferences,
edit &&
isArtifactRewriteClarification(
thread.messages,
edit.id,
request.request_id,
)
? edit
: null,
() => {
sent = true;
if (pendingReferences.length > 0) {
@ -404,7 +442,7 @@ export function SidecarPanel({ className }: { className?: string }) {
);
return sent;
},
[sidecar, submitToSidecarThread],
[sidecar, submitToSidecarThread, thread.messages],
);
const handleSubmitApproval = useCallback(
@ -429,13 +467,8 @@ export function SidecarPanel({ className }: { className?: string }) {
sidecar.sidecarThreadId,
nextSubmit.message,
nextSubmit.references,
// Clear references only once the send genuinely proceeds; a send dropped
// by the in-flight guard leaves them attached instead of losing them.
() => {
if (nextSubmit.references.length > 0) {
sidecar.clearActiveReferences();
}
},
nextSubmit.artifactEdit,
nextSubmit.onSent,
).then(nextSubmit.resolve, nextSubmit.reject);
}, [
queuedSubmit,
@ -446,7 +479,7 @@ export function SidecarPanel({ className }: { className?: string }) {
]);
const handleSubmit = useCallback(
async (message: PromptInputMessage) => {
async (message: PromptInputMessage, event: FormEvent<HTMLFormElement>) => {
const text = message.text.trim();
const files = promptMessageFiles(message);
if ((!text && message.files.length === 0) || disabled) {
@ -459,6 +492,14 @@ export function SidecarPanel({ className }: { className?: string }) {
}
const pendingReferences = [...sidecar.activeReferences];
const edit = sidecar.artifactEdit;
const submitter = (event.nativeEvent as SubmitEvent).submitter;
const artifactEdit =
submitter?.getAttribute("value") === "rewrite" ? edit : null;
const onSent = () => {
if (pendingReferences.length > 0) sidecar.clearActiveReferences();
if (edit && !artifactEdit) sidecar.clearArtifactEdit(edit.id);
};
try {
if (!sidecar.sidecarThreadId) {
await ensureSidecarThread(pendingReferences);
@ -468,6 +509,8 @@ export function SidecarPanel({ className }: { className?: string }) {
setQueuedSubmit({
message,
references: pendingReferences,
artifactEdit,
onSent,
resolve,
reject,
});
@ -479,11 +522,8 @@ export function SidecarPanel({ className }: { className?: string }) {
sidecar.sidecarThreadId,
message,
pendingReferences,
() => {
if (pendingReferences.length > 0) {
sidecar.clearActiveReferences();
}
},
artifactEdit,
onSent,
);
} catch (error) {
toast.error(
@ -504,11 +544,16 @@ export function SidecarPanel({ className }: { className?: string }) {
],
);
const discardDraftAndClose = useCallback(() => {
const clearSelectedReferences = useCallback(() => {
sidecar.clearArtifactEdit();
sidecar.clearActiveReferences();
}, [sidecar]);
const discardDraftAndClose = useCallback(() => {
clearSelectedReferences();
sidecar.setSidecarThreadId(null);
sidecar.close();
}, [sidecar]);
}, [clearSelectedReferences, sidecar]);
const handleDelete = useCallback(async () => {
const threadId = sidecar.sidecarThreadId;
@ -626,6 +671,15 @@ export function SidecarPanel({ className }: { className?: string }) {
)}
</div>
{sidecar.artifactEdit && (
<ArtifactRewriteReview
key={sidecar.artifactEdit.id}
edit={sidecar.artifactEdit}
messages={thread.messages}
disabled={disabled || !!thread.error || parentThread.isLoading}
onCancel={() => sidecar.clearArtifactEdit()}
/>
)}
<div className="bg-background/95 shrink-0 px-3 pt-3 pb-4 sm:px-4">
<PromptInputProvider key={sidecar.parentThreadId}>
<PromptInput
@ -646,7 +700,7 @@ export function SidecarPanel({ className }: { className?: string }) {
<ReferenceAttachmentSummary
references={sidecar.activeReferences}
testId="sidecar-reference-attachment"
onClear={() => sidecar.clearActiveReferences()}
onClear={clearSelectedReferences}
/>
)}
</PromptInputHeader>
@ -687,6 +741,16 @@ export function SidecarPanel({ className }: { className?: string }) {
variant="outline"
/>
</Tooltip>
{sidecar.artifactEdit && (
<Button
type="submit"
value="rewrite"
size="sm"
disabled={disabled}
>
{t.artifactSelection.rewrite}
</Button>
)}
</PromptInputTools>
</PromptInputFooter>
</PromptInput>

View File

@ -0,0 +1,114 @@
import type { Root } from "hast";
import { SKIP, visit } from "unist-util-visit";
import { locateArtifactSelection } from "./selection";
// Runs after sanitization: authored attributes cannot impersonate source offsets.
export function rehypeArtifactSourceRanges({ source }: { source: string }) {
return (tree: Root, file: { value: unknown }) => {
// Preprocessing may change math, indentation or internal tags. In that
// case offsets belong to the transformed text, not to the stored artifact.
if (String(file.value) !== source) return;
visit(tree, "element", (node) => {
if (!/^(p|h[1-6]|li|pre|td|th|blockquote)$/.test(node.tagName)) return;
const from = node.position?.start.offset;
const to = node.position?.end.offset;
if (from !== undefined && to !== undefined) {
node.properties.dataArtifactFrom = from;
node.properties.dataArtifactTo = to;
}
});
visit(tree, (node, index, parent) => {
// The renderer can replace code/math with its own DOM. Only plain text
// nodes with a literal source span get an exact offset.
if (
node.type === "element" &&
(node.tagName === "code" || node.tagName === "pre")
)
return SKIP;
if (node.type !== "text" || index === undefined || !parent) return;
const from = node.position?.start.offset;
const to = node.position?.end.offset;
if (
from === undefined ||
to === undefined ||
!node.value ||
source.slice(from, to) !== node.value
)
return;
parent.children[index] = {
type: "element",
tagName: "span",
properties: { dataArtifactTextFrom: from },
children: [node],
};
return SKIP;
});
};
}
function exactTextRange(source: string, range: Range, text: string) {
const node = range.startContainer;
if (node.nodeType !== Node.TEXT_NODE || node !== range.endContainer)
return null;
const offset = node.parentElement?.dataset.artifactTextFrom;
if (offset === undefined) return null;
const start = Number(offset);
const from = start + range.startOffset;
const to = start + range.endOffset;
return Number.isInteger(start) &&
start >= 0 &&
source.slice(from, to) === text
? { from, to }
: null;
}
export function readArtifactSelection(container: HTMLElement, source: string) {
const selection = window.getSelection();
if (!selection || selection.isCollapsed || selection.rangeCount !== 1)
return null;
const range = selection.getRangeAt(0);
if (
!container.contains(range.startContainer) ||
!container.contains(range.endContainer)
)
return null;
const block = (node: Node) =>
(node instanceof Element ? node : node.parentElement)?.closest<HTMLElement>(
"[data-artifact-from][data-artifact-to]",
);
const start = block(range.startContainer);
const end = block(range.endContainer);
const text = selection.toString();
const rect = range.getBoundingClientRect();
const exact = exactTextRange(source, range, text);
if (
!start ||
!end ||
!container.contains(start) ||
!container.contains(end)
) {
return {
text,
range: exact ?? locateArtifactSelection(source, text),
exact,
rect,
};
}
const from = Number(start.dataset.artifactFrom);
const to = Number(end.dataset.artifactTo);
if (
!Number.isInteger(from) ||
!Number.isInteger(to) ||
from < 0 ||
from >= to ||
to > source.length
)
return null;
return {
text,
range: { from, to },
exact,
rect,
};
}

View File

@ -0,0 +1,193 @@
import type { Message } from "@langchain/langgraph-sdk";
import { extractHumanInputRequest } from "@/core/messages/human-input";
import { extractTextFromMessage } from "@/core/messages/utils";
import type { SidecarContext } from "@/core/sidecar";
import type { ArtifactDraftState } from "./editing";
export type SourceSelection = { from: number; to: number };
export type ArtifactSelectionEdit = {
id: string;
context: SidecarContext;
filepath: string;
threadId: string;
ownerId?: string;
source: string;
revision: string;
} & SourceSelection;
export function applyArtifactSelectionDraft(
draft: ArtifactDraftState | undefined,
edit: ArtifactSelectionEdit,
replacement: string,
) {
if (
draft?.filepath !== edit.filepath ||
draft.conflict ||
draft.baselineSha256 !== edit.revision ||
draft.draftContent !== edit.source
)
return null;
return {
...draft,
draftContent: replaceArtifactSelection(
draft.draftContent,
edit,
replacement,
),
};
}
export const MAX_SELECTION_LENGTH = 12_000;
export const MAX_REPLACEMENT_LENGTH = 64_000;
// A unique text match can locate a quotation, but does not prove which
// Markdown source span produced the rendered text.
export function locateArtifactSelection(
source: string,
text: string,
lower = 0,
upper = source.length,
): SourceSelection | null {
if (!text || lower < 0 || upper > source.length || lower >= upper)
return null;
const from = source.indexOf(text, lower);
if (from < 0 || from + text.length > upper) return null;
const duplicate = source.indexOf(text, from + 1);
if (duplicate >= 0 && duplicate + text.length <= upper) return null;
return { from, to: from + text.length };
}
export function selectionLines(source: string, from: number, to: number) {
const lineBreak = /\r\n?|\n/;
const startLine = source.slice(0, from).split(lineBreak).length;
const endLine = source
.slice(0, to)
.replace(/(?:\r\n?|\n)$/, "")
.split(lineBreak).length;
return { startLine, endLine };
}
// CodeMirror normalizes CRLF and lone CR to a one-position line break.
// Only CRLF changes the number of source positions.
export function sourceSelectionOffsets(
source: string,
{ from, to }: SourceSelection,
): SourceSelection {
for (const match of source.matchAll(/\r\n/g)) {
if (match.index >= to) break;
if (match.index < from) from++;
to++;
}
return { from, to };
}
export function replaceArtifactSelection(
current: string,
selection: SourceSelection & { source: string },
replacement: string,
) {
const { source, from, to } = selection;
if (
current !== source ||
!Number.isInteger(from) ||
!Number.isInteger(to) ||
from < 0 ||
from >= to ||
to > source.length ||
replacement.length > MAX_REPLACEMENT_LENGTH
)
throw new Error("The artifact selection has changed");
return source.slice(0, from) + replacement + source.slice(to);
}
export function artifactSelectionContext(
filepath: string,
source: string,
text: string,
range: SourceSelection | null,
): SidecarContext {
const lines = range && selectionLines(source, range.from, range.to);
return {
type: "referenced_message",
role: "assistant",
label: lines
? `${filepath}:L${lines.startLine}-L${lines.endLine}`
: filepath,
content: text,
};
}
function lastSidecarRequest(messages: Message[]) {
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (
message?.type === "human" &&
message.additional_kwargs?.sidecar_visible_message === true
)
return index;
}
return -1;
}
export function isArtifactRewriteClarification(
messages: Message[],
editId: string,
requestId: string,
) {
const request = lastSidecarRequest(messages);
return (
request >= 0 &&
messages[request]?.additional_kwargs?.artifact_selection_edit === editId &&
messages
.slice(request + 1)
.some(
(message) =>
extractHumanInputRequest(message)?.request_id === requestId,
)
);
}
// An answer must follow a submitted request for this particular edit. Restored
// sidecar history and a previous edit's answer must never become replacements.
export function artifactReplacement(messages: Message[], editId: string) {
const lastHuman = lastSidecarRequest(messages);
if (
lastHuman < 0 ||
messages[lastHuman]?.additional_kwargs?.artifact_selection_edit !== editId
)
return null;
const answer = messages
.slice(lastHuman + 1)
.reverse()
.find(
(message) =>
message.type === "ai" &&
!message.tool_calls?.length &&
message.additional_kwargs?.hide_from_ui !== true &&
extractTextFromMessage(message).trim(),
);
if (!answer) return null;
const visible = extractTextFromMessage(answer);
const raw =
typeof answer.content === "string"
? answer.content
: answer.content
.flatMap((part) =>
typeof part === "string"
? [part]
: part.type === "text" && typeof part.text === "string"
? [part.text]
: [],
)
.join("\n");
// The message renderer trims display text and removes inline reasoning. Keep
// code indentation when the visible answer is otherwise unchanged.
const text = raw.trim() === visible ? raw : visible;
// Accept a single wrapping code fence, preserving the replacement's internal
// whitespace. Users can review and edit the text before applying it.
const fenced = /^```[^\n]*\r?\n([\s\S]*?)\r?\n```$/.exec(text.trim());
const replacement = fenced?.[1] ?? text;
return replacement.length <= MAX_REPLACEMENT_LENGTH ? replacement : null;
}

View File

@ -424,6 +424,20 @@ export const enUS: Translations = {
linkCopied: "Link copied to clipboard",
},
artifactSelection: {
rewrite: "Rewrite selection",
instructions:
"Describe the change, then choose Rewrite selection. To ask a regular question, use Send.",
exactRequired: "Switch to source to select an exact range for rewriting.",
review: "Review replacement",
original: "Selected passage",
replacement: "Replacement",
apply: "Apply to draft",
applied: "Selection replaced in the draft. Review and save the artifact.",
changed: "The file or draft changed. Select the passage again.",
limit: "Select up to 12,000 characters.",
},
artifactEditing: {
unsaved: "Unsaved",
saving: "Saving...",

View File

@ -360,6 +360,19 @@ export interface Translations {
linkCopied: string;
};
artifactSelection: {
rewrite: string;
instructions: string;
exactRequired: string;
review: string;
original: string;
replacement: string;
apply: string;
applied: string;
changed: string;
limit: string;
};
artifactEditing: {
unsaved: string;
saving: string;

View File

@ -404,6 +404,19 @@ export const zhCN: Translations = {
linkCopied: "链接已复制到剪贴板",
},
artifactSelection: {
rewrite: "改写选区",
instructions: "描述如何修改后,选择「改写选区」。普通追问请使用发送按钮。",
exactRequired: "切换到源码,选择准确范围后即可改写。",
review: "预览替换内容",
original: "选中段落",
replacement: "替换内容",
apply: "应用到草稿",
applied: "选区已替换到草稿,请检查后保存文件。",
changed: "文件或草稿已变化,请重新选择段落。",
limit: "请选择不超过 12,000 个字符。",
},
artifactEditing: {
unsaved: "未保存",
saving: "正在保存...",

View File

@ -13,6 +13,7 @@ export function isSameSidecarContext(
left.type === right.type &&
left.role === right.role &&
left.messageId === right.messageId &&
(left.messageId !== undefined || left.label === right.label) &&
left.content === right.content
);
}

View File

@ -0,0 +1,448 @@
import { createHash } from "node:crypto";
import { expect, test, type Page } from "@playwright/test";
import {
handleRunStream,
mockLangGraphAPI,
MOCK_THREAD_ID,
visibleRunInputMessages,
runStreamThreadId,
} from "./utils/mock-api";
const filepath = "/mnt/user-data/outputs/selection-report.md";
const original =
"# Quarterly report\n\nKeep the introduction.\n\nRevenue rose by 20 percent.\n\nKeep the conclusion.\n";
const revision = createHash("sha256").update(original).digest("hex");
const selected = "Revenue rose by 20 percent.";
async function setup(page: Page, source = original) {
const api = mockLangGraphAPI(page, {
threads: [
{
thread_id: MOCK_THREAD_ID,
title: "Quarterly report",
artifacts: [filepath],
messages: [
{
type: "human",
id: "question",
content: "Write a quarterly report",
},
{
type: "ai",
id: "report",
content: "",
tool_calls: [
{
id: "present",
name: "present_files",
args: { filepaths: [filepath] },
},
],
},
{
type: "ai",
id: "report-answer",
content: "The report is ready.",
},
],
},
],
});
const writes: unknown[] = [];
await page.route(
`**/api/threads/${MOCK_THREAD_ID}/artifacts/mnt/user-data/outputs/selection-report.md`,
async (route) => {
if (route.request().method() === "PUT") {
const body = route.request().postDataJSON() as { content: string };
writes.push(body);
source = body.content;
return route.fulfill({
json: {
path: filepath,
sha256: createHash("sha256").update(source).digest("hex"),
size: source.length,
},
});
}
return route.fulfill({
contentType: "text/markdown",
headers: { ETag: `"${revision}"` },
body: source,
});
},
);
await page.goto(`/workspace/chats/${MOCK_THREAD_ID}`);
await page.getByText("selection-report.md", { exact: true }).first().click();
await expect(page.getByTestId("artifact-markdown-preview")).toContainText(
"Quarterly report",
);
return { writes, api };
}
async function select(page: Page, text: string, occurrence = 0) {
await page.getByTestId("artifact-markdown-preview").evaluate(
(root, { text, occurrence }) => {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
let node: Node | null;
let count = 0;
while ((node = walker.nextNode())) {
const start = (node.textContent ?? "").indexOf(text);
if (start < 0 || count++ !== occurrence) continue;
const range = document.createRange();
range.setStart(node, start);
range.setEnd(node, start + text.length);
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
node.parentElement!.dispatchEvent(
new MouseEvent("mouseup", { bubbles: true }),
);
return;
}
throw new Error("Selection text not found");
},
{ text, occurrence },
);
await expect(page.getByTestId("artifact-selection-toolbar")).toBeVisible();
}
test("artifact quotes retain the selected source line in the conversation", async ({
page,
}, testInfo) => {
const { writes } = await setup(page);
await select(page, selected);
await page.screenshot({
path: testInfo.outputPath("artifact-selection-entry.png"),
fullPage: true,
});
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Add to conversation" })
.click();
const composer = page.getByPlaceholder(/How can I assist you/i);
const form = composer.locator("xpath=ancestor::form");
await expect(form).toContainText("selected text fragment");
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
return handleRunStream(route);
});
await composer.fill("Explain this figure");
await form.getByRole("button", { name: "Submit", exact: true }).click();
await expect
.poll(() => JSON.stringify(submitted))
.toContain(`${filepath}:L5-L5`);
expect(JSON.stringify(submitted)).toContain(selected);
expect(writes).toHaveLength(0);
});
test("rewriting changes only the selection after review, then uses revision-checked Save", async ({
page,
}, testInfo) => {
const { writes, api } = await setup(page);
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
const answer = {
type: "ai",
id: "rewrite-answer",
content: "Revenue increased by one fifth.",
};
const id = runStreamThreadId(route);
const inputs = visibleRunInputMessages(route);
api.upsertThread({
...api.getThread(id),
thread_id: id,
messages: [...inputs, answer],
});
return handleRunStream(route, {}, inputs, { responseMessage: answer });
});
await select(page, selected);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
const review = page.getByTestId("artifact-rewrite-review");
await expect(review).toContainText(`${filepath}:L5-L5`);
await expect(
review.getByRole("button", { name: "Review replacement" }),
).toBeDisabled();
const composer = page.getByPlaceholder(/deeper follow-up/i);
await composer.fill("Make the wording simpler");
await composer
.locator("xpath=ancestor::form")
.getByRole("button", { name: "Rewrite selection", exact: true })
.click();
await expect(
review.getByRole("button", { name: "Review replacement" }),
).toBeEnabled();
expect(JSON.stringify(submitted)).toContain("artifact_selection_edit");
expect(JSON.stringify(submitted)).toContain(selected);
expect(writes).toHaveLength(0);
await review.getByRole("button", { name: "Review replacement" }).click();
const dialog = page.getByRole("dialog");
await expect(dialog.getByLabel("Selected passage")).toHaveValue(selected);
await expect(dialog.getByLabel("Replacement", { exact: true })).toHaveValue(
"Revenue increased by one fifth.",
);
await expect(dialog).toHaveCSS("opacity", "1");
await page.screenshot({
path: testInfo.outputPath("artifact-rewrite-review.png"),
fullPage: true,
});
await dialog.getByRole("button", { name: "Apply to draft" }).click();
await expect(page.locator("#artifacts .cm-content")).toContainText(
"Revenue increased by one fifth.",
);
expect(writes).toHaveLength(0);
await page
.locator("#artifacts")
.getByRole("button", { name: "Save", exact: true })
.click();
await expect.poll(() => writes.length).toBe(1);
expect(writes[0]).toEqual({
content: original.replace(selected, "Revenue increased by one fifth."),
expected_sha256: revision,
});
});
test("repeated paragraphs use source offsets of the selected occurrence", async ({
page,
}) => {
await setup(page, original + "\n" + selected + "\n");
await select(page, selected, 1);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
await expect(page.getByTestId("artifact-rewrite-review")).toContainText(
`${filepath}:L9-L9`,
);
});
test("source editor selections carry exact offsets and line ranges", async ({
page,
}) => {
await setup(page);
await page.locator("#artifacts").getByLabel("View source").click();
const editor = page.locator("#artifacts .cm-content");
await editor.click();
await editor.press("x");
await expect(editor).not.toContainText("x");
await editor.press("ControlOrMeta+a");
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
await expect(page.getByTestId("artifact-rewrite-review")).toContainText(
`${filepath}:L1-L7`,
);
});
test("formatted text can be quoted without guessing a replacement span", async ({
page,
}) => {
await setup(
page,
original.replace(selected, "Revenue rose by **20 percent**."),
);
await page
.getByTestId("artifact-markdown-preview")
.locator("p")
.filter({ hasText: selected })
.evaluate((paragraph) => {
const range = document.createRange();
range.selectNodeContents(paragraph);
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
paragraph.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
});
const toolbar = page.getByTestId("artifact-selection-toolbar");
await expect(
toolbar.getByRole("button", { name: "Rewrite selection" }),
).toBeDisabled();
await toolbar.getByRole("button", { name: "Ask in side chat" }).click();
await expect(page.getByPlaceholder(/deeper follow-up/i)).toBeVisible();
await expect(page.getByTestId("sidecar-reference-attachment")).toContainText(
"1 selected text fragment",
);
});
test("the source editor quotes the exact text after a CRLF", async ({
page,
}) => {
await setup(page, "# Quarterly report\r\n\r\nTarget paragraph\r\n");
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
return handleRunStream(route);
});
await page.locator("#artifacts").getByLabel("View source").click();
const editor = page.locator("#artifacts .cm-content");
await editor.getByText("Target paragraph", { exact: true }).dblclick({
position: { x: 12, y: 8 },
});
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe(
"Target",
);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
const review = page.getByTestId("artifact-rewrite-review");
await expect(review).toContainText(`${filepath}:L3-L3`);
const composer = page.getByPlaceholder(/deeper follow-up/i);
await composer.fill("Update this word");
await composer
.locator("xpath=ancestor::form")
.getByRole("button", { name: "Rewrite selection", exact: true })
.click();
await expect.poll(() => JSON.stringify(submitted)).toContain("Target");
});
test("a rendered link label cannot match the hidden URL for rewriting", async ({
page,
}) => {
await setup(page, original.replace(selected, "[Budg&#101;t](/files/Budget)"));
await select(page, "Budget");
const toolbar = page.getByTestId("artifact-selection-toolbar");
await expect(
toolbar.getByRole("button", { name: "Rewrite selection" }),
).toBeDisabled();
await expect(
toolbar.getByRole("button", { name: "Ask in side chat" }),
).toBeEnabled();
});
test("a regular send while a rewrite is pending stays a question", async ({
page,
}) => {
await setup(page);
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
return handleRunStream(route);
});
await select(page, selected);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
const composer = page.getByPlaceholder(/deeper follow-up/i);
await composer.fill("What does this section mean?");
await composer.press("Enter");
await expect
.poll(() => JSON.stringify(submitted))
.toContain("What does this section mean?");
expect(JSON.stringify(submitted)).toContain(selected);
expect(JSON.stringify(submitted)).not.toContain("artifact_selection_edit");
expect(JSON.stringify(submitted)).not.toContain(
"Rewrite only the first referenced passage",
);
await expect(page.getByTestId("artifact-rewrite-review")).toBeHidden();
});
test("a rewrite can start when crypto.randomUUID is unavailable", async ({
page,
}) => {
await page.addInitScript(() => {
// Match the Web Crypto API surface on non-loopback HTTP origins.
Object.defineProperty(Crypto.prototype, "randomUUID", { value: undefined });
});
await setup(page);
expect(await page.evaluate(() => typeof crypto.randomUUID)).toBe("undefined");
await select(page, selected);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
await expect(page.getByTestId("artifact-rewrite-review")).toContainText(
`${filepath}:L5-L5`,
);
});
test("clearing the target quote cancels the pending rewrite", async ({
page,
}) => {
await setup(page);
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
return handleRunStream(route);
});
await select(page, selected);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
const panel = page.getByTestId("sidecar-panel");
await panel
.getByRole("button", { name: "Clear selected references" })
.click();
await expect(panel.getByTestId("sidecar-reference-attachment")).toBeHidden();
await expect(panel.getByTestId("artifact-rewrite-review")).toBeHidden();
await expect(
panel.getByRole("button", { name: "Rewrite selection" }),
).toBeHidden();
await expect(
panel.getByRole("button", { name: "Submit", exact: true }),
).toBeDisabled();
expect(submitted).toBeUndefined();
});
for (const discard of ["close draft", "delete thread"] as const) {
test(`ordinary side-chat questions omit a discarded rewrite after ${discard}`, async ({
page,
}) => {
await setup(page);
let submitted: unknown;
await page.route("**/api/langgraph/threads/*/runs/stream", (route) => {
submitted = route.request().postDataJSON();
return handleRunStream(route);
});
await select(page, selected);
await page
.getByTestId("artifact-selection-toolbar")
.getByRole("button", { name: "Rewrite selection" })
.click();
const composer = page.getByPlaceholder(/deeper follow-up/i);
const submit = async (text: string, button = "Submit") => {
await composer.fill(text);
await composer
.locator("xpath=ancestor::form")
.getByRole("button", { name: button, exact: true })
.click();
};
if (discard === "delete thread") {
await submit("Rewrite this line", "Rewrite selection");
await expect
.poll(() => JSON.stringify(submitted))
.toContain("artifact_selection_edit");
await page.getByTestId("sidecar-delete-button").click();
await page.getByTestId("sidecar-delete-confirm-button").click();
} else {
await page.getByTestId("sidecar-close-button").click();
}
await expect(page.getByTestId("sidecar-panel")).toBeHidden();
await page
.getByText("The report is ready.", { exact: true })
.evaluate((paragraph) => {
const range = document.createRange();
range.selectNodeContents(paragraph);
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
paragraph.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
});
await page
.locator("[data-sidecar-selection-toolbar]")
.getByRole("button", { name: "Ask in side chat" })
.click();
await submit("Explain the report");
await expect
.poll(() => JSON.stringify(submitted))
.toContain("Explain the report");
expect(JSON.stringify(submitted)).not.toContain("artifact_selection_edit");
expect(JSON.stringify(submitted)).not.toContain(selected);
});
}

View File

@ -0,0 +1,93 @@
import { afterEach, expect, rs, test } from "@rstest/core";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useArtifactSelection } from "@/components/workspace/artifacts/use-artifact-selection";
import {
SidecarProvider,
useSidecar,
} from "@/components/workspace/sidecar/context";
import { I18nProvider } from "@/core/i18n/context";
rs.mock("@/core/sidecar/api", () => ({
findLatestSidecarThread: async () => null,
}));
afterEach(cleanup);
function Source() {
const selection = useArtifactSelection({
filepath: "/report.md",
threadId: "thread",
ownerId: "owner",
source: "Selected text\nOther text",
revision: "a".repeat(64),
enabled: true,
editable: true,
});
return (
<>
<button
onClick={() =>
selection.onSourceSelection({
from: 0,
to: 13,
rect: { left: 20, bottom: 20 },
})
}
>
Select passage
</button>
{selection.toolbar}
</>
);
}
function Panels() {
const sidecar = useSidecar();
// The real workspace uses one right-hand panel: opening side chat unmounts
// ArtifactFileDetail. The edit must survive that transition.
return (
<>
{!sidecar.open && <Source />}
<output data-testid="target">
{sidecar.artifactEdit?.context.label ?? "none"}
</output>
<output data-testid="references">
{sidecar.conversationQuotes
.map((quote) => quote.context.label)
.join(",")}
</output>
</>
);
}
function App({ threadId = "thread" }: { threadId?: string }) {
return (
<I18nProvider initialLocale="en-US">
<SidecarProvider
parentThreadId={threadId}
context={{ thread_id: threadId, mode: "flash" }}
>
<Panels />
</SidecarProvider>
</I18nProvider>
);
}
test("a rewrite survives the source panel unmount, then clears on chat navigation", () => {
const app = render(<App />);
fireEvent.click(screen.getByText("Select passage"));
fireEvent.click(screen.getByRole("button", { name: "Rewrite selection" }));
expect(screen.queryByText("Select passage")).toBeNull();
expect(screen.getByTestId("target").textContent).toBe("/report.md:L1-L1");
app.rerender(<App threadId="another-thread" />);
expect(screen.getByTestId("target").textContent).toBe("none");
});
test("adding a quotation leaves the source open and carries source provenance", () => {
render(<App />);
fireEvent.click(screen.getByText("Select passage"));
fireEvent.click(screen.getByRole("button", { name: "Add to conversation" }));
expect(screen.getByText("Select passage")).toBeDefined();
expect(screen.getByTestId("references").textContent).toBe("/report.md:L1-L1");
expect(screen.getByTestId("target").textContent).toBe("none");
});

View File

@ -0,0 +1,223 @@
import type { Message } from "@langchain/langgraph-sdk";
import { describe, expect, it } from "@rstest/core";
import {
applyArtifactSelectionDraft,
artifactReplacement,
artifactSelectionContext,
isArtifactRewriteClarification,
locateArtifactSelection,
replaceArtifactSelection,
selectionLines,
sourceSelectionOffsets,
} from "@/core/artifacts/selection";
import { isSameSidecarContext } from "@/core/sidecar";
describe("artifact selections", () => {
it.each([
[1, 2, "\r\n"],
[0, 1, "a"],
[2, 5, "b\r\nc"],
[1, 6, "\r\nb\r\nc\r"],
[6, 7, "d"],
])(
"maps editor offsets %i–%i to the original line endings",
(from, to, expected) => {
const source = "a\r\nb\r\nc\rd";
const offsets = sourceSelectionOffsets(source, { from, to });
expect(source.slice(offsets.from, offsets.to)).toBe(expected);
},
);
it("keeps the rewrite marker only on its own clarification chain", () => {
const messages: Message[] = [
{
type: "human",
content: "Rewrite this",
additional_kwargs: {
sidecar_visible_message: true,
artifact_selection_edit: "edit",
},
},
{
type: "tool",
content: "",
tool_call_id: "tool",
artifact: {
human_input: {
version: 1,
kind: "human_input_request",
source: "ask_clarification",
request_id: "request",
question: "Which tone?",
input_mode: "free_text",
},
},
},
];
expect(isArtifactRewriteClarification(messages, "edit", "request")).toBe(
true,
);
expect(isArtifactRewriteClarification(messages, "edit", "other")).toBe(
false,
);
expect(isArtifactRewriteClarification(messages, "other", "request")).toBe(
false,
);
messages.push({
type: "human",
content: "Ordinary question",
additional_kwargs: { sidecar_visible_message: true },
});
expect(isArtifactRewriteClarification(messages, "edit", "request")).toBe(
false,
);
});
it("locates repeated text only inside its selected source block", () => {
const source = "same\n\nother\n\nsame";
expect(
locateArtifactSelection(source, "same", 0, source.length),
).toBeNull();
expect(locateArtifactSelection(source, "same", 13, 17)).toEqual({
from: 13,
to: 17,
});
});
it("does not guess source offsets for transformed Markdown", () => {
expect(
locateArtifactSelection("hello **world**", "hello world", 0, 15),
).toBeNull();
});
it("preserves every byte outside the selected span, including CRLF and Unicode", () => {
const source = "前文\r\n😀selected\r\n尾文";
const from = source.indexOf("selected"),
to = from + 8;
expect(replaceArtifactSelection(source, { source, from, to }, "改写")).toBe(
"前文\r\n😀改写\r\n尾文",
);
expect(selectionLines(source, from, to)).toEqual({
startLine: 2,
endLine: 2,
});
expect(selectionLines("a\nb\n", 0, 2)).toEqual({
startLine: 1,
endLine: 1,
});
});
it("rejects stale drafts and invalid ranges before applying a replacement", () => {
expect(() =>
replaceArtifactSelection("new", { source: "old", from: 0, to: 1 }, "x"),
).toThrow();
for (const [from, to] of [
[-1, 1],
[2, 1],
[0, 4],
[1, 1],
]) {
expect(() =>
replaceArtifactSelection(
"old",
{ source: "old", from: from!, to: to! },
"x",
),
).toThrow();
}
});
it("keeps identical quotations from different files and line ranges distinct", () => {
const first = artifactSelectionContext("/a.md", "same\n\nsame", "same", {
from: 0,
to: 4,
});
const second = artifactSelectionContext("/a.md", "same\n\nsame", "same", {
from: 6,
to: 10,
});
const other = artifactSelectionContext("/b.md", "same", "same", {
from: 0,
to: 4,
});
expect(first.label).toBe("/a.md:L1-L1");
expect(second.label).toBe("/a.md:L3-L3");
expect(isSameSidecarContext(first, second)).toBe(false);
expect(isSameSidecarContext(first, other)).toBe(false);
expect(isSameSidecarContext(first, { ...first })).toBe(true);
});
it("rejects changed drafts, conflicting versions and files removed while the agent was answering", () => {
const draft = {
filepath: "/a.md",
baselineContent: "before selected after",
draftContent: "before selected after",
baselineSha256: "a",
conflict: false,
};
const edit = {
id: "edit",
context: artifactSelectionContext(
draft.filepath,
draft.draftContent,
"selected",
{ from: 7, to: 15 },
),
filepath: draft.filepath,
threadId: "thread",
source: draft.draftContent,
revision: "a",
from: 7,
to: 15,
};
expect(applyArtifactSelectionDraft(draft, edit, "new")?.draftContent).toBe(
"before new after",
);
for (const changed of [
undefined,
{ ...draft, conflict: true },
{ ...draft, baselineSha256: "b" },
{ ...draft, draftContent: "manual edit" },
{ ...draft, filepath: "/b.md" },
]) {
expect(applyArtifactSelectionDraft(changed, edit, "new")).toBeNull();
}
});
it("offers only the answer to the current edit's submitted request", () => {
const request = {
type: "human" as const,
content: "rewrite",
additional_kwargs: {
sidecar_visible_message: true,
artifact_selection_edit: "edit",
},
};
const answer = {
type: "ai" as const,
content: "```markdown\nreplacement\n```",
};
expect(artifactReplacement([answer], "edit")).toBeNull();
expect(artifactReplacement([request, answer], "other")).toBeNull();
expect(artifactReplacement([request, answer], "edit")).toBe("replacement");
expect(
artifactReplacement(
[request, { ...answer, content: " indented code\n" }],
"edit",
),
).toBe(" indented code\n");
expect(
artifactReplacement(
[
request,
answer,
{ ...request, additional_kwargs: { sidecar_visible_message: true } },
],
"edit",
),
).toBeNull();
expect(
artifactReplacement(
[request, { ...answer, additional_kwargs: { hide_from_ui: true } }],
"edit",
),
).toBeNull();
});
});