Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🪟 feat: Undock the Artifacts Pane into Its Own Window (#15911)
Marco Beretta345a20fe3a1a
diff --git a/client/src/App.jsx b/client/src/App.jsxindex cae2221eec..28b47cf04d 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -4,8 +4,8 @@ import { DndProvider } from 'react-dnd';import { RouterProvider } from 'react-router-dom';import * as RadixToast from '@radix-ui/react-toast';import { HTML5Backend } from 'react-dnd-html5-backend';-import { Toast, ToastProvider, useInputModality } from '@librechat/client';import { QueryClient, QueryClientProvider, QueryCache } from '@tanstack/react-query';+import { Toast, ToastViewport, ToastProvider, useInputModality } from '@librechat/client';import { ScreenshotProvider, useApiErrorBoundary } from './hooks';import WakeLockManager from '~/components/System/WakeLockManager';import QueryDevtoolsGate from '~/components/QueryDevtoolsGate';@@ -75,7 +75,7 @@ const App = () => {<WakeLockManager /><QueryDevtoolsGate /><Toast />- <RadixToast.Viewport className="pointer-events-none fixed inset-x-0 top-0 z-[1000] mx-auto my-2 flex max-w-[560px] flex-col items-stretch justify-start" />+ <ToastViewport /></DndProvider></ToastProvider></RadixToast.Provider>diff --git a/client/src/Providers/ArtifactsContext.tsx b/client/src/Providers/ArtifactsContext.tsxindex 2eb26e04b0..f2bb28fabf 100644--- a/client/src/Providers/ArtifactsContext.tsx+++ b/client/src/Providers/ArtifactsContext.tsx@@ -9,13 +9,23 @@ export interface ArtifactsContextValue {latestMessageId: string | null;latestMessageText: string;conversationId: string | null;+ /** Whether this host offers opening the pane in its own window. The pane+ * consumes the deployment's `interface.artifactUndocking` rather than+ * reading config itself: the host already knows, and only the host knows+ * whether a window it would have to render is available at all. */+ canUndock: boolean;}const ArtifactsContext = createContext<ArtifactsContextValue | undefined>(undefined);interface ArtifactsProviderProps {children: React.ReactNode;- value?: Partial<ArtifactsContextValue>;+ /* The capability has no safe default, so the host has to answer it: a+ * provider that guessed would either offer a window the deployment forbids+ * or hide a control it allows. Everything else here has a chat-shaped+ * fallback the host can leave alone. */+ value: Partial<Omit<ArtifactsContextValue, 'canUndock'>> &+ Pick<ArtifactsContextValue, 'canUndock'>;}export function ArtifactsProvider({ children, value }: ArtifactsProviderProps) {@@ -27,7 +37,7 @@ export function ArtifactsProvider({ children, value }: ArtifactsProviderProps) {return getLatestText(latestMessage);}, [latestMessage]);- const defaultContextValue = useMemo<ArtifactsContextValue>(+ const defaultContextValue = useMemo<Omit<ArtifactsContextValue, 'canUndock'>>(() => ({isSubmitting,conversationId: conversationId ?? null,@@ -38,7 +48,7 @@ export function ArtifactsProvider({ children, value }: ArtifactsProviderProps) {);const contextValue = useMemo<ArtifactsContextValue>(- () => (value ? { ...defaultContextValue, ...value } : defaultContextValue),+ () => ({ ...defaultContextValue, ...value }),[defaultContextValue, value],);diff --git a/client/src/Providers/EditorContext.tsx b/client/src/Providers/EditorContext.tsxindex 1a81d31a2d..16e73b6b46 100644--- a/client/src/Providers/EditorContext.tsx+++ b/client/src/Providers/EditorContext.tsx@@ -1,21 +1,125 @@-import React, { createContext, useContext, useState, useMemo } from 'react';+import React, { createContext, useContext, useState, useMemo, useCallback, useRef } from 'react';+import { useIsMutating } from '@tanstack/react-query';+import { MutationKeys } from 'librechat-data-provider';/*** Mutation state context - for components that need to know about save/edit status* Separated from code state to prevent unnecessary re-renders+ *+ * The state is the request's, not a flag anyone sets: a save outlives the+ * editor that started it — React Query keeps it — and an editor that appears+ * while one is running has to see it. Reading the mutation cache makes "a save+ * is in flight" true exactly while one is, so no session can release a lock it+ * does not hold and none can be left behind by a pane the user closed.*/interface MutationContextType {isMutating: boolean;- setIsMutating: React.Dispatch<React.SetStateAction<boolean>>;}/*** Code state context - for components that need the current code content- * Changes frequently (on every keystroke), so only subscribe if needed+ * Changes frequently (on every keystroke), so only subscribe if needed.+ *+ * The buffer carries the artifact it belongs to. The pane is remounted when it+ * changes hosts (side panel, mobile sheet, undocked window), so whether the+ * buffer is this artifact's unsaved text cannot be decided from a mount.+ *+ * `rejectedCode` is session state rather than editor-instance state because a+ * remount is a host change, not a new decision by the user. It is recorded per+ * artifact for the same reason as the code buffer: a rejection for one+ * artifact must neither suppress a save for another nor be overwritten by+ * another's refusal.+ *+ * A buffer another artifact displaces is retained under the artifact it+ * belongs to: the edit's debounce died with the selection change, so the+ * retained copy is the only place that text still lives, and the editor that+ * gets the artifact back restores and sends it from there.+ *+ * `codeSession` is the editing session the buffer belongs to. A save keeps its+ * callbacks after the editor that started it is gone, and those callbacks+ * would otherwise write the buffer a closed session just cleared and submit+ * its queued edit — so they compare the session they were started in against+ * this live counter. It is a mutable object rather than a value because the+ * comparison happens after the reader's last render.+ *+ * Ending a session leaves a running save alone: the request is not the+ * session's to cancel, and nothing waits on a flag it could clear.+ *+ * `savedContent` is what this tab knows the server holds for each artifact,+ * read and written synchronously because save callbacks run between renders.+ * It outlives a session: the server's content does not change when the pane+ * closes.*/interface CodeContextType {currentCode?: string;- setCurrentCode: React.Dispatch<React.SetStateAction<string | undefined>>;+ codeArtifactId?: string;+ retainedCode: Record<string, string>;+ setCurrentCode: (code: string | undefined, artifactId?: string) => void;+ rejectedCode: Record<string, string>;+ setRejectedCode: (code: string | undefined, artifactId?: string) => void;+ clearCode: (artifactId: string) => void;+ codeSession: { current: number };+ endCodeSession: () => void;+ savedContent: SavedContentLedger;+}++/**+ * A successful save is the server's content before the registry shows it: the+ * edited message propagates afterwards. `base` is the text the last save wrote,+ * and `pending` the values the registry may still show until it catches up, in+ * the order they were replaced. Anything else the registry shows is a change+ * made elsewhere, which wins. `savedBuffer` is the buffer text that save wrote+ * until the buffer changes again: only that copy is known to be saved.+ */+type SavedContent = { base: string; pending: string[]; savedBuffer: string | null };+export type SavedContentLedger = { current: Record<string, SavedContent> };++export function recordSave(+ ledger: SavedContentLedger,+ artifactId: string,+ original: string,+ updated: string,+): void {+ const previous = ledger.current[artifactId];+ ledger.current[artifactId] = {+ base: updated,+ pending: [...(previous?.pending ?? []), original],+ savedBuffer: updated,+ };+}++/**+ * The content an edit of this artifact replaces. Only the values the registry+ * showed before this tab's own saves count as lag; once it reaches the saved+ * text, or moves anywhere else, it is the truth again, so a later revert to an+ * earlier value is not mistaken for lag.+ */+export function resolveServerContent(+ ledger: SavedContentLedger,+ artifactId: string,+ registry: string | undefined,+): string | undefined {+ const entry = ledger.current[artifactId];+ if (entry == null || registry == null) {+ return registry ?? entry?.base;+ }+ const lagging = registry === entry.base ? -1 : entry.pending.indexOf(registry);+ if (lagging >= 0) {+ /* The registry has passed every value before this one. */+ if (lagging > 0) {+ ledger.current[artifactId] = { ...entry, pending: entry.pending.slice(lagging) };+ }+ return entry.base;+ }+ if (entry.pending.length > 0) {+ ledger.current[artifactId] = { ...entry, pending: [] };+ }+ return registry;+}++/** Whether this buffer text is the copy the last save wrote, so it is not unsaved. */+export function isSavedText(ledger: SavedContentLedger, artifactId: string, text: string): boolean {+ return ledger.current[artifactId]?.savedBuffer === text;}const MutationContext = createContext<MutationContextType | undefined>(undefined);@@ -28,11 +132,95 @@ const CodeContext = createContext<CodeContextType | undefined>(undefined);* - CodeContext: for code content (changes on every keystroke)*/export function EditorProvider({ children }: { children: React.ReactNode }) {- const [isMutating, setIsMutating] = useState(false);- const [currentCode, setCurrentCode] = useState<string | undefined>();+ const isMutating = useIsMutating({ mutationKey: [MutationKeys.editArtifact] }) > 0;+ const [codeState, setCodeState] = useState<{+ buffer: { code?: string; artifactId?: string };+ retained: Record<string, string>;+ }>({ buffer: {}, retained: {} });+ const [rejectedCode, setRejectedState] = useState<Record<string, string>>({});+ const codeSession = useRef(0);+ const savedContent = useRef<Record<string, SavedContent>>({});++ const setCurrentCode = useCallback((code: string | undefined, artifactId?: string) => {+ setCodeState((previous) => {+ if (code === undefined) {+ return { ...previous, buffer: {} };+ }+ /* The buffer keeps its owner when the writer does not name one. */+ const owner = artifactId ?? previous.buffer.artifactId;+ const { code: wasCode, artifactId: wasOwner } = previous.buffer;+ const retained = { ...previous.retained };+ /* Displacing another artifact's buffer retains that text under its+ * owner; writing for the same artifact makes the active slot the newest+ * text again, so its retained copy retires. */+ if (wasCode != null && wasOwner != null && wasOwner !== owner) {+ retained[wasOwner] = wasCode;+ }+ if (owner != null) {+ const before = wasOwner === owner ? wasCode : previous.retained[owner];+ const entry = savedContent.current[owner];+ /* Any change to the text makes it the user's again, even one that+ * lands back on what was saved. */+ if (entry != null && before !== code) {+ savedContent.current[owner] = { ...entry, savedBuffer: null };+ }+ delete retained[owner];+ }+ return { buffer: { code, artifactId: owner }, retained };+ });+ }, []);- const mutationValue = useMemo(() => ({ isMutating, setIsMutating }), [isMutating]);- const codeValue = useMemo(() => ({ currentCode, setCurrentCode }), [currentCode]);+ const setRejectedCode = useCallback((code: string | undefined, artifactId?: string) => {+ setRejectedState((previous) => {+ if (artifactId == null) {+ return code === undefined ? {} : previous;+ }+ const next = { ...previous };+ if (code === undefined) {+ delete next[artifactId];+ } else {+ next[artifactId] = code;+ }+ return next;+ });+ }, []);++ const clearCode = useCallback((artifactId: string) => {+ setCodeState((previous) => {+ const retained = { ...previous.retained };+ delete retained[artifactId];+ const buffer = previous.buffer.artifactId === artifactId ? {} : previous.buffer;+ return { buffer, retained };+ });+ }, []);++ const endCodeSession = useCallback(() => {+ codeSession.current += 1;+ setCodeState({ buffer: {}, retained: {} });+ setRejectedState({});+ /* With the buffers gone, an entry only matters while the registry may+ * still lag behind a save. */+ savedContent.current = Object.fromEntries(+ Object.entries(savedContent.current).filter(([, entry]) => entry.pending.length > 0),+ );+ }, []);++ const mutationValue = useMemo(() => ({ isMutating }), [isMutating]);+ const codeValue = useMemo(+ () => ({+ currentCode: codeState.buffer.code,+ codeArtifactId: codeState.buffer.artifactId,+ retainedCode: codeState.retained,+ setCurrentCode,+ rejectedCode,+ setRejectedCode,+ clearCode,+ codeSession,+ endCodeSession,+ savedContent,+ }),+ [clearCode, codeState, endCodeSession, rejectedCode, setCurrentCode, setRejectedCode],+ );return (<MutationContext.Provider value={mutationValue}>@@ -74,3 +262,16 @@ export function useEditorContext() {const code = useCodeState();return { ...mutation, ...code };}++/**+ * The text an artifact's editing surface should show: its active buffer when+ * the artifact owns it, the copy retained when another artifact's edit+ * displaced it, and nothing when the artifact never had unsaved text. Every+ * consumer of the buffer (the editor, both tab hosts, download) resolves it+ * the same way, so the code tab, the preview and an export can never disagree+ * about which text is the artifact's own.+ */+export function useArtifactCode(artifactId: string): string | undefined {+ const { currentCode, codeArtifactId, retainedCode } = useCodeState();+ return codeArtifactId === artifactId ? currentCode : retainedCode[artifactId];+}diff --git a/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx b/client/src/components/Artifacts/ArtifactCodeEditor.test.tsxindex 8b6588fcc6..85d693f9f1 100644--- a/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx+++ b/client/src/components/Artifacts/ArtifactCodeEditor.test.tsx@@ -1,5 +1,6 @@import React from 'react';import { render, act } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { ThemeContext, highContrastDarkTheme, highContrastLightTheme } from '@librechat/client';import type { Monaco } from '@monaco-editor/react';import type { IThemeRGB } from '@librechat/client';@@ -45,14 +46,50 @@ jest.mock('@monaco-editor/react', () => ({jest.mock('~/Providers/EditorContext', () => {const ReactModule = jest.requireActual<typeof import('react')>('react');+ const actual = jest.requireActual<typeof import('~/Providers/EditorContext')>(+ '~/Providers/EditorContext',+ );return {- useMutationState: () => {- const [isMutating, setIsMutating] = ReactModule.useState(false);- return { isMutating, setIsMutating };- },+ isSavedText: actual.isSavedText,+ recordSave: actual.recordSave,+ resolveServerContent: actual.resolveServerContent,+ useMutationState: () => ({ isMutating: false }),useCodeState: () => {const [currentCode, setCurrentCode] = ReactModule.useState('');- return { currentCode, setCurrentCode };+ const [rejectedCode, setRejectedState] = ReactModule.useState<Record<string, string>>({});+ const setRejectedCode = ReactModule.useCallback(+ (code: string | undefined, artifactId?: string) => {+ setRejectedState((previous) => {+ if (artifactId == null) {+ return code === undefined ? {} : previous;+ }+ const next = { ...previous };+ if (code === undefined) {+ delete next[artifactId];+ } else {+ next[artifactId] = code;+ }+ return next;+ });+ },+ [],+ );+ const codeSession = ReactModule.useRef(0);+ const savedContent = ReactModule.useRef({});+ const endCodeSession = ReactModule.useCallback(() => {+ codeSession.current += 1;+ }, []);+ return {+ currentCode,+ setCurrentCode,+ retainedCode: {},+ rejectedCode,+ setRejectedCode,+ clearCode: () => {},+ codeSession,+ endCodeSession,+ savedContent,+ };},};});@@ -101,17 +138,22 @@ const renderEditor = (initial: Artifact = artifact, initialAppearance = defaultAconst monacoRef: React.MutableRefObject<editor.IStandaloneCodeEditor | null> = { current: null };let currentArtifact = initial;let currentAppearance = initialAppearance;+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false }, queries: { retry: false } },+ });const tree = () => (- <ThemeContext.Provider- value={- {- resolvedMode: currentAppearance.resolvedMode,- highContrast: currentAppearance.highContrast,- } as React.ContextType<typeof ThemeContext>- }- >- <ArtifactCodeEditor artifact={currentArtifact} monacoRef={monacoRef} />- </ThemeContext.Provider>+ <QueryClientProvider client={client}>+ <ThemeContext.Provider+ value={+ {+ resolvedMode: currentAppearance.resolvedMode,+ highContrast: currentAppearance.highContrast,+ } as React.ContextType<typeof ThemeContext>+ }+ >+ <ArtifactCodeEditor artifact={currentArtifact} monacoRef={monacoRef} />+ </ThemeContext.Provider>+ </QueryClientProvider>);const utils = render(tree());const rerenderWith = (next: Artifact) => {diff --git a/client/src/components/Artifacts/ArtifactCodeEditor.tsx b/client/src/components/Artifacts/ArtifactCodeEditor.tsxindex ad1b42b420..a077d9599c 100644--- a/client/src/components/Artifacts/ArtifactCodeEditor.tsx+++ b/client/src/components/Artifacts/ArtifactCodeEditor.tsx@@ -6,7 +6,13 @@ import type { Monaco } from '@monaco-editor/react';import type { IThemeRGB } from '@librechat/client';import type { editor } from 'monaco-editor';import type { Artifact } from '~/common';-import { useMutationState, useCodeState } from '~/Providers/EditorContext';+import {+ isSavedText,+ recordSave,+ useCodeState,+ useMutationState,+ resolveServerContent,+} from '~/Providers/EditorContext';import { getResponseStatus } from '~/utils/errors';import { useArtifactsContext } from '~/Providers';import { useEditArtifact } from '~/data-provider';@@ -186,6 +192,7 @@ type PendingUpdate = ArtifactEditTarget & {type ArtifactMutationVars = {messageId: string;index: number;+ original: string;updated: string;};@@ -232,34 +239,82 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({const { resolvedMode, highContrast } = useContext(ThemeContext);const { isSubmitting } = useArtifactsContext();const readOnly = (externalReadOnly ?? false) || isSubmitting;- const { setCurrentCode } = useCodeState();+ const {+ currentCode,+ codeArtifactId,+ retainedCode,+ setCurrentCode,+ rejectedCode,+ setRejectedCode,+ clearCode,+ codeSession,+ savedContent,+ } = useCodeState();+ /* The pane is remounted when it changes hosts (side panel, mobile sheet,+ * undocked window). The buffer outlives that remount, so unsaved text is+ * restored here instead of falling back to the persisted content. An edit+ * another artifact displaced from the active slot is retained under this+ * artifact, so coming back to it lands on its own unsaved text too. The+ * same resolution serves the preview and the export, so every surface of+ * the artifact shows one text. */+ const restoredCode = codeArtifactId === artifact.id ? currentCode : retainedCode[artifact.id];const [currentUpdate, setCurrentUpdate] = useState<string | null>(null);- const { isMutating, setIsMutating } = useMutationState();- const [failedContent, setFailedContent] = useState<string | null>(null);+ const { isMutating } = useMutationState();const artifactRef = useRef(artifact);const isMutatingRef = useRef(isMutating);const currentUpdateRef = useRef(currentUpdate);const setCurrentCodeRef = useRef(setCurrentCode);- const failedContentRef = useRef(failedContent);+ const rejectedCodeRef = useRef(rejectedCode);const pendingUpdateRef = useRef<PendingUpdate | null>(null);const runMutationRef = useRef<(code: string, original?: string) => void>(() => {});+ /** Read by the mount effect below, which must not re-run as the user types. */+ const restoredCodeRef = useRef(restoredCode);+ /* The session a save was started in. Its callbacks outlive the editor, so+ * they compare this against the live session before touching the buffer or+ * submitting a queued edit: both belong to whoever is editing now, and a+ * pane the user closed is not it. The save itself is left alone — it is the+ * request's to finish, and `isMutating` reports it until it does. */+ const mutationSessionRef = useRef(codeSession.current);+ /* The artifact a save was started for. Its callbacks answer later, by which+ * time the user may have selected another artifact, and a rejection belongs+ * to the text that was refused rather than to whatever is on screen when+ * the refusal lands. */+ const mutationArtifactIdRef = useRef<string | null>(null);+ /* The buffer this instance inherited at mount, and whether it has been+ * dealt with. It is the oldest text in play: anything the user types here+ * supersedes it, so both the drain and the queue consult these. */+ const inheritedBufferRef = useRef<string | null>(restoredCode ?? null);+ const drainedBufferRef = useRef<string | null>(null);+ const isStaleSession = () => codeSession.current !== mutationSessionRef.current;const editArtifact = useEditArtifact({onMutate: (vars) => {isMutatingRef.current = true;currentUpdateRef.current = vars.updated;- setIsMutating(true);setCurrentUpdate(vars.updated);},onSuccess: (_data, vars) => {- isMutatingRef.current = false;currentUpdateRef.current = null;- setIsMutating(false);- setCurrentUpdate(null);- setFailedContent(null);-+ /* What the server now holds is true whoever is editing, so it is+ * recorded before the session check below. */+ recordSave(+ savedContent,+ mutationArtifactIdRef.current ?? artifactRef.current.id,+ vars.original,+ vars.updated,+ );+ /* A save that outlived its session reports to nobody: the buffer and any+ * queued edit belong to whoever is editing now. */+ if (isStaleSession()) {+ return;+ }const pending = pendingUpdateRef.current;pendingUpdateRef.current = null;+ setCurrentUpdate(null);+ /* Only this save's own artifact is cleared: another artifact's refusal+ * is still a refusal. */+ const savedArtifactId = mutationArtifactIdRef.current ?? artifactRef.current.id;+ setRejectedCode(undefined, savedArtifactId);const currentTarget = getArtifactEditTarget(artifactRef.current);if (pending == null ||@@ -271,21 +326,23 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({const original = isSameMutationTarget(pending, vars) ? vars.updated : pending.original;if (pending.code.trim() !== original.trim()) {- setCurrentCodeRef.current(pending.code);+ setCurrentCodeRef.current(pending.code, artifactRef.current.id);runMutationRef.current(pending.code, original);}},onError: (error) => {- const status = getResponseStatus(error);- if (status === 400 && currentUpdateRef.current != null) {- setFailedContent(currentUpdateRef.current);- failedContentRef.current = currentUpdateRef.current;+ const attempted = currentUpdateRef.current;+ currentUpdateRef.current = null;+ if (isStaleSession()) {+ return;}const pending = pendingUpdateRef.current;pendingUpdateRef.current = null;- isMutatingRef.current = false;- currentUpdateRef.current = null;- setIsMutating(false);++ const status = getResponseStatus(error);+ if (status === 400 && attempted != null) {+ setRejectedCode(attempted, mutationArtifactIdRef.current ?? artifactRef.current.id);+ }setCurrentUpdate(null);const currentTarget = getArtifactEditTarget(artifactRef.current);@@ -298,7 +355,7 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({}if (pending.code.trim() !== pending.original.trim()) {- setCurrentCodeRef.current(pending.code);+ setCurrentCodeRef.current(pending.code, artifactRef.current.id);runMutationRef.current(pending.code, pending.original);}},@@ -314,7 +371,8 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({currentUpdateRef.current = currentUpdate;editArtifactRef.current = editArtifact;setCurrentCodeRef.current = setCurrentCode;- failedContentRef.current = failedContent;+ rejectedCodeRef.current = rejectedCode;+ restoredCodeRef.current = restoredCode;const runMutation = useCallback((code: string, originalOverride?: string) => {@@ -324,7 +382,34 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({return;}- const original = originalOverride ?? art.content ?? '';+ /* An empty editor is not an instruction to delete the artifact. Typing+ * never saves it — a user who selects all and deletes is mid-edit — and+ * the paths that resubmit retained text must not turn that into a+ * deletion just because the pane changed hosts or the user came back to+ * the artifact. The rule belongs here, with the rest of what decides+ * whether a request goes out. */+ if (code.length === 0) {+ return;+ }++ /* What an edit replaces is whatever the last save wrote, and the+ * registry catches up only when the edited message propagates — so+ * every path that sends text (a keystroke's debounce, a queued edit, a+ * buffer inherited at mount, one restored on the way back to an+ * artifact) rebases here rather than each remembering to. Sending a+ * registry that has not caught up has the endpoint refuse the newest+ * text, and three of those paths have had to learn that separately. */+ const original =+ originalOverride ?? resolveServerContent(savedContent, art.id, art.content) ?? '';+ /* Anything this instance sends is newer than the buffer it inherited at+ * mount, so that older text stops being a candidate for the drain —+ * whether this goes out now or waits behind a running save. Left in+ * play, it would be sent once this one lands and would quietly put the+ * user's edit back the way it was. The drain itself passes the+ * inherited text, which is how it stays exempt. */+ if (inheritedBufferRef.current !== code) {+ drainedBufferRef.current = inheritedBufferRef.current;+ }if (isMutatingRef.current) {pendingUpdateRef.current = {...target,@@ -342,11 +427,14 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({return;}- if (failedContentRef.current != null && code.trim() === failedContentRef.current.trim()) {+ const rejected = rejectedCodeRef.current[art.id];+ if (rejected != null && code.trim() === rejected.trim()) {return;}- setCurrentCodeRef.current(code);+ mutationSessionRef.current = codeSession.current;+ mutationArtifactIdRef.current = target.artifactId;+ setCurrentCodeRef.current(code, art.id);editArtifactRef.current.mutate({index: target.index,messageId: target.messageId,@@ -354,11 +442,23 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({updated: code,});},- [readOnly],+ [codeSession, readOnly, savedContent],);runMutationRef.current = runMutation;+ /** The value this component last wrote into the model, held until the change+ * event it produces arrives. */+ const programmaticValueRef = useRef<string | null>(null);+ const writeModelValue = useCallback((ed: editor.IStandaloneCodeEditor, value: string) => {+ const model = ed.getModel();+ if (!model || model.getValue() === value) {+ return;+ }+ programmaticValueRef.current = value;+ model.setValue(value);+ }, []);+const debouncedMutation = useMemo(() =>debounce((code: string) => {@@ -371,6 +471,110 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({return () => debouncedMutation.cancel();}, [artifact.id, debouncedMutation]);+ /* Declared ahead of the drain below: when editing becomes available again,+ * the persisted content lands first and an inherited buffer the drain is+ * still holding is written over it, rather than the other way round. */+ useEffect(() => {+ if (prevReadOnly.current && !readOnly && artifact.content != null) {+ const ed = monacoRef.current;+ if (ed) {+ writeModelValue(ed, artifact.content);+ prevContentRef.current = artifact.content;+ }+ }+ prevReadOnly.current = readOnly;+ }, [readOnly, artifact.content, monacoRef, writeModelValue]);++ /* A remount cancels the debounce mid-flight, so text the user typed just+ * before the pane changed hosts lives in the buffer and has never been sent.+ * The request its previous instance started keeps its own callbacks — React+ * Query holds them on the mutation, not on the observer — so this instance+ * must not guess at that request's state or resubmit against an `original`+ * it may already have replaced. It waits for the shared flag to go idle and+ * submits then, once.+ *+ * Only the buffer this instance inherited at mount is drained. A buffer+ * picked up by navigating back to an artifact belongs to an editor that is+ * still alive and will send it itself; submitting it here would race that+ * editor's own `setValue`.+ *+ * A read-only editor cannot save, so nothing is drained while a response is+ * generating: the buffer stays in play and goes out once editing returns. */+ useEffect(() => {+ if (isMutating || readOnly) {+ return;+ }++ /* An edit typed while a save was in flight is queued here, and normally+ * the callbacks of that save send it. Those callbacks belong to whichever+ * editor started it, so when the save was started by a previous session+ * nobody else will: this editor sends its own queued edit as soon as the+ * pipeline is idle.+ *+ * What that edit replaces is whatever the last save wrote, which is not+ * necessarily `artifact.content` yet — the registry catches up when the+ * edited message propagates. Sending either the content captured when the+ * edit was queued or a registry that has not caught up has the endpoint+ * reject the newest text, so the request's own record decides. */+ const queued = pendingUpdateRef.current;+ if (queued != null) {+ pendingUpdateRef.current = null;+ const currentTarget = getArtifactEditTarget(artifactRef.current);+ if (currentTarget != null && isSameArtifactTarget(queued, currentTarget)) {+ const original =+ resolveServerContent(+ savedContent,+ currentTarget.artifactId,+ artifactRef.current.content,+ ) ?? queued.original;+ if (queued.code.trim() !== original.trim()) {+ setCurrentCodeRef.current(queued.code, artifactRef.current.id);+ runMutationRef.current(queued.code, original);+ return;+ }+ }+ }++ const inherited = inheritedBufferRef.current;+ if (inherited == null || drainedBufferRef.current === inherited) {+ return;+ }+ const inheritedTarget = getArtifactEditTarget(artifactRef.current);+ const inheritedOriginal =+ resolveServerContent(savedContent, artifactRef.current.id, artifactRef.current.content) ?? '';+ if (inherited === inheritedOriginal) {+ return;+ }+ drainedBufferRef.current = inherited;+ const ed = monacoRef.current;+ /* Text this tab already saved is not unsaved: when the server has moved+ * past it since, the newer content is what the pane shows, and nothing is+ * sent on the user's behalf. */+ if (isSavedText(savedContent, artifactRef.current.id, inherited)) {+ clearCode(artifactRef.current.id);+ prevContentRef.current = inheritedOriginal;+ if (ed) {+ writeModelValue(ed, inheritedOriginal);+ }+ return;+ }+ prevContentRef.current = inherited;+ if (ed) {+ writeModelValue(ed, inherited);+ }+ const rejected = rejectedCodeRef.current[artifactRef.current.id];+ if (inheritedTarget != null && rejected != null && inherited.trim() === rejected.trim()) {+ return;+ }+ runMutationRef.current(inherited, inheritedOriginal);+ }, [isMutating, readOnly, savedContent, clearCode, monacoRef, writeModelValue]);++ /* The registry reaching this tab's last save ends the lag, so a later+ * change elsewhere (even back to an earlier value) is read as the truth. */+ useEffect(() => {+ resolveServerContent(savedContent, artifact.id, artifact.content);+ }, [artifact.id, artifact.content, savedContent]);+/*** Streaming: use model.applyEdits() to append new content.* Unlike setValue/pushEditOperations, applyEdits preserves existing@@ -415,38 +619,67 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({ed.revealLine(model.getLineCount());}, [artifact.content, readOnly, monacoRef]);+ /* Selecting another artifact and coming back has to land on this artifact's+ * own text: its unsaved buffer when it has one, the persisted content+ * otherwise. Writing the persisted content over a retained edit would queue+ * that content behind the edit and quietly undo it.+ *+ * A retained buffer is also sent here. Its own debounce was cancelled when+ * the selection moved away, so this is where that edit finally becomes a+ * save — and it is sent for the artifact it belongs to, which is the one on+ * screen again. The rejection marker is deliberately left alone: it names+ * the artifact it was recorded for, so it cannot suppress this artifact's+ * save, and dropping it here would let this resend put the one text the+ * endpoint already refused back on the wire. */useEffect(() => {if (artifact.id === prevArtifactId.current) {return;}prevArtifactId.current = artifact.id;pendingUpdateRef.current = null;- setFailedContent(null);- prevContentRef.current = artifact.content ?? '';+ const server = resolveServerContent(savedContent, artifact.id, artifact.content);+ /* A retained copy of text this tab already saved is not an edit to send:+ * the server's content is the artifact's text again. */+ const stale =+ restoredCodeRef.current != null &&+ restoredCodeRef.current !== server &&+ isSavedText(savedContent, artifact.id, restoredCodeRef.current);+ if (stale) {+ clearCode(artifact.id);+ }+ const restored = stale ? undefined : restoredCodeRef.current;+ const nextValue = restored ?? server;+ prevContentRef.current = nextValue ?? '';const ed = monacoRef.current;- if (ed && artifact.content != null) {- ed.getModel()?.setValue(artifact.content);+ if (ed && nextValue != null) {+ writeModelValue(ed, nextValue);}- }, [artifact.id, artifact.content, monacoRef]);-- useEffect(() => {- if (prevReadOnly.current && !readOnly && artifact.content != null) {- const ed = monacoRef.current;- if (ed) {- ed.getModel()?.setValue(artifact.content);- prevContentRef.current = artifact.content;- }+ /* `runMutation` decides what this replaces, and refuses text that would+ * change nothing or that the endpoint already rejected. */+ if (restored != null) {+ runMutationRef.current(restored);}- prevReadOnly.current = readOnly;- }, [readOnly, artifact.content, monacoRef]);+ }, [artifact.id, artifact.content, savedContent, clearCode, monacoRef, writeModelValue]);+ /* Monaco reports a write this component made through `onChange` like any+ * other edit. Treating it as typing would key the shared buffer to the+ * artifact now on screen and drop the unsaved text another artifact is+ * holding, so the value written here is recognised and consumed. */const handleChange = useCallback((value: string | undefined) => {- if (value === undefined || readOnly) {+ if (value === undefined) {+ return;+ }+ const programmatic = programmaticValueRef.current;+ programmaticValueRef.current = null;+ if (readOnly) {return;}prevContentRef.current = value;- setCurrentCode(value);+ if (programmatic != null && value === programmatic) {+ return;+ }+ setCurrentCode(value, artifactRef.current.id);if (value.length > 0) {debouncedMutation(value);}@@ -571,7 +804,7 @@ export const ArtifactCodeEditor = function ArtifactCodeEditor({height="100%"language={readOnly ? 'plaintext' : language}theme={editorAppearance.theme}- defaultValue={artifact.content}+ defaultValue={restoredCode ?? artifact.content}onChange={handleChange}beforeMount={handleBeforeMount}onMount={handleMount}diff --git a/client/src/components/Artifacts/ArtifactTabs.test.tsx b/client/src/components/Artifacts/ArtifactTabs.test.tsxindex a8c207c719..c6111419c2 100644--- a/client/src/components/Artifacts/ArtifactTabs.test.tsx+++ b/client/src/components/Artifacts/ArtifactTabs.test.tsx@@ -16,6 +16,7 @@ const mockUseGetSharedStartupConfig = jest.fn((_shareId?: unknown, _options?: undata: {},}));let mockCurrentCode: string | undefined;+let mockCodeArtifactId: string | undefined;jest.mock('./ArtifactCodeEditor', () => ({ArtifactCodeEditor: (props: EditorProps) => mockEditor(props),@@ -52,7 +53,8 @@ jest.mock('~/components/Messages/Content/Mermaid/Mermaid', () => {});jest.mock('~/Providers/EditorContext', () => ({- useCodeState: () => ({ currentCode: mockCurrentCode, setCurrentCode: jest.fn() }),+ useArtifactCode: (artifactId: string) =>+ mockCodeArtifactId === artifactId ? mockCurrentCode : undefined,}));jest.mock('~/Providers', () => ({@@ -87,6 +89,7 @@ describe('ArtifactTabs Mermaid editing', () => {mockUseGetStartupConfig.mockClear();mockUseGetSharedStartupConfig.mockClear();mockCurrentCode = undefined;+ mockCodeArtifactId = undefined;});it('renders Mermaid natively without loading startup config or Sandpack preview', () => {@@ -139,9 +142,10 @@ describe('ArtifactTabs Mermaid editing', () => {</Tabs.Root>,);- /* Editor text only belongs to the preview once it was typed against the- * artifact on screen, so it is applied on a later render, not on mount. */+ /* Editor text belongs to the preview only while it is this artifact's+ * buffer, so the ownership the editor recorded is what applies it. */mockCurrentCode = 'graph TD\nA-->C';+ mockCodeArtifactId = artifact.id;rerender(<Tabs.Root value="preview"><ArtifactTabs artifact={artifact} previewRef={previewRef} />@@ -231,12 +235,13 @@ describe('ArtifactTabs Mermaid editing', () => {};mockCurrentCode = 'graph TD\nEDITED-->A';+ mockCodeArtifactId = first.id;const { rerender } = render(<Tabs.Root value="preview"><ArtifactTabs artifact={first} previewRef={previewRef} /></Tabs.Root>,);-+ testGlobal.nativeMermaidRenderer?.mockClear();rerender(<Tabs.Root value="preview"><ArtifactTabs artifact={second} previewRef={previewRef} />diff --git a/client/src/components/Artifacts/ArtifactTabs.tsx b/client/src/components/Artifacts/ArtifactTabs.tsxindex 4c9ea9771e..c1461f86ff 100644--- a/client/src/components/Artifacts/ArtifactTabs.tsx+++ b/client/src/components/Artifacts/ArtifactTabs.tsx@@ -1,4 +1,4 @@-import { lazy, Suspense, useEffect, useRef } from 'react';+import { lazy, Suspense, useRef } from 'react';import { Spinner } from '@librechat/client';import * as Tabs from '@radix-ui/react-tabs';import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled';@@ -6,8 +6,8 @@ import type { editor } from 'monaco-editor';import type { ProcessedMermaidSvg } from '~/utils/diagram/export';import { MermaidRenderer } from '~/components/Messages/Content/Mermaid/Mermaid';import { MERMAID_ARTIFACT_TYPE, type Artifact } from '~/common/artifacts';+import { useArtifactCode } from '~/Providers/EditorContext';import { ArtifactCodeEditor } from './ArtifactCodeEditor';-import { useCodeState } from '~/Providers/EditorContext';import { useLocalize } from '~/hooks';const SandboxArtifactTabs = lazy(() => import('./SandboxArtifactTabs'));@@ -39,24 +39,14 @@ function MermaidArtifactTabs({onMermaidExportReady,}: Omit<ArtifactTabsProps, 'previewRef'>) {const localize = useLocalize();- const { currentCode, setCurrentCode } = useCodeState();+ const editedCode = useArtifactCode(artifact.id);const monacoRef = useRef<editor.IStandaloneCodeEditor | null>(null);- const lastIdRef = useRef<string | null>(null);- /* The reset below only lands after commit, so on the render that switches- * artifacts `currentCode` still holds the previous artifact's editor text.- * Ignore it until the reset catches up, or the freshly keyed renderer would- * mount showing (and exporting) the diagram we just navigated away from. */- const hasCurrentArtifactCode = lastIdRef.current === artifact.id;-- useEffect(() => {- if (artifact.id !== lastIdRef.current) {- setCurrentCode(undefined);- }- lastIdRef.current = artifact.id;- }, [artifact.id, setCurrentCode]);-- const content = (hasCurrentArtifactCode ? currentCode : undefined) ?? artifact.content ?? '';+ /* The buffer belongs to whichever artifact last wrote it: a freshly keyed+ * renderer must not show (or export) the diagram we navigated away from,+ * while a pane that remounted for another host keeps its unsaved text and a+ * displaced copy is just as much this artifact's own. */+ const content = editedCode ?? artifact.content ?? '';const isReadOnly = isSharedConvo === true || artifact.index == null;return (diff --git a/client/src/components/Artifacts/Artifacts.test.tsx b/client/src/components/Artifacts/Artifacts.test.tsxindex 6b3206349e..73ff4a5344 100644--- a/client/src/components/Artifacts/Artifacts.test.tsx+++ b/client/src/components/Artifacts/Artifacts.test.tsx@@ -1,6 +1,8 @@import React from 'react';+import { getDefaultStore } from 'jotai';import { RecoilRoot, useRecoilValue } from 'recoil';-import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { undockedArtifacts } from './state';import Artifacts from './Artifacts';import store from '~/store';@@ -14,9 +16,12 @@ jest.mock('@librechat/client', () => ({query === '(prefers-reduced-motion: reduce)' ? mockPrefersReducedMotion : mockIsMobile,}));+let mockCanUndock = true;+jest.mock('~/Providers', () => ({useMutationState: () => ({ isMutating: false }),useShareContext: () => ({ isSharedConvo: false }),+ useArtifactsContext: () => ({ canUndock: mockCanUndock }),}));jest.mock('~/hooks', () => ({@@ -94,6 +99,7 @@ describe('Artifacts panel accessibility', () => {beforeEach(() => {mockIsMobile = false;mockPrefersReducedMotion = false;+ mockCanUndock = true;mockUseArtifacts.mockReturnValue({activeTab: 'code',setActiveTab: jest.fn(),@@ -337,4 +343,126 @@ describe('Artifacts panel accessibility', () => {opener.remove();});++ describe('undocking', () => {+ const jotaiStore = getDefaultStore();+ let openSpy: jest.SpyInstance<Window | null>;++ beforeEach(() => {+ act(() => jotaiStore.set(undockedArtifacts, null));+ openSpy = jest.spyOn(window, 'open');+ });++ afterEach(() => {+ openSpy.mockRestore();+ act(() => jotaiStore.set(undockedArtifacts, null));+ });++ it('opens a window from the click and offers to dock back', async () => {+ const detached = {+ focus: jest.fn(),+ closed: false,+ document: document.implementation.createHTMLDocument(''),+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ close: jest.fn(),+ } as unknown as Window;+ openSpy.mockReturnValue(detached);++ render(+ <RecoilRoot>+ <Artifacts />+ </RecoilRoot>,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_undock_artifacts' }));++ expect(openSpy).toHaveBeenCalledWith(+ '',+ expect.stringContaining('librechat-artifacts'),+ expect.any(String),+ );+ expect(jotaiStore.get(undockedArtifacts)?.window).toBe(detached);+ expect(+ await screen.findByRole('button', { name: 'com_ui_dock_artifacts' }),+ ).toBeInTheDocument();+ });++ /* A blocked popup must leave the pane where it is, not hide it in a window+ * that never opened. */+ it('stays docked when the browser blocks the window', async () => {+ openSpy.mockReturnValue(null);++ render(+ <RecoilRoot>+ <Artifacts />+ </RecoilRoot>,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'com_ui_undock_artifacts' }));++ expect(jotaiStore.get(undockedArtifacts)).toBeNull();+ expect(screen.getByRole('button', { name: 'com_ui_undock_artifacts' })).toBeInTheDocument();+ });++ it('has no undock action on the mobile sheet', async () => {+ mockIsMobile = true;++ render(+ <RecoilRoot>+ <Artifacts />+ </RecoilRoot>,+ );++ await screen.findByRole('dialog', { name: 'Diagram' });+ expect(+ screen.queryByRole('button', { name: 'com_ui_undock_artifacts' }),+ ).not.toBeInTheDocument();+ });++ it('offers no undock action where the deployment turned it off', async () => {+ mockCanUndock = false;++ render(+ <RecoilRoot>+ <Artifacts />+ </RecoilRoot>,+ );++ await screen.findByTestId('artifact-content');+ expect(+ screen.queryByRole('button', { name: 'com_ui_undock_artifacts' }),+ ).not.toBeInTheDocument();+ });++ /* Losing the capability while the pane is out there must not strand it in+ * a window with no way back. */+ it('keeps the dock action when the capability goes away while undocked', async () => {+ const detached = {+ focus: jest.fn(),+ closed: false,+ document: document.implementation.createHTMLDocument(''),+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ close: jest.fn(),+ } as unknown as Window;+ act(() =>+ jotaiStore.set(undockedArtifacts, {+ window: detached,+ root: document.createElement('div'),+ }),+ );+ mockCanUndock = false;++ render(+ <RecoilRoot>+ <Artifacts />+ </RecoilRoot>,+ );++ expect(+ await screen.findByRole('button', { name: 'com_ui_dock_artifacts' }),+ ).toBeInTheDocument();+ });+ });});diff --git a/client/src/components/Artifacts/Artifacts.tsx b/client/src/components/Artifacts/Artifacts.tsxindex 57496db604..2f93beb32c 100644--- a/client/src/components/Artifacts/Artifacts.tsx+++ b/client/src/components/Artifacts/Artifacts.tsx@@ -1,15 +1,27 @@import { useRef, useState, useEffect, useCallback, useMemo } from 'react';+import { useAtom } from 'jotai';import copy from 'copy-to-clipboard';import * as Tabs from '@radix-ui/react-tabs';import { useSetRecoilState, useResetRecoilState } from 'recoil';-import { Button, Spinner, useMediaQuery, Radio } from '@librechat/client';-import { Code, Maximize2, Minimize2, Play, RefreshCw, X } from 'lucide-react';+import { Button, Spinner, useMediaQuery, Radio, useToastContext } from '@librechat/client';+import {+ Code,+ Maximize2,+ Minimize2,+ PanelRight,+ PictureInPicture2,+ Play,+ RefreshCw,+ X,+} from 'lucide-react';import type { SandpackPreviewRef } from '@codesandbox/sandpack-react';import type { ProcessedMermaidSvg } from '~/utils/diagram/export';import { TOOL_ARTIFACT_TYPES, isCodeOnlyArtifact, isPreviewOnlyArtifact } from '~/utils/artifacts';+import { copyWithinDocument, openUndockedWindow, prepareUndockedDocument } from './undockedWindow';+import { artifactsOpenedArtifactId, artifactsPaneFocusRequest, undockedArtifacts } from './state';import { displayFilename } from '~/components/Chat/Messages/Content/Parts/attachmentTypes';+import { useArtifactsContext, useShareContext, useMutationState } from '~/Providers';import CopyButton from '~/components/Messages/Content/CopyButton';-import { useShareContext, useMutationState } from '~/Providers';import useArtifacts from '~/hooks/Artifacts/useArtifacts';import { useFocusTrap, useLocalize } from '~/hooks';import DownloadArtifact from './DownloadArtifact';@@ -26,17 +38,30 @@ export default function Artifacts() {const localize = useLocalize();const { isMutating } = useMutationState();const { isSharedConvo } = useShareContext();- const isMobile = useMediaQuery('(max-width: 868px)');+ /* A deployment can keep the docked pane: the host resolves+ * `interface.artifactUndocking` and passes the answer in. */+ const { canUndock } = useArtifactsContext();+ const [detached, setDetached] = useAtom(undockedArtifacts);+ const [paneFocusRequest, setPaneFocusRequest] = useAtom(artifactsPaneFocusRequest);+ const isUndocked = detached != null;+ const undockButtonRef = useRef<HTMLButtonElement>(null);+ /* The undocked window is its own viewport: the host's width says nothing+ * about it, and a bottom sheet — backdrop, drag handle, no dock action — is+ * not what a window wants to be. */+ const isMobile = useMediaQuery('(max-width: 868px)') && !isUndocked;const prefersReducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)');const previewRef = useRef<SandpackPreviewRef>();const artifactContainerRef = useRef<HTMLDivElement>(null);- const fullscreenPortalRef = useRef<HTMLDivElement>(null);+ const [fullscreenPortal, setFullscreenPortal] = useState<HTMLDivElement | null>(null);const panelRef = useRef<HTMLDivElement>(null);const openerRef = useRef<HTMLElement | null>(null);const [isVisible, setIsVisible] = useState(false);const [isClosing, setIsClosing] = useState(false);const [isRefreshing, setIsRefreshing] = useState(false);const [isFullscreen, setIsFullscreen] = useState(false);+ const [fullscreenEnabled, setFullscreenEnabled] = useState(+ typeof document === 'undefined' ? false : document.fullscreenEnabled,+ );const [isMounted, setIsMounted] = useState(false);const [height, setHeight] = useState(90);const [isDragging, setIsDragging] = useState(false);@@ -50,6 +75,10 @@ export default function Artifacts() {const dragStartHeight = useRef(90);const setArtifactsVisible = useSetRecoilState(store.artifactsVisibility);const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);+ const { showToast } = useToastContext();+ /* Radix portals default to the host document's body, which is the wrong+ * window once undocked — and the wrong stacking context in fullscreen. */+ const overlayPortal = isFullscreen || isUndocked ? (fullscreenPortal ?? undefined) : undefined;const allTabOptions = useMemo(() => [@@ -81,15 +110,20 @@ export default function Artifacts() {};}, [isMobile]);+ /* Undocked, the pane lives in the popup's document: its fullscreen element+ * and its change events belong to that document, not the host's. The+ * container only exists once mounted, hence the dependency. */useEffect(() => {+ const ownerDocument = artifactContainerRef.current?.ownerDocument ?? document;+ setFullscreenEnabled(ownerDocument.fullscreenEnabled);const handleFullscreenChange = () => {const container = artifactContainerRef.current;- setIsFullscreen(container !== null && document.fullscreenElement === container);+ setIsFullscreen(container !== null && ownerDocument.fullscreenElement === container);};- document.addEventListener('fullscreenchange', handleFullscreenChange);- return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);- }, []);+ ownerDocument.addEventListener('fullscreenchange', handleFullscreenChange);+ return () => ownerDocument.removeEventListener('fullscreenchange', handleFullscreenChange);+ }, [isMounted]);useEffect(() => {if (!isMobile) {@@ -181,6 +215,44 @@ export default function Artifacts() {setArtifactsVisible,]);+ const toggleUndock = useCallback(() => {+ if (isUndocked) {+ /* This button goes away with its window; the docked pane picks focus up. */+ setPaneFocusRequest(true);+ setDetached(null);+ return;+ }+ /* Opened straight from the click: popup permission follows user activation,+ * and an effect would spend it. The container is prepared here too, so the+ * pane can render into it on the very commit this state change causes —+ * a commit with the pane unmounted would reset the artifact registry. */+ const opened = openUndockedWindow(window);+ if (opened == null) {+ showToast({ status: 'error', message: localize('com_ui_undock_artifacts_blocked') });+ return;+ }+ /* The same handoff the other way: the control the user pressed goes away+ * with the docked toolbar, so focus follows the pane into the window it+ * just opened instead of being left on that window's empty document. */+ setPaneFocusRequest(true);+ setDetached({ window: opened, root: prepareUndockedDocument(document, opened.document) });+ }, [isUndocked, localize, setDetached, setPaneFocusRequest, showToast]);++ /* Moving the pane replaces one toolbar with the other: move focus to the+ * control that took the place of the one the user just pressed. The control+ * only exists once the pane has mounted, hence the dependency. */+ useEffect(() => {+ if (!paneFocusRequest || !isMounted) {+ return;+ }+ const control = undockButtonRef.current;+ if (control == null) {+ return;+ }+ control.focus();+ setPaneFocusRequest(false);+ }, [paneFocusRequest, isMounted, setPaneFocusRequest]);+useFocusTrap(panelRef, isMobile && isVisible && !isClosing, closeArtifacts);/* Office artifacts have no source view, and source-code artifacts have@@ -212,28 +284,65 @@ export default function Artifacts() {* shared state leaked it to the next artifact — after a `.py` (code-only)* every preview-capable row opened on Code while announcing a rendered* preview — so the tab is reset per artifact instead, and a manual choice- * survives only while that artifact stays open. */- const openedArtifactRef = useRef<string | null>(null);+ * survives only while that artifact stays open. The marker is pane state+ * for the same reason the tab is: changing host remounts the pane, and an+ * instance ref would start empty and reset the tab of the artifact already+ * on screen. */+ const [openedArtifactId, setOpenedArtifactId] = useAtom(artifactsOpenedArtifactId);useEffect(() => {const openedId = currentArtifact?.id ?? null;- if (openedId === openedArtifactRef.current) {+ if (openedId === openedArtifactId) {return;}- openedArtifactRef.current = openedId;+ setOpenedArtifactId(openedId);if (openedId != null && constrainedTab == null && activeTab !== 'preview') {setActiveTab('preview');}- }, [activeTab, constrainedTab, currentArtifact?.id, setActiveTab]);+ }, [+ activeTab,+ constrainedTab,+ currentArtifact?.id,+ openedArtifactId,+ setActiveTab,+ setOpenedArtifactId,+ ]);- const handleCopyArtifact = useCallback(() => {+ const handleCopyArtifact = useCallback(async () => {const content = currentArtifact?.content ?? '';if (!content) {return;}- copy(content, { format: 'text/plain' });+ /* Both clipboard paths have to act on the document the user is looking at:+ * `copy-to-clipboard` drives `execCommand` on the host document, which is+ * in the background while the undocked window has focus, and an unfocused+ * document copies nothing. Success is claimed only once a write lands. */+ const paneDocument = isUndocked ? panelRef.current?.ownerDocument : undefined;+ let copied = false;+ const clipboard = paneDocument?.defaultView?.navigator.clipboard;+ if (clipboard != null) {+ try {+ await clipboard.writeText(content);+ copied = true;+ } catch (error) {+ logger.error('Failed to copy the artifact through the clipboard API:', error);+ }+ }+ if (!copied && paneDocument != null) {+ /* No Clipboard API — a non-secure deployment — so fall back to the+ * selection dance, run in the pane's document rather than the host's. */+ copied = copyWithinDocument(paneDocument, content);+ }+ if (!copied && paneDocument == null) {+ copied = copy(content, { format: 'text/plain' });+ }++ if (!copied) {+ showToast({ status: 'error', message: localize('com_ui_copy_failed') });+ return;+ }setIsCopied(true);setTimeout(() => setIsCopied(false), 3000);- }, [currentArtifact?.content]);+ }, [currentArtifact?.content, isUndocked, localize, showToast]);const handleDragStart = (e: React.PointerEvent) => {setIsDragging(true);@@ -312,9 +421,13 @@ export default function Artifacts() {return;}+ /* Undocked, the pane's fullscreen element and `exitFullscreen` belong to+ * the popup's document; the host's would never match, so the minimize+ * action would request fullscreen again instead of leaving it. */+ const ownerDocument = container.ownerDocument;try {- if (document.fullscreenElement === container) {- await document.exitFullscreen();+ if (ownerDocument.fullscreenElement === container) {+ await ownerDocument.exitFullscreen();return;}await container.requestFullscreen();@@ -454,7 +567,7 @@ export default function Artifacts() {)}</Button>)}- {(displayedTab === 'preview' || isFullscreen) && document.fullscreenEnabled && (+ {(displayedTab === 'preview' || isFullscreen) && fullscreenEnabled && (<Buttonsize="icon"variant="ghost"@@ -478,7 +591,7 @@ export default function Artifacts() {<ArtifactVersioncurrentIndex={currentIndex}totalVersions={orderedArtifactIds.length}- portalElement={isFullscreen ? fullscreenPortalRef.current : undefined}+ portalElement={overlayPortal}onVersionChange={(index) => {const target = orderedArtifactIds[index];if (target) {@@ -490,7 +603,7 @@ export default function Artifacts() {<CopyButtonisCopied={isCopied}iconOnly- portalElement={isFullscreen ? fullscreenPortalRef.current : undefined}+ portalElement={overlayPortal}onClick={handleCopyArtifact}/>{/* Mermaid diagrams route every download through the export@@ -500,11 +613,32 @@ export default function Artifacts() {<MermaidExportartifact={currentArtifact}exportData={mermaidExportData}- portalElement={isFullscreen ? fullscreenPortalRef.current : undefined}+ portalElement={overlayPortal}/>) : (<DownloadArtifact artifact={currentArtifact} />)}+ {/* A capability that turns off while the pane is out there must+ not take away the only way back, so an undocked pane always+ keeps the control that docks it. */}+ {!isMobile && (canUndock || isUndocked) && (+ <Button+ ref={undockButtonRef}+ size="icon"+ variant="ghost"+ className="h-9 w-9"+ onClick={toggleUndock}+ aria-label={localize(+ isUndocked ? 'com_ui_dock_artifacts' : 'com_ui_undock_artifacts',+ )}+ >+ {isUndocked ? (+ <PanelRight size={16} aria-hidden="true" />+ ) : (+ <PictureInPicture2 size={16} aria-hidden="true" />+ )}+ </Button>+ )}<Buttonsize="icon"variant="ghost"@@ -559,7 +693,7 @@ export default function Artifacts() {)}</div><div- ref={fullscreenPortalRef}+ ref={setFullscreenPortal}className="z-[101]"data-testid="artifact-fullscreen-portal"/>diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsxindex dd3ca02f4d..f3cbe14bce 100644--- a/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx+++ b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx@@ -13,6 +13,7 @@ interface PreviewProps {const mockPreview = jest.fn((_props: PreviewProps) => null);let mockCurrentCode: string | undefined;+let mockCodeArtifactId: string | undefined;jest.mock('./ArtifactCodeEditor', () => ({ArtifactCodeEditor: () => null,@@ -23,7 +24,8 @@ jest.mock('./ArtifactPreview', () => ({}));jest.mock('~/Providers/EditorContext', () => ({- useCodeState: () => ({ currentCode: mockCurrentCode, setCurrentCode: jest.fn() }),+ useArtifactCode: (artifactId: string) =>+ mockCodeArtifactId === artifactId ? mockCurrentCode : undefined,}));jest.mock('~/Providers', () => ({@@ -67,6 +69,7 @@ function lastFiles(): Record<string, string> {describe('SandboxArtifactTabs SVG preview', () => {beforeEach(() => {mockCurrentCode = undefined;+ mockCodeArtifactId = undefined;mockPreview.mockClear();});@@ -79,6 +82,7 @@ describe('SandboxArtifactTabs SVG preview', () => {/* Editor text belongs to the preview only once it was typed against the* artifact on screen, so it lands on a later render, not on mount. */mockCurrentCode = edited;+ mockCodeArtifactId = svgArtifact.id;rerender(<Tabs.Root value="preview"><SandboxArtifactTabs artifact={svgArtifact} previewRef={previewRef} />@@ -95,6 +99,7 @@ describe('SandboxArtifactTabs SVG preview', () => {const { rerender } = renderTabs();mockCurrentCode = '';+ mockCodeArtifactId = svgArtifact.id;rerender(<Tabs.Root value="preview"><SandboxArtifactTabs artifact={svgArtifact} previewRef={previewRef} />@@ -116,6 +121,7 @@ describe('SandboxArtifactTabs SVG preview', () => {const { rerender } = renderTabs(htmlArtifact);mockCurrentCode = '<p>edited</p>';+ mockCodeArtifactId = htmlArtifact.id;rerender(<Tabs.Root value="preview"><SandboxArtifactTabs artifact={htmlArtifact} previewRef={previewRef} />diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.tsxindex 811cc00dfd..27fa0dc129 100644--- a/client/src/components/Artifacts/SandboxArtifactTabs.tsx+++ b/client/src/components/Artifacts/SandboxArtifactTabs.tsx@@ -1,12 +1,12 @@-import { useEffect, useMemo, useRef } from 'react';+import { useMemo, useRef } from 'react';import * as Tabs from '@radix-ui/react-tabs';import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled';import type { editor } from 'monaco-editor';import type { Artifact } from '~/common';import { useGetSharedStartupConfig, useGetStartupConfig } from '~/data-provider';import useArtifactProps from '~/hooks/Artifacts/useArtifactProps';+import { useArtifactCode } from '~/Providers/EditorContext';import { ArtifactCodeEditor } from './ArtifactCodeEditor';-import { useCodeState } from '~/Providers/EditorContext';import { ArtifactPreview } from './ArtifactPreview';import { useShareContext } from '~/Providers';@@ -19,7 +19,6 @@ export default function SandboxArtifactTabs({previewRef: React.MutableRefObject<SandpackPreviewRef>;isSharedConvo?: boolean;}) {- const { currentCode, setCurrentCode } = useCodeState();const { shareId } = useShareContext();const shouldUseSharedConfig =isSharedConvo === true && typeof shareId === 'string' && shareId.length > 0;@@ -29,21 +28,13 @@ export default function SandboxArtifactTabs({});const resolvedStartupConfig = shouldUseSharedConfig ? sharedStartupConfig : startupConfig;const monacoRef = useRef<editor.IStandaloneCodeEditor | null>(null);- const lastIdRef = useRef<string | null>(null);- /* The reset lands only after commit, so the render that switches artifacts- * still sees the previous artifact's editor text. */- const hasCurrentArtifactCode = lastIdRef.current === artifact.id;-- useEffect(() => {- if (artifact.id !== lastIdRef.current) {- setCurrentCode(undefined);- }- lastIdRef.current = artifact.id;- }, [artifact.id, setCurrentCode]);+ /* The buffer belongs to whichever artifact last wrote it, so a pane that+ * remounted for another host keeps this artifact's unsaved text; a copy+ * another artifact displaced is just as much this artifact's text. */+ const editedCode = useArtifactCode(artifact.id);const { files, fileKey, template, sharedProps, deriveFiles } = useArtifactProps({ artifact });- const editedCode = hasCurrentArtifactCode ? currentCode : undefined;/* An artifact whose preview entry is derived from its source needs the whole* set rebuilt from the editor text; `ArtifactPreview` can only swap the filediff --git a/client/src/components/Artifacts/UndockedArtifacts.tsx b/client/src/components/Artifacts/UndockedArtifacts.tsxnew file mode 100644index 0000000000..787b86646a--- /dev/null+++ b/client/src/components/Artifacts/UndockedArtifacts.tsx@@ -0,0 +1,131 @@+import { useEffect, useLayoutEffect } from 'react';+import { useRecoilValue } from 'recoil';+import { createPortal } from 'react-dom';+import { useAtom, useSetAtom } from 'jotai';+import * as RadixToast from '@radix-ui/react-toast';+import { Toast, ToastViewport } from '@librechat/client';+import {+ mirrorDocumentStyles,+ mirrorDocumentTheme,+ persistBounds,+ relayFrameMessages,+} from './undockedWindow';+import { artifactsPaneFocusRequest, undockedArtifacts } from './state';+import { useLocalize } from '~/hooks';+import store from '~/store';++/** `pagehide` covers the ordinary close; the poll covers the cases browsers+ * drop it (OS-level window close, session restore), because a pane that never+ * came home would leave the user with no artifacts at all. */+const CLOSED_POLL_MS = 500;++/**+ * Hosts the artifacts pane in a separate browser window while keeping it in+ * this window's React tree, so the pane keeps receiving artifacts as they+ * stream in and docking back is a re-render rather than a reload.+ *+ * The portal renders on the first commit — the window and its container are+ * prepared by the header before this mounts — so the pane never spends a+ * commit unmounted, which is what keeps its artifact registry alive.+ */+export default function UndockedArtifacts({+ children,+ hidden = false,+}: {+ children: React.ReactNode;+ /** The host is hiding the conversation this pane belongs to. */+ hidden?: boolean;+}) {+ const localize = useLocalize();+ const artifacts = useRecoilValue(store.artifactsState);+ const currentArtifactId = useRecoilValue(store.currentArtifactId);+ const [detached, setDetached] = useAtom(undockedArtifacts);+ const setPaneFocusRequest = useSetAtom(artifactsPaneFocusRequest);++ useLayoutEffect(() => {+ if (detached == null) {+ return;+ }+ const { window: detachedWindow, root } = detached;+ /* Never clobber a window the user opened after this one. */+ const redock = () => setDetached((current) => (current === detached ? null : current));+ if (detachedWindow.closed) {+ redock();+ return;+ }++ const teardown = [+ mirrorDocumentStyles(document, detachedWindow.document),+ mirrorDocumentTheme(document, detachedWindow.document),+ relayFrameMessages(window, detachedWindow),+ ];++ const closeWithOpener = () => detachedWindow.close();+ /* A window the user closes through the browser reports zeroes by the time+ * the cleanup runs, so its size and position are read while it still has+ * them — otherwise the remembered bounds only ever track Dock. Closing the+ * window is a dock the user asked for, so the pane that takes over picks+ * focus up exactly as it does for the Dock control. */+ const rememberAndRedock = () => {+ persistBounds(detachedWindow, window);+ setPaneFocusRequest(true);+ redock();+ };+ detachedWindow.addEventListener('pagehide', rememberAndRedock);+ window.addEventListener('pagehide', closeWithOpener);+ const closedPoll = window.setInterval(() => {+ if (detachedWindow.closed) {+ setPaneFocusRequest(true);+ redock();+ }+ }, CLOSED_POLL_MS);++ return () => {+ window.clearInterval(closedPoll);+ window.removeEventListener('pagehide', closeWithOpener);+ detachedWindow.removeEventListener('pagehide', rememberAndRedock);+ for (const dispose of teardown) {+ dispose();+ }+ root.remove();+ persistBounds(detachedWindow, window);+ detachedWindow.close();+ /* Closing the pane while undocked is not a dock: clear the window so the+ * next artifact opens in the side panel. */+ redock();+ };+ }, [detached, setDetached, setPaneFocusRequest]);++ const artifactTitle =+ (currentArtifactId != null ? artifacts?.[currentArtifactId]?.title : null) ??+ localize('com_ui_artifacts');++ useEffect(() => {+ if (detached == null || detached.window.closed) {+ return;+ }+ detached.window.document.title = artifactTitle;+ }, [artifactTitle, detached]);++ if (detached == null) {+ return null;+ }++ /* The app's toast surface lives in the opener's document, which the user is+ * not looking at while the pane is undocked. A Radix provider of its own+ * gives every toast raised inside this window a viewport inside it, and the+ * toast state is shared, so the same notice shows wherever the user is. */+ return createPortal(+ <RadixToast.Provider>+ {/* The portal escapes the host's tree, so a host that hides its+ * conversation while the route loads (or fails to) hides the pane here+ * too, instead of leaving the previous conversation editable. */}+ <div hidden={hidden} className={hidden ? 'hidden' : 'contents'}>+ {children}+ </div>+ <Toast />+ <ToastViewport />+ </RadixToast.Provider>,+ detached.root,+ );+}diff --git a/client/src/components/Artifacts/__tests__/ArtifactCodeEditorBuffer.test.tsx b/client/src/components/Artifacts/__tests__/ArtifactCodeEditorBuffer.test.tsxnew file mode 100644index 0000000000..21060d7211--- /dev/null+++ b/client/src/components/Artifacts/__tests__/ArtifactCodeEditorBuffer.test.tsx@@ -0,0 +1,718 @@+import React, { useEffect } from 'react';+import { ThemeContext } from '@librechat/client';+import { render, act } from '@testing-library/react';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type { editor } from 'monaco-editor';+import type { Artifact } from '~/common';+import { EditorProvider, useCodeState } from '~/Providers/EditorContext';+import { ArtifactCodeEditor } from '../ArtifactCodeEditor';++interface MonacoEditorProps {+ onChange?: (value: string | undefined) => void;+}++const editorProps: MonacoEditorProps = {};++/** One save at a time, settled by the test the way the server would. */+let inFlight: { resolve: (value: unknown) => void; reject: (error: unknown) => void } | null = null;+const mockEditArtifact = jest.fn(+ (vars: unknown) =>+ new Promise((resolve, reject) => {+ inFlight = {+ resolve: () =>+ resolve({ ...(vars as object), content: '', text: '', conversationId: null }),+ reject,+ };+ }),+);++jest.mock('@monaco-editor/react', () => ({+ __esModule: true,+ default: (props: MonacoEditorProps) => {+ Object.assign(editorProps, props);+ return null;+ },+}));++jest.mock('~/Providers', () => ({+ useArtifactsContext: () => ({ isSubmitting: false }),+}));++jest.mock('librechat-data-provider', () => ({+ ...jest.requireActual('librechat-data-provider'),+ dataService: { editArtifact: (vars: unknown) => mockEditArtifact(vars) },+}));++const artifactA: Artifact = {+ id: 'artifact-a',+ lastUpdateTime: 0,+ index: 0,+ messageId: 'msg-a',+ content: 'CONTENT-A',+ type: 'text/plain',+};++const artifactB: Artifact = {+ id: 'artifact-b',+ lastUpdateTime: 0,+ index: 1,+ messageId: 'msg-b',+ content: 'CONTENT-B',+ type: 'text/plain',+};++/**+ * Monaco reports a programmatic `setValue` through `onChange` exactly like a+ * keystroke, which is the behaviour these cases turn on.+ */+const createModel = (initial: string) => {+ let value = initial;+ const model = {+ getValue: () => value,+ setValue: (next: string) => {+ value = next;+ editorProps.onChange?.(next);+ },+ getLineCount: () => 1,+ getValueLength: () => value.length,+ getPositionAt: () => ({ lineNumber: 1, column: value.length + 1 }),+ applyEdits: jest.fn(),+ };+ const ed = {+ getModel: () => model,+ revealLine: jest.fn(),+ } as unknown as editor.IStandaloneCodeEditor;+ return { ed, read: () => value };+};++type Session = {+ endCodeSession: () => void;+ buffer: { code?: string; artifactId?: string };+};++const session: Session = { endCodeSession: () => {}, buffer: {} };++/** Publishes the shared editing state the pane's hosts drive. */+function SessionProbe() {+ const { currentCode, codeArtifactId, endCodeSession } = useCodeState();+ useEffect(() => {+ session.endCodeSession = endCodeSession;+ session.buffer = { code: currentCode, artifactId: codeArtifactId };+ });+ return null;+}++/**+ * The provider sits above the pane's hosts, so closing the pane unmounts the+ * editor while the session state and any running save stay where they are.+ */+const renderEditor = (initial: Artifact, monacoRef: React.MutableRefObject<any>) => {+ let current = initial;+ let paneOpen = true;+ let readOnly = false;+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false }, queries: { retry: false } },+ });+ const tree = () => (+ <QueryClientProvider client={client}>+ <ThemeContext.Provider+ value={+ { resolvedMode: 'dark', highContrast: false } as React.ContextType<typeof ThemeContext>+ }+ >+ <EditorProvider>+ <SessionProbe />+ {paneOpen ? (+ <ArtifactCodeEditor artifact={current} monacoRef={monacoRef} readOnly={readOnly} />+ ) : null}+ </EditorProvider>+ </ThemeContext.Provider>+ </QueryClientProvider>+ );+ const utils = render(tree());+ const rerender = () =>+ act(() => {+ utils.rerender(tree());+ });+ return {+ ...utils,+ select: (next: Artifact) => {+ current = next;+ rerender();+ },+ closePane: () => {+ paneOpen = false;+ rerender();+ },+ reopenPane: () => {+ paneOpen = true;+ rerender();+ },+ setReadOnly: (next: boolean) => {+ readOnly = next;+ rerender();+ },+ };+};++const type = (value: string) => {+ act(() => {+ editorProps.onChange?.(value);+ });+};++const settleDebounce = () => {+ act(() => {+ jest.advanceTimersByTime(500);+ });+};++/** Let the mutation's own promise chain and React Query's notify batch run. */+const flush = async () => {+ await act(async () => {+ await Promise.resolve();+ await Promise.resolve();+ jest.advanceTimersByTime(1);+ await Promise.resolve();+ });+};++describe('ArtifactCodeEditor unsaved text across a selection change', () => {+ beforeEach(() => {+ jest.useFakeTimers();+ mockEditArtifact.mockClear();+ inFlight = null;+ editorProps.onChange = undefined;+ });++ afterEach(() => {+ jest.runOnlyPendingTimers();+ jest.useRealTimers();+ });++ it('keeps the unsaved text of the artifact the user left', () => {+ const { ed } = createModel('CONTENT-A');+ const monacoRef = { current: ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDITED-A');+ view.select(artifactB);++ expect(session.buffer).toEqual({ code: 'EDITED-A', artifactId: 'artifact-a' });+ expect(mockEditArtifact).not.toHaveBeenCalled();+ });++ /* Editing the artifact the user moved to must not evict the text the one+ * they left was holding: its debounce died with the selection change, so the+ * retained copy is the only place it still lives. Reported by Codex on+ * 591ab13c96 (P1). */+ it('restores the text of the left artifact after another is edited', async () => {+ const { ed, read } = createModel('CONTENT-A');+ const monacoRef = { current: ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDITED-A');+ view.select(artifactB);+ type('EDITED-B');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ view.select(artifactA);+ await flush();++ /* The restored edit queues behind the running save of the other artifact,+ * and that save's callbacks send it once it lands. */+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();++ expect(read()).toBe('EDITED-A');+ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ messageId: 'msg-a', original: 'CONTENT-A', updated: 'EDITED-A' }),+ );+ });++ it('restores that text and saves it when the artifact is selected again', async () => {+ const { ed, read } = createModel('CONTENT-A');+ const monacoRef = { current: ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDITED-A');+ view.select(artifactB);+ expect(read()).toBe('CONTENT-B');++ view.select(artifactA);+ await flush();++ expect(read()).toBe('EDITED-A');+ expect(mockEditArtifact).toHaveBeenCalledWith(+ expect.objectContaining({ messageId: 'msg-a', original: 'CONTENT-A', updated: 'EDITED-A' }),+ );+ });++ /* The save that held the lock has already replaced the content the queued+ * edit was typed against, so sending that stale `original` would have the+ * endpoint reject the newest text. */+ it('sends a queued edit against the content the finished save left', async () => {+ const { ed } = createModel('CONTENT-A');+ const monacoRef = { current: ed } as React.MutableRefObject<any>;+ renderEditor(artifactA, monacoRef);++ type('FIRST-EDIT');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* Typed while the first save is still running: queued, not sent. */+ type('SECOND-EDIT');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* The save lands. The registry still holds the pre-save content — it+ * catches up only when the edited message propagates — so the queued edit+ * has to be rebased on what the request wrote, not on what is on screen. */+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({+ messageId: 'msg-a',+ original: 'FIRST-EDIT',+ updated: 'SECOND-EDIT',+ }),+ );+ });++ /* The save is the request's, not the session's: a pane closed mid-save must+ * neither release it nor let the next session write over it. */+ it('waits for a save the closed session started before sending the next edit', async () => {+ const { ed } = createModel('CONTENT-A');+ const monacoRef = { current: ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDIT-BEFORE-CLOSE');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* The pane is closed and reopened while that save is still running. */+ act(() => {+ session.endCodeSession();+ });+ view.closePane();+ view.reopenPane();+ type('EDIT-AFTER-REOPEN');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({+ messageId: 'msg-a',+ original: 'EDIT-BEFORE-CLOSE',+ updated: 'EDIT-AFTER-REOPEN',+ }),+ );+ });++ it('does not resubmit rejected text when the editor remounts in the same session', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('REJECTED-EDIT');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();++ view.closePane();+ view.reopenPane();+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(1);+ });++ it('saves a new edit after a rejected buffer is remounted', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('REJECTED-EDIT');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();++ view.closePane();+ view.reopenPane();+ type('NEW-EDIT');+ settleDebounce();+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(2);+ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ updated: 'NEW-EDIT' }),+ );+ });++ /* A save answers after the user has moved on, so the refusal has to be+ * recorded against the artifact whose text was refused. Filed under the+ * artifact on screen instead, it would let the one that was rejected send+ * the same text again the moment the user came back to it. */+ it('records a refusal against the artifact whose save was refused', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('REJECTED-A');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ view.select(artifactB);+ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();++ view.select(artifactA);+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(1);+ });++ /* A save for the artifact the user left can land while they are reading+ * another one, and the registry catches up only when the edited message+ * propagates. The edit restored on the way back replaces what that save+ * wrote, not what the registry still says, or the endpoint refuses it and+ * the text the user typed never lands. */+ it('rebases a restored edit on what the last save actually wrote', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('SAVED-A');+ settleDebounce();+ await flush();+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* A second edit whose debounce the selection change cancels. */+ type('RETAINED-A');+ view.select(artifactB);+ view.select(artifactA);+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(2);+ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'SAVED-A', updated: 'RETAINED-A' }),+ );+ });++ /* The registry can also move past this session's save from the outside:+ * another tab or session edits the artifact and the messages query+ * refetches what they wrote. The local save is then the older truth, and+ * preferring it would have the endpoint refuse every further edit. */+ it('rebases on content that moved past the local save', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('LOCAL-SAVE');+ settleDebounce();+ await flush();+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* The messages query brings what another session wrote. */+ view.select({ ...artifactA, content: 'FOREIGN-CONTENT' });+ await flush();++ type('AFTER-REFRESH');+ settleDebounce();+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'FOREIGN-CONTENT', updated: 'AFTER-REFRESH' }),+ );+ });++ /* Two artifacts can both have a refusal on file: one marker must not be+ * overwritten by the other's, or the older refusal is forgotten and its+ * text goes back on the wire when the user returns to it. */+ it('keeps a refusal for each artifact that was refused', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('REJECTED-A');+ settleDebounce();+ await flush();+ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ view.select(artifactB);+ type('REJECTED-B');+ settleDebounce();+ await flush();+ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(2);++ /* B's refusal must not make A's text eligible again. */+ view.select(artifactA);+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(2);+ });++ /* Clearing the editor is mid-edit, not a deletion: typing never saves an+ * empty buffer, so no path that resubmits retained text may either — a host+ * change would otherwise persist the removal of the whole artifact. */+ it('does not persist a cleared editor when the pane changes hosts', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).not.toHaveBeenCalled();++ view.closePane();+ view.reopenPane();+ await flush();++ expect(mockEditArtifact).not.toHaveBeenCalled();++ view.select(artifactB);+ view.select(artifactA);+ await flush();++ expect(mockEditArtifact).not.toHaveBeenCalled();+ });++ /* The pane changes hosts while a save is running and the user keeps typing:+ * the text they typed in the new instance is the newest thing in play, so+ * the buffer it inherited at mount must not be sent after it and put the+ * artifact back the way it was. */+ it('does not undo a newer edit with the buffer it inherited at mount', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDIT-OLD');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ /* The host change happens while that save is still open. */+ view.closePane();+ view.reopenPane();+ await flush();++ type('EDIT-NEW');+ settleDebounce();+ await flush();++ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(2);+ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ updated: 'EDIT-NEW' }),+ );+ });++ /* A response starts while an edit is still waiting on its debounce, and the+ * pane changes hosts before it saves: the edit is inherited by an editor+ * that cannot save yet. It has to survive until editing returns, then be+ * saved and stay on screen rather than give way to the persisted content. */+ it('saves an inherited edit once a generation ends', async () => {+ const model = createModel('CONTENT-A');+ const monacoRef = { current: model.ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ type('EDIT-A');+ view.setReadOnly(true);+ view.closePane();+ view.reopenPane();+ settleDebounce();+ await flush();+ expect(mockEditArtifact).not.toHaveBeenCalled();++ view.setReadOnly(false);+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(1);+ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'CONTENT-A', updated: 'EDIT-A' }),+ );+ expect(model.read()).toBe('EDIT-A');+ });++ const saveAndSettle = async (text: string) => {+ type(text);+ settleDebounce();+ await flush();+ await act(async () => {+ inFlight?.resolve(undefined);+ await Promise.resolve();+ });+ await flush();+ };++ /* Text this tab saved is not unsaved. When another session moves the+ * artifact on, a host change must not send the saved text back over it. */+ it('does not resend saved text over a newer change made elsewhere', async () => {+ const model = createModel('CONTENT-A');+ const monacoRef = { current: model.ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ await saveAndSettle('SAVED-HERE');+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ view.select({ ...artifactA, content: 'SAVED-HERE' });+ view.select({ ...artifactA, content: 'CHANGED-ELSEWHERE' });+ await flush();++ view.closePane();+ view.reopenPane();+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(1);+ expect(model.read()).toBe('CHANGED-ELSEWHERE');+ });++ /* Once the registry has shown this tab's save, a later change back to an+ * earlier value is made elsewhere, not lag, and the next edit replaces it. */+ it('rebases on an earlier value restored elsewhere after the save landed', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ await saveAndSettle('SAVED-HERE');+ view.select({ ...artifactA, content: 'SAVED-HERE' });+ await flush();+ view.select({ ...artifactA, content: 'CONTENT-A' });+ await flush();++ type('AFTER-REVERT');+ settleDebounce();+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'CONTENT-A', updated: 'AFTER-REVERT' }),+ );+ });++ /* The user edits away and back to the text of a save that is still open.+ * When that save is refused, the queued copy of the same text is the refused+ * text and must not go out again. */+ it('does not retry a queued edit the running save was refused for', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ renderEditor(artifactA, monacoRef);++ type('REFUSED');+ settleDebounce();+ await flush();+ expect(mockEditArtifact).toHaveBeenCalledTimes(1);++ type('DETOUR');+ settleDebounce();+ type('REFUSED');+ settleDebounce();+ await flush();++ await act(async () => {+ inFlight?.reject({ status: 400 });+ await Promise.resolve();+ });+ await flush();++ expect(mockEditArtifact).toHaveBeenCalledTimes(1);+ });++ /* Two saves land before the registry shows either. Once it shows the first+ * one, the value before it is history: the registry going back there later+ * is a change made elsewhere, not lag. */+ it('retires lag values the registry has already passed', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ await saveAndSettle('ONE');+ await saveAndSettle('TWO');+ view.select({ ...artifactA, content: 'ONE' });+ await flush();+ view.select({ ...artifactA, content: 'CONTENT-A' });+ await flush();++ type('NEXT');+ settleDebounce();+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'CONTENT-A', updated: 'NEXT' }),+ );+ });++ /* Only the copy a save wrote is known to be saved. A user who edits away+ * and back to that same text has made an edit, and it is sent. */+ it('sends an edit that returns to previously saved text', async () => {+ const monacoRef = { current: createModel('CONTENT-A').ed } as React.MutableRefObject<any>;+ const view = renderEditor(artifactA, monacoRef);++ await saveAndSettle('SAVED');+ view.select({ ...artifactA, content: 'SAVED' });+ await flush();++ type('DETOUR');+ type('SAVED');+ view.select(artifactB);+ view.select({ ...artifactA, content: 'CHANGED-ELSEWHERE' });+ await flush();++ expect(mockEditArtifact).toHaveBeenLastCalledWith(+ expect.objectContaining({ original: 'CHANGED-ELSEWHERE', updated: 'SAVED' }),+ );+ });+});diff --git a/client/src/components/Artifacts/__tests__/Artifacts.test.tsx b/client/src/components/Artifacts/__tests__/Artifacts.test.tsxindex 999fc93b47..57cd9df8d9 100644--- a/client/src/components/Artifacts/__tests__/Artifacts.test.tsx+++ b/client/src/components/Artifacts/__tests__/Artifacts.test.tsx@@ -110,6 +110,7 @@ const renderArtifacts = async ({latestMessageId: null,latestMessageText: '',conversationId: 'conversation-1',+ canUndock: true,}}>{includeStateControls && <ArtifactStateControls />}diff --git a/client/src/components/Artifacts/__tests__/ArtifactsTabSession.test.tsx b/client/src/components/Artifacts/__tests__/ArtifactsTabSession.test.tsxnew file mode 100644index 0000000000..15f874baa7--- /dev/null+++ b/client/src/components/Artifacts/__tests__/ArtifactsTabSession.test.tsx@@ -0,0 +1,114 @@+import React, { useState } from 'react';+import { RecoilRoot } from 'recoil';+import { getDefaultStore } from 'jotai';+import type { MutableSnapshot } from 'recoil';+import type { Artifact } from '~/common';+import { artifactsActiveTab, artifactsOpenedArtifactId } from '../state';+import { act, fireEvent, render, screen } from 'test/layout-test-utils';+import { ArtifactsProvider, EditorProvider } from '~/Providers';+import Artifacts from '../Artifacts';+import store from '~/store';++/**+ * The pane changes hosts — side panel, mobile sheet, undocked window — by+ * unmounting one instance and mounting another. Everything the user can see+ * about "where they were" therefore has to live outside the instance, and the+ * tab is the part they notice: arriving back on Preview reads as the code they+ * were editing having been thrown away.+ *+ * The other half of the rule — opening a *different* artifact does return to+ * the preview — is covered in `../Artifacts.test.tsx`, which mocks+ * `useArtifacts` and so can drive artifact changes without a live preview.+ */++const htmlArtifact: Artifact = {+ id: 'artifact-1',+ type: 'text/html',+ title: 'Preview',+ content: '<p>one</p>',+ lastUpdateTime: 0,+};++const MOVE_PANE = 'Move pane to another host';++const initializeArtifacts = ({ set }: MutableSnapshot) => {+ set(store.artifactsState, { [htmlArtifact.id]: htmlArtifact });+ set(store.currentArtifactId, htmlArtifact.id);+ set(store.queriesEnabled, false);+};++/**+ * Stands in for the two hosts. Changing the key unmounts the pane and mounts a+ * fresh instance in the same commit, which is what moving it between the side+ * panel and the undocked window does; the surrounding state stays put.+ */+function Hosts() {+ const [host, setHost] = useState('panel');++ return (+ <RecoilRoot initializeState={initializeArtifacts}>+ <EditorProvider>+ <ArtifactsProvider+ value={{+ isSubmitting: false,+ latestMessageId: null,+ latestMessageText: '',+ conversationId: 'conversation-1',+ canUndock: true,+ }}+ >+ <button+ type="button"+ onClick={() => setHost((current) => (current === 'panel' ? 'window' : 'panel'))}+ >+ {MOVE_PANE}+ </button>+ <Artifacts key={host} />+ </ArtifactsProvider>+ </EditorProvider>+ </RecoilRoot>+ );+}++const codeTab = () => screen.getByRole('radio', { name: 'Code' });+/** Present on both tabs, unlike Refresh, which is a preview-only control. */+const paneReady = () => screen.findByRole('button', { name: 'Copy' });++describe('the artifacts pane tab across a host change', () => {+ beforeEach(() => {+ /* Desktop: the mobile sheet renders no tab control at all. */+ window.matchMedia = jest.fn().mockImplementation((query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: jest.fn(),+ removeListener: jest.fn(),+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ dispatchEvent: jest.fn(),+ }));+ /* Pane state lives in a module-global store, so one test's tab would+ * otherwise be the next test's starting point. */+ getDefaultStore().set(artifactsActiveTab, 'preview');+ getDefaultStore().set(artifactsOpenedArtifactId, null);+ });++ it('keeps the tab the user chose when the pane moves host', async () => {+ render(<Hosts />);+ await paneReady();++ await act(async () => {+ fireEvent.click(codeTab());+ });+ expect(codeTab()).toHaveAttribute('aria-checked', 'true');++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: MOVE_PANE }));+ });+ await paneReady();++ /* The new instance sees the artifact already on screen. Reading that as a+ * freshly opened artifact is what used to send the user back to Preview. */+ expect(codeTab()).toHaveAttribute('aria-checked', 'true');+ });+});diff --git a/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsx b/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsxindex f048d2392d..2b983ab59a 100644--- a/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsx+++ b/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsx@@ -9,6 +9,7 @@ const mockFileDownload = jest.fn();const mockAttachmentOptions = jest.fn();let mockFileKey = 'index.html';let mockCurrentCode: string | undefined;+let mockCodeArtifactId: string | undefined;jest.mock('~/hooks', () => ({useLocalize:@@ -23,7 +24,8 @@ jest.mock('~/hooks/Artifacts/useArtifactProps', () => ({}));jest.mock('~/Providers/EditorContext', () => ({- useCodeState: () => ({ currentCode: mockCurrentCode }),+ useArtifactCode: (artifactId: string) =>+ mockCodeArtifactId === artifactId ? mockCurrentCode : undefined,}));const mockShowToast = jest.fn();@@ -113,6 +115,7 @@ describe('DownloadArtifact', () => {beforeEach(() => {mockFileKey = 'index.html';mockCurrentCode = undefined;+ mockCodeArtifactId = undefined;mockFileDownload.mockReset();mockShowToast.mockReset();// The attachment helper resolves to `true` when a file was delivered.@@ -161,6 +164,7 @@ describe('DownloadArtifact', () => {])('names %s download with title %s', async (type, title, fileKey, language, expected) => {mockFileKey = fileKey;mockCurrentCode = 'edited content';+ mockCodeArtifactId = htmlArtifact.id;render(<DownloadArtifact artifact={{ ...htmlArtifact, type, title, language }} />);await act(async () => {fireEvent.click(screen.getByRole('button'));@@ -181,6 +185,7 @@ describe('DownloadArtifact', () => {async (title) => {mockFileKey = 'content.md';mockCurrentCode = '# New **migration** [plan](https://example.com) for `migrate_users.py`';+ mockCodeArtifactId = htmlArtifact.id;render(<DownloadArtifactartifact={{ ...htmlArtifact, type: 'text/markdown', title, content: '# Old heading' }}@@ -301,6 +306,7 @@ describe('DownloadArtifact', () => {text: 'Prefix\n\n…[truncated]',filepath: '/api/files/code/output/large.py',});+ mockCodeArtifactId = artifact!.id;render(<DownloadArtifact artifact={artifact!} />);await act(async () => {fireEvent.click(screen.getByRole('button'));@@ -320,6 +326,7 @@ describe('DownloadArtifact', () => {text: 'Prefix\n\n…[truncated]',filepath: '/api/files/code/output/large.py',});+ mockCodeArtifactId = artifact!.id;render(<DownloadArtifact artifact={artifact!} />);await act(async () => {fireEvent.click(screen.getByRole('button'));@@ -331,6 +338,26 @@ describe('DownloadArtifact', () => {},);+ /* The buffer outlives a pane remount, so the next artifact must not be+ * exported with the previous artifact's edits under its own name. */+ it('ignores an edit that belongs to another artifact', async () => {+ mockCurrentCode = 'edits for the other artifact';+ mockCodeArtifactId = 'llm-artifact-other';+ render(+ <DownloadArtifact artifact={{ ...htmlArtifact, content: '<h1>mine</h1>', title: 'Mine' }} />,+ );+ await act(async () => {+ fireEvent.click(screen.getByRole('button'));+ });+ const blob = createObjectURL.mock.calls[0][0] as Blob;+ const content = await new Promise<string>((resolve) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result));+ reader.readAsText(blob);+ });+ expect(content).toBe('<h1>mine</h1>');+ });+it('names a truncated preview distinctly when the original route is unavailable', async () => {const artifact = fileToArtifact({file_id: 'file',@@ -469,6 +496,7 @@ describe('DownloadArtifact', () => {source: FileSources.execute_code,user: 'user-1',});+ mockCodeArtifactId = artifact!.id;render(<DownloadArtifact artifact={artifact!} />);await act(async () => {fireEvent.click(screen.getByRole('button'));diff --git a/client/src/components/Artifacts/__tests__/UndockedArtifacts.test.tsx b/client/src/components/Artifacts/__tests__/UndockedArtifacts.test.tsxnew file mode 100644index 0000000000..471a92a351--- /dev/null+++ b/client/src/components/Artifacts/__tests__/UndockedArtifacts.test.tsx@@ -0,0 +1,122 @@+import { RecoilRoot } from 'recoil';+import { Provider, createStore } from 'jotai';+import { act, render, screen } from '@testing-library/react';+import type { MutableSnapshot } from 'recoil';+import { prepareUndockedDocument } from '../undockedWindow';+import UndockedArtifacts from '../UndockedArtifacts';+import { undockedArtifacts } from '../state';+import store from '~/store';++jest.mock('~/hooks', () => ({+ useLocalize:+ () =>+ (key: string): string =>+ key,+}));++interface FakeWindow extends Window {+ closed: boolean;+}++const createFakeWindow = (): FakeWindow => {+ const detachedDocument = document.implementation.createHTMLDocument('');+ const fake = {+ document: detachedDocument,+ closed: false,+ outerWidth: 900,+ outerHeight: 700,+ screenX: 120,+ screenY: 40,+ focus: jest.fn(),+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ close: jest.fn(() => {+ fake.closed = true;+ }),+ };+ return fake as unknown as FakeWindow;+};++const artifact = {+ id: 'artifact-1',+ type: 'text/html',+ title: 'dashboard.html',+ content: '<p>hi</p>',+ lastUpdateTime: 1,+};++const seedArtifacts = ({ set }: MutableSnapshot) => {+ set(store.artifactsState, { [artifact.id]: artifact });+ set(store.currentArtifactId, artifact.id);+};++const renderUndocked = (detached: FakeWindow, hidden = false) => {+ const jotaiStore = createStore();+ jotaiStore.set(undockedArtifacts, {+ window: detached,+ root: prepareUndockedDocument(document, detached.document),+ });+ const view = render(+ <RecoilRoot initializeState={seedArtifacts}>+ <Provider store={jotaiStore}>+ <UndockedArtifacts hidden={hidden}>+ <div data-testid="artifact-pane" />+ </UndockedArtifacts>+ </Provider>+ </RecoilRoot>,+ );+ return { ...view, jotaiStore };+};++describe('UndockedArtifacts', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ it('renders the pane inside the detached window rather than the host page', () => {+ const detached = createFakeWindow();++ const { jotaiStore } = renderUndocked(detached);++ const pane = detached.document.querySelector('[data-testid="artifact-pane"]');+ expect(pane).not.toBeNull();+ expect(pane?.closest('#undocked-artifacts-root')).not.toBeNull();+ expect(screen.queryByTestId('artifact-pane')).not.toBeInTheDocument();+ expect(detached.document.title).toBe('dashboard.html');+ expect(detached.document.head.querySelector('style')).not.toBeNull();+ expect(jotaiStore.get(undockedArtifacts)?.window).toBe(detached);+ });++ /* The host hides its conversation while the route loads another one; the+ * window must not keep the previous conversation's pane usable. */+ it('hides the pane while its host hides the conversation', () => {+ const detached = createFakeWindow();+ renderUndocked(detached, true);++ const pane = detached.document.querySelector('[data-testid="artifact-pane"]');+ expect(pane?.parentElement?.hidden).toBe(true);+ });++ it('closes the window when the pane docks back', () => {+ const detached = createFakeWindow();+ const { unmount } = renderUndocked(detached);++ unmount();++ expect(detached.close).toHaveBeenCalled();+ expect(window.localStorage.getItem('artifacts:undocked-window-bounds')).toBe(+ JSON.stringify({ width: 900, height: 700, left: 120, top: 40 }),+ );+ });++ /* The user closing the popup is the other way to dock: the pane has to come+ * home, not vanish with the window. */+ it('docks the pane back when the user closes the window', () => {+ const detached = createFakeWindow();+ const { jotaiStore } = renderUndocked(detached);++ detached.closed = true;+ act(() => jest.advanceTimersByTime(500));++ expect(jotaiStore.get(undockedArtifacts)).toBeNull();+ });+});diff --git a/client/src/components/Artifacts/__tests__/undockedWindow.spec.ts b/client/src/components/Artifacts/__tests__/undockedWindow.spec.tsnew file mode 100644index 0000000000..1f3cfa6c51--- /dev/null+++ b/client/src/components/Artifacts/__tests__/undockedWindow.spec.ts@@ -0,0 +1,402 @@+import {+ defaultBounds,+ mirrorDocumentStyles,+ mirrorDocumentTheme,+ openUndockedWindow,+ parseBounds,+ persistBounds,+ prepareUndockedDocument,+ relayFrameMessages,+ UNDOCKED_ARTIFACTS_BOUNDS_KEY,+} from '../undockedWindow';++const detachedDocument = () => document.implementation.createHTMLDocument('detached');++/**+ * A browser that denies Web Storage throws from the `localStorage` getter+ * itself, not from `getItem`. Undocking has to fall back to default bounds,+ * and docking back — which runs through the same persistence — has to finish,+ * or the pane is stranded in a window with no way home.+ */+const windowWithDeniedStorage = (overrides: Partial<Window> = {}) => {+ const denied = {+ screen: { availWidth: 1600, availHeight: 1000 },+ outerWidth: 1200,+ outerHeight: 900,+ screenX: 0,+ screenY: 0,+ open: jest.fn(() => ({ focus: jest.fn() })),+ ...overrides,+ };+ Object.defineProperty(denied, 'localStorage', {+ get() {+ throw new DOMException('denied', 'SecurityError');+ },+ });+ return denied as unknown as Window;+};++describe('undocking when the browser denies storage', () => {+ it('opens the window at the default bounds instead of throwing', () => {+ const source = windowWithDeniedStorage();++ const opened = openUndockedWindow(source);++ expect(opened).not.toBeNull();+ const features = (source.open as jest.Mock).mock.calls[0][2] as string;+ const { width, height } = defaultBounds(source);+ expect(features).toContain(`width=${width}`);+ expect(features).toContain(`height=${height}`);+ });++ it('lets the redock and teardown path finish without remembering bounds', () => {+ const detached = {+ outerWidth: 900,+ outerHeight: 700,+ screenX: 120,+ screenY: 40,+ } as unknown as Window;++ expect(() => persistBounds(detached, windowWithDeniedStorage())).not.toThrow();+ });++ it('still remembers the bounds when storage is available', () => {+ const detached = {+ outerWidth: 900,+ outerHeight: 700,+ screenX: 120,+ screenY: 40,+ } as unknown as Window;++ persistBounds(detached, window);++ expect(window.localStorage.getItem(UNDOCKED_ARTIFACTS_BOUNDS_KEY)).toBe(+ JSON.stringify({ width: 900, height: 700, left: 120, top: 40 }),+ );+ });+});++describe('parseBounds', () => {+ it('keeps a window that was left on a monitor at negative coordinates', () => {+ expect(parseBounds(JSON.stringify({ width: 900, height: 700, left: -1720, top: -80 }))).toEqual(+ {+ width: 900,+ height: 700,+ left: -1720,+ top: -80,+ },+ );+ });++ it('refuses to reopen a window too small to use', () => {+ expect(parseBounds(JSON.stringify({ width: 10, height: 10, left: 0, top: 0 }))).toEqual({+ width: 520,+ height: 480,+ left: 0,+ top: 0,+ });+ });++ it.each([+ ['nothing stored', null],+ ['not json', '{oops'],+ ['a partial record', JSON.stringify({ width: 900, height: 700 })],+ ['a non-numeric field', JSON.stringify({ width: '900', height: 700, left: 0, top: 0 })],+ ])('falls back when storage holds %s', (_label, raw) => {+ expect(parseBounds(raw)).toBeNull();+ });+});++/**+ * Remembered coordinates outlive the monitor arrangement that produced them,+ * and undocking takes the pane — and the only Dock control — out of this page.+ * A window put where nothing can reach it is the one failure the remembered+ * bounds must never cause.+ */+describe('reopening at remembered bounds', () => {+ const sourceOn = (screen: Record<string, unknown>) =>+ ({+ screen,+ outerWidth: 1200,+ outerHeight: 900,+ screenX: 0,+ screenY: 0,+ localStorage: {+ getItem: () => JSON.stringify({ width: 900, height: 700, left: -1720, top: -80 }),+ },+ open: jest.fn(() => ({ focus: jest.fn() })),+ }) as unknown as Window;++ const openedFeatures = (source: Window) => {+ openUndockedWindow(source);+ return (source.open as jest.Mock).mock.calls[0][2] as string;+ };++ it('ignores a monitor that is no longer attached', () => {+ const source = sourceOn({+ availWidth: 1600,+ availHeight: 1000,+ availLeft: 0,+ availTop: 0,+ isExtended: false,+ });++ const features = openedFeatures(source);++ const fallback = defaultBounds(source);+ expect(features).toContain(`left=${fallback.left}`);+ expect(features).toContain(`top=${fallback.top}`);+ });++ it('keeps the placement while a second display is attached', () => {+ const features = openedFeatures(+ sourceOn({+ availWidth: 1600,+ availHeight: 1000,+ availLeft: 0,+ availTop: 0,+ isExtended: true,+ }),+ );++ expect(features).toContain('left=-1720');+ expect(features).toContain('top=-80');+ });++ it('keeps the placement when the browser does not report other displays', () => {+ const features = openedFeatures({+ screen: { availWidth: 1600, availHeight: 1000 },+ outerWidth: 1200,+ outerHeight: 900,+ screenX: 0,+ screenY: 0,+ localStorage: {+ getItem: () => JSON.stringify({ width: 900, height: 700, left: -1720, top: -80 }),+ },+ open: jest.fn(() => ({ focus: jest.fn() })),+ } as unknown as Window);++ expect(features).toContain('left=-1720');+ });++ it('keeps a placement that still overlaps this display', () => {+ const source = {+ screen: {+ availWidth: 1600,+ availHeight: 1000,+ availLeft: 0,+ availTop: 0,+ isExtended: false,+ },+ outerWidth: 1200,+ outerHeight: 900,+ screenX: 0,+ screenY: 0,+ localStorage: {+ getItem: () => JSON.stringify({ width: 900, height: 700, left: 640, top: 120 }),+ },+ open: jest.fn(() => ({ focus: jest.fn() })),+ } as unknown as Window;++ const features = openedFeatures(source);++ expect(features).toContain('left=640');+ expect(features).toContain('top=120');+ });+});++describe('mirrorDocumentStyles', () => {+ let host: HTMLStyleElement;+ let link: HTMLLinkElement;++ beforeEach(() => {+ jest.useFakeTimers();+ host = document.createElement('style');+ host.textContent = '.mirrored { color: red; }';+ link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = '/assets/app.css';+ document.head.append(host, link);+ });++ afterEach(() => {+ jest.useRealTimers();+ document.head.querySelectorAll('style, link').forEach((node) => node.remove());+ });++ it('mirrors the host stylesheets into the detached document', () => {+ const target = detachedDocument();++ const stop = mirrorDocumentStyles(document, target);++ expect(target.head.querySelector('style')?.textContent).toContain('.mirrored');+ expect(target.head.querySelector('style')?.textContent).toContain('color: red');+ expect(target.head.querySelector('link')?.href).toContain('/assets/app.css');++ stop();+ expect(target.head.querySelector('style')).toBeNull();+ expect(target.head.querySelector('link')).toBeNull();+ });++ it('picks up a stylesheet added after the window opened', async () => {+ const target = detachedDocument();+ const stop = mirrorDocumentStyles(document, target);++ const lazyChunkStyle = document.createElement('style');+ lazyChunkStyle.textContent = '.lazy { color: blue; }';+ document.head.appendChild(lazyChunkStyle);+ await Promise.resolve();++ expect(target.head.textContent).toContain('.lazy');+ expect(target.head.textContent).toContain('color: blue');+ stop();+ });++ /* A sheet can change what it applies to without any of its content moving:+ * a `media` switch, or a `disabled` flag, is an attribute and nothing else.+ * The popup shows the host's styling, so it has to follow. */+ it('follows a stylesheet that changes which medium it applies to', async () => {+ link.media = 'print';+ const target = detachedDocument();+ const stop = mirrorDocumentStyles(document, target);+ expect(target.head.querySelector('link')?.getAttribute('media')).toBe('print');++ link.media = 'all';+ await Promise.resolve();++ expect(target.head.querySelector('link')?.getAttribute('media')).toBe('all');+ stop();+ });++ it('follows a stylesheet the host switches off', async () => {+ const target = detachedDocument();+ const stop = mirrorDocumentStyles(document, target);+ expect(target.head.querySelector('link')?.hasAttribute('disabled')).toBe(false);++ link.setAttribute('disabled', '');+ await Promise.resolve();++ expect(target.head.querySelector('link')?.hasAttribute('disabled')).toBe(true);+ stop();+ });++ /* A sheet the host had already switched off before the window opened: the+ * clone has to arrive switched off too, because from then on its signature+ * matches and nothing would come back to correct it. */+ it('mirrors a stylesheet that was already switched off when the window opened', () => {+ link.setAttribute('disabled', '');+ link.media = 'print';+ const target = detachedDocument();++ const stop = mirrorDocumentStyles(document, target);++ const clone = target.head.querySelector('link');+ expect(clone?.hasAttribute('disabled')).toBe(true);+ expect(clone?.getAttribute('media')).toBe('print');+ stop();+ });++ /* A rewrite that keeps the text length and the rule count is invisible to+ * any cheap signature, so the mutation record has to drive the refresh. */+ it('mirrors a rewrite that changes no measurable shape', async () => {+ const target = detachedDocument();+ const stop = mirrorDocumentStyles(document, target);++ host.textContent = '.mirrored { color: RED; }'.replace('RED', 'tan');+ await Promise.resolve();++ expect(target.head.textContent).toContain('color: tan');+ expect(target.head.textContent).not.toContain('color: red');+ stop();+ });++ /* Monaco writes its dynamic rules straight into the CSSOM, which mutates no+ * node: only the periodic re-check can notice them. */+ it('mirrors rules inserted through the CSSOM', () => {+ const target = detachedDocument();+ const dynamic = document.createElement('style');+ document.head.appendChild(dynamic);+ const stop = mirrorDocumentStyles(document, target);++ dynamic.sheet?.insertRule('.inserted { color: green; }', 0);+ jest.advanceTimersByTime(1000);++ expect(target.head.textContent).toContain('.inserted');+ stop();+ });+});++describe('mirrorDocumentTheme', () => {+ afterEach(() => {+ document.documentElement.removeAttribute('data-theme');+ document.documentElement.className = '';+ document.documentElement.removeAttribute('style');+ });++ it('follows the host theme while the window is open', () => {+ document.documentElement.className = 'dark';+ document.documentElement.dataset.theme = 'midnight';+ document.documentElement.style.setProperty('--surface-primary', '13 13 13');+ const target = detachedDocument();++ const stop = mirrorDocumentTheme(document, target);+ expect(target.documentElement.className).toBe('dark');+ expect(target.documentElement.dataset.theme).toBe('midnight');+ expect(target.documentElement.style.getPropertyValue('--surface-primary')).toBe('13 13 13');++ document.documentElement.className = 'light high-contrast';+ document.documentElement.removeAttribute('data-theme');++ return Promise.resolve().then(() => {+ expect(target.documentElement.className).toBe('light high-contrast');+ expect(target.documentElement.hasAttribute('data-theme')).toBe(false);+ stop();+ });+ });+});++describe('relayFrameMessages', () => {+ it('re-dispatches frame messages on the host window with their source intact', () => {+ const detached = { addEventListener: jest.fn(), removeEventListener: jest.fn() };+ const stop = relayFrameMessages(window, detached as unknown as Window);+ const relay = detached.addEventListener.mock.calls[0][1] as (event: MessageEvent) => void;++ const received: MessageEvent[] = [];+ const listener = (event: Event) => received.push(event as MessageEvent);+ window.addEventListener('message', listener);++ const frameWindow = {} as Window;+ relay(+ new MessageEvent('message', {+ data: { codesandbox: true, type: 'initialize' },+ source: frameWindow,+ origin: 'https://bundler.example',+ }),+ );++ expect(received).toHaveLength(1);+ expect(received[0].data).toEqual({ codesandbox: true, type: 'initialize' });+ expect(received[0].source).toBe(frameWindow);+ expect(received[0].origin).toBe('https://bundler.example');++ /* The popup's own messages must not bounce back into the host. */+ relay(new MessageEvent('message', { data: 'noise', source: detached as unknown as Window }));+ expect(received).toHaveLength(1);++ window.removeEventListener('message', listener);+ stop();+ expect(detached.removeEventListener).toHaveBeenCalled();+ });+});++describe('prepareUndockedDocument', () => {+ it('gives the popup a portal root and a base URL to resolve assets against', () => {+ const target = detachedDocument();++ const root = prepareUndockedDocument(document, target);++ expect(root.parentElement).toBe(target.body);+ expect(target.body.children).toHaveLength(1);+ expect(target.head.querySelector('base')?.href).toBe(document.baseURI);+ });+});diff --git a/client/src/components/Artifacts/state.ts b/client/src/components/Artifacts/state.tsnew file mode 100644index 0000000000..ca80ad48b2--- /dev/null+++ b/client/src/components/Artifacts/state.ts@@ -0,0 +1,45 @@+import { atom } from 'jotai';++export interface UndockedArtifactsTarget {+ /** The popup hosting the pane. */+ window: Window;+ /** Its portal container, prepared before the pane is handed over. */+ root: HTMLElement;+}++/**+ * Where the artifacts pane currently lives, or `null` while it is docked in+ * the side panel.+ *+ * The prepared container travels with the window so the host can portal into+ * it on its first render: the pane's Recoil-backed registry only survives the+ * move if the new instance mounts in the same commit the docked one unmounts.+ * Clearing this atom is the single instruction to come home.+ */+export const undockedArtifacts = atom<UndockedArtifactsTarget | null>(null);++export const artifactsUndocked = atom((get) => get(undockedArtifacts) != null);++/**+ * Which tab the pane is showing. The pane is a new instance in every host, so+ * a user who undocks while reading code has to arrive in the window on the+ * code tab — with the text they were typing — rather than back on the preview.+ */+export const artifactsActiveTab = atom<string>('preview');++/**+ * The artifact the pane last opened, which is what makes the tab reset above+ * mean "a different artifact" rather than "a new pane instance". Changing host+ * remounts the pane, so an instance-local ref would read the artifact already+ * on screen as freshly opened and send the user back to the preview — losing+ * the tab this atom exists to carry.+ */+export const artifactsOpenedArtifactId = atom<string | null>(null);++/**+ * Set when the user moves the pane from its own toolbar, either way. That+ * button goes away with the toolbar it lived in, so the pane that takes over+ * has to pick focus up again — a keyboard user would otherwise land on the+ * document of whichever window they were sent to.+ */+export const artifactsPaneFocusRequest = atom(false);diff --git a/client/src/components/Artifacts/undockedWindow.ts b/client/src/components/Artifacts/undockedWindow.tsnew file mode 100644index 0000000000..11f5410bb8--- /dev/null+++ b/client/src/components/Artifacts/undockedWindow.ts@@ -0,0 +1,493 @@+/**+ * DOM plumbing for the undocked artifacts pane.+ *+ * The pane stays part of the host window's React tree and is portaled into a+ * popup document, so artifacts keep streaming into it and the editor keeps its+ * state while the user drags the window to another screen. A portal moves+ * nodes, not the document that styled them, so everything the popup needs from+ * the host — stylesheets, the resolved theme, the Sandpack message channel —+ * has to be mirrored explicitly.+ */++/**+ * Window names are shared between same-origin tabs that can reach each other,+ * and reusing one would let a second tab's undock take over the first tab's+ * window — leaving that pane portaled into a document nobody can see. One name+ * per loaded tab keeps them apart while still reusing this tab's own window.+ */+export const UNDOCKED_ARTIFACTS_WINDOW_NAME = `librechat-artifacts-${Math.random()+ .toString(36)+ .slice(2, 10)}`;+export const UNDOCKED_ARTIFACTS_BOUNDS_KEY = 'artifacts:undocked-window-bounds';++const MIN_WIDTH = 520;+const MIN_HEIGHT = 480;+/** CSSOM rule insertion (Monaco's dynamic rules) mutates no DOM node, so the+ * style observer never fires for it. Re-check the cheap signatures instead. */+const RESYNC_INTERVAL_MS = 1000;+/** Above this, a sheet is a compiled bundle: serialize its rules once per tick+ * and the mirror would cost more than the pane it is mirroring. */+const MAX_SERIALIZED_RULES = 400;+const STYLE_SELECTOR = 'style, link[rel~="stylesheet"]';+const MIRRORED_ROOT_ATTRIBUTES = ['class', 'style', 'data-theme', 'lang', 'dir'];+const ROOT_ELEMENT_ID = 'undocked-artifacts-root';++export interface UndockedWindowBounds {+ width: number;+ height: number;+ left: number;+ top: number;+}++const isFiniteNumber = (value: unknown): value is number =>+ typeof value === 'number' && Number.isFinite(value);++/** Screen coordinates are signed: a monitor left of the primary one reports a+ * negative `left`, so only the size is clamped. */+export function parseBounds(raw: string | null): UndockedWindowBounds | null {+ if (raw == null || raw === '') {+ return null;+ }+ try {+ const parsed = JSON.parse(raw) as Partial<UndockedWindowBounds>;+ if (+ !isFiniteNumber(parsed.width) ||+ !isFiniteNumber(parsed.height) ||+ !isFiniteNumber(parsed.left) ||+ !isFiniteNumber(parsed.top)+ ) {+ return null;+ }+ return {+ width: Math.max(MIN_WIDTH, Math.round(parsed.width)),+ height: Math.max(MIN_HEIGHT, Math.round(parsed.height)),+ left: Math.round(parsed.left),+ top: Math.round(parsed.top),+ };+ } catch {+ return null;+ }+}++export function defaultBounds(source: Window): UndockedWindowBounds {+ const availableWidth = source.screen?.availWidth ?? source.outerWidth ?? MIN_WIDTH;+ const availableHeight = source.screen?.availHeight ?? source.outerHeight ?? MIN_HEIGHT;+ const width = Math.max(MIN_WIDTH, Math.round(availableWidth * 0.45));+ const height = Math.max(MIN_HEIGHT, Math.round(availableHeight * 0.85));+ return {+ width,+ height,+ left: Math.round((source.screenX ?? 0) + Math.max(0, (source.outerWidth - width) / 2)),+ top: Math.round(source.screenY ?? 0) + 32,+ };+}++/** Enough of the window to see and grab, if that is all that overlaps. */+const MIN_VISIBLE_EDGE = 96;++/**+ * Whether remembered bounds can still put the window somewhere the user can+ * reach it. Coordinates outlive the monitor arrangement that produced them, and+ * the pane leaves this page when it undocks: a window opened onto a display+ * that no longer exists would take the artifact and its only Dock control with+ * it.+ *+ * `screen` describes the display the host window is on, so bounds on a second+ * monitor look off-screen here and are indistinguishable from bounds on a+ * monitor that was unplugged — except that `isExtended` says whether there is+ * another display at all. A desktop that reports exactly one is the only case+ * where the remembered rectangle is provably gone; anything else (including a+ * browser that does not report it) keeps the user's placement.+ */+export function isPlausibleOnScreen(bounds: UndockedWindowBounds, source: Window): boolean {+ const screen = source.screen as (Screen & { availLeft?: number; availTop?: number }) | undefined;+ if (screen == null || !isFiniteNumber(screen.availWidth) || !isFiniteNumber(screen.availHeight)) {+ return true;+ }+ const left = isFiniteNumber(screen.availLeft) ? screen.availLeft : 0;+ const top = isFiniteNumber(screen.availTop) ? screen.availTop : 0;+ const overlaps =+ bounds.left + bounds.width - MIN_VISIBLE_EDGE > left &&+ bounds.left + MIN_VISIBLE_EDGE < left + screen.availWidth &&+ bounds.top + bounds.height - MIN_VISIBLE_EDGE > top &&+ bounds.top + MIN_VISIBLE_EDGE < top + screen.availHeight;+ if (overlaps) {+ return true;+ }+ return (screen as Screen & { isExtended?: boolean }).isExtended !== false;+}++/**+ * Opens (or refocuses) the popup that hosts the undocked pane. Returns `null`+ * when the browser blocked it, which is the caller's cue to tell the user.+ * Must run inside the click handler: popup permission follows user activation.+ */+export function openUndockedWindow(source: Window): Window | null {+ let stored: string | null = null;+ try {+ /* A policy that denies Web Storage throws from the `localStorage` getter+ * itself, so the property is read inside the guard. Reaching for it at the+ * call site would throw before any of this could fall back to defaults. */+ stored = source.localStorage?.getItem(UNDOCKED_ARTIFACTS_BOUNDS_KEY) ?? null;+ } catch {+ stored = null;+ }+ const remembered = parseBounds(stored);+ const bounds =+ remembered != null && isPlausibleOnScreen(remembered, source)+ ? remembered+ : defaultBounds(source);+ const features = [+ 'popup=yes',+ `width=${bounds.width}`,+ `height=${bounds.height}`,+ `left=${bounds.left}`,+ `top=${bounds.top}`,+ ].join(',');++ const opened = source.open('', UNDOCKED_ARTIFACTS_WINDOW_NAME, features);+ if (opened == null) {+ return null;+ }+ opened.focus();+ return opened;+}++/**+ * Remembers where the user put the window so the next undock lands there.+ * Takes the opener rather than its `Storage`, because the `localStorage`+ * getter throws under a policy that denies storage and this runs on the+ * redock and teardown paths, which must finish.+ */+export function persistBounds(detached: Window, source: Window): void {+ try {+ const bounds: UndockedWindowBounds = {+ width: detached.outerWidth,+ height: detached.outerHeight,+ left: detached.screenX,+ top: detached.screenY,+ };+ /* A window mid-teardown reports zeroes, or nothing at all. */+ if (!isFiniteNumber(bounds.width) || bounds.width <= 0 || bounds.height <= 0) {+ return;+ }+ source.localStorage?.setItem(UNDOCKED_ARTIFACTS_BOUNDS_KEY, JSON.stringify(bounds));+ } catch {+ /* window already torn down, or storage denied */+ }+}++/**+ * Clears whatever the popup already holds and installs the portal container.+ * A named window is reused across undocks, so this has to be repeatable. The+ * layout rules live in an injected sheet rather than inline styles, because+ * the theme mirror overwrites the `<html>` style attribute wholesale.+ */+export function prepareUndockedDocument(source: Document, target: Document): HTMLElement {+ target.head.querySelectorAll('[data-undocked-artifacts]').forEach((node) => node.remove());++ /* The popup's own URL is `about:blank`, so relative asset URLs in mirrored+ * styles and markup need the host's base to resolve against. */+ const base = target.createElement('base');+ base.dataset.undockedArtifacts = 'base';+ base.href = source.baseURI;+ target.head.appendChild(base);++ /* A mirrored `<link>` is fetched, so the popup would paint its default white+ * canvas for that moment — jarring against a dark app. The host's resolved+ * surface serves as the `var()` fallback until the sheet arrives, after+ * which the real token (and any theme change) takes over. */+ const hostSurface =+ source.defaultView+ ?.getComputedStyle(source.documentElement)+ .getPropertyValue('--surface-primary')+ .trim() ?? '';+ const layout = target.createElement('style');+ layout.dataset.undockedArtifacts = 'layout';+ layout.textContent = [+ 'html, body { height: 100%; margin: 0; padding: 0; overflow: hidden; }',+ `body { background-color: rgb(var(--surface-primary${hostSurface === '' ? '' : `, ${hostSurface}`})); }`,+ `#${ROOT_ELEMENT_ID} { display: flex; height: 100%; width: 100%; overflow: hidden; }`,+ ].join('\n');+ target.head.appendChild(layout);++ const root = target.createElement('div');+ root.id = ROOT_ELEMENT_ID;+ target.body.replaceChildren(root);+ return root;+}++const copyAttributes = (source: Element, target: Element, names: string[]): void => {+ for (const name of names) {+ const value = source.getAttribute(name);+ if (value == null) {+ target.removeAttribute(name);+ } else if (target.getAttribute(name) !== value) {+ target.setAttribute(name, value);+ }+ }+};++/**+ * Keeps the popup on the host's theme. The palette is a set of custom+ * properties on `<html>` plus an appearance class, both of which change while+ * the window is open (theme switch, high contrast), so mirror them live.+ */+export function mirrorDocumentTheme(source: Document, target: Document): () => void {+ const apply = () => {+ copyAttributes(source.documentElement, target.documentElement, MIRRORED_ROOT_ATTRIBUTES);+ copyAttributes(source.body, target.body, ['class']);+ };++ apply();+ const observer = new MutationObserver(apply);+ observer.observe(source.documentElement, {+ attributes: true,+ attributeFilter: MIRRORED_ROOT_ATTRIBUTES,+ });+ observer.observe(source.body, { attributes: true, attributeFilter: ['class'] });+ return () => observer.disconnect();+}++interface MirroredSheet {+ source: Element;+ clone: HTMLStyleElement | HTMLLinkElement;+ signature: string;+}++const readableRules = (element: Element): CSSRuleList | null => {+ try {+ return (element as HTMLStyleElement).sheet?.cssRules ?? null;+ } catch {+ /* opaque cross-origin sheet */+ return null;+ }+};++const serializeRules = (rules: CSSRuleList): string => {+ const parts: string[] = [];+ for (let index = 0; index < rules.length; index += 1) {+ parts.push(rules[index].cssText);+ }+ return parts.join('\n');+};++/**+ * The text to clone, and a signature that changes whenever that text does.+ *+ * A sheet the page drives through the CSSOM (Monaco's dynamic rules, CSS-in-JS)+ * can gain, lose or replace a rule without touching a single node, and its+ * source text may stay empty or keep its length. Those sheets are small, so+ * their serialized rules are both the content and the signature. A large sheet+ * — the compiled Tailwind bundle — is only ever rewritten through its text+ * node, which the mutation observer sees, so it is compared by cheap shape+ * instead of being serialized every second.+ */+const styleSnapshot = (element: Element): { text: string; signature: string } => {+ const text = element.textContent ?? '';+ const rules = readableRules(element);+ if (rules != null && rules.length <= MAX_SERIALIZED_RULES) {+ const serialized = serializeRules(rules);+ return { text: serialized === '' ? text : serialized, signature: `rules|${serialized}` };+ }+ return { text, signature: `text|${text.length}|${rules?.length ?? -1}` };+};++/** Attributes that decide whether, and where, a sheet applies. They are part+ * of the signature because a change to any of them changes the styling the+ * popup should be showing, without touching a rule or a text node. */+const SHEET_ATTRIBUTES = ['media', 'disabled', 'rel', 'href', 'type'] as const;++const attributeSignature = (element: Element): string =>+ SHEET_ATTRIBUTES.map((name) => element.getAttribute(name) ?? '').join('|');++const sheetSnapshot = (element: Element): { text: string; signature: string } => {+ const attributes = attributeSignature(element);+ if (element.tagName === 'LINK') {+ const link = element as HTMLLinkElement;+ return { text: '', signature: `link|${link.href}|${attributes}` };+ }+ const style = styleSnapshot(element);+ return { text: style.text, signature: `${style.signature}|${attributes}` };+};++/** Applies the attributes that travelled with the sheet to its clone. */+const mirrorSheetAttributes = (source: Element, clone: Element): void => {+ for (const name of SHEET_ATTRIBUTES) {+ const value = source.getAttribute(name);+ if (value == null) {+ clone.removeAttribute(name);+ } else if (clone.getAttribute(name) !== value) {+ clone.setAttribute(name, value);+ }+ }+};++const createClone = (element: Element, target: Document): HTMLStyleElement | HTMLLinkElement => {+ if (element.tagName === 'LINK') {+ const source = element as HTMLLinkElement;+ const clone = target.createElement('link');+ clone.href = source.href;+ if (source.crossOrigin != null) {+ clone.crossOrigin = source.crossOrigin;+ }+ /* The same attributes the sync keeps current, applied at birth: a sheet+ * the host had already switched off before the window opened would+ * otherwise arrive in the popup switched on, and its signature would+ * match from then on so nothing would correct it. */+ mirrorSheetAttributes(source, clone);+ return clone;+ }++ const source = element as HTMLStyleElement;+ const clone = target.createElement('style');+ clone.textContent = styleSnapshot(source).text;+ mirrorSheetAttributes(source, clone);+ return clone;+};++/**+ * Mirrors every host stylesheet into the popup and keeps them current: lazy+ * route chunks add sheets, dev HMR rewrites them, Monaco inserts rules.+ */+export function mirrorDocumentStyles(source: Document, target: Document): () => void {+ let mirrored: MirroredSheet[] = [];+ /* Nodes the observer saw change: a rewrite that keeps the same text length+ * is invisible to the signature, so the record decides instead. */+ const touched = new Set<Element>();++ const sync = () => {+ const nodes = Array.from(source.querySelectorAll(STYLE_SELECTOR));+ const unchangedSet =+ nodes.length === mirrored.length &&+ nodes.every((node, index) => mirrored[index].source === node);++ if (!unchangedSet) {+ for (const entry of mirrored) {+ entry.clone.remove();+ }+ mirrored = nodes.map((node) => {+ const clone = createClone(node, target);+ target.head.appendChild(clone);+ return { source: node, clone, signature: sheetSnapshot(node).signature };+ });+ touched.clear();+ return;+ }++ for (const entry of mirrored) {+ const { text, signature } = sheetSnapshot(entry.source);+ if (signature === entry.signature && !touched.has(entry.source)) {+ continue;+ }+ entry.signature = signature;+ mirrorSheetAttributes(entry.source, entry.clone);+ if (entry.clone.tagName === 'STYLE') {+ (entry.clone as HTMLStyleElement).textContent = text;+ } else {+ (entry.clone as HTMLLinkElement).href = (entry.source as HTMLLinkElement).href;+ }+ }+ touched.clear();+ };++ sync();++ const observer = new MutationObserver((records) => {+ for (const record of records) {+ const node = record.target;+ const element = node instanceof Element ? node : node.parentElement;+ const sheet = element?.closest(STYLE_SELECTOR);+ if (sheet != null) {+ touched.add(sheet);+ }+ }+ sync();+ });+ /* A sheet can be switched on, off or onto another medium by attribute alone+ * — `media`, `disabled`, or a `rel` that stops it being a stylesheet at all+ * — which touches no child and no text node. */+ observer.observe(source.head, {+ childList: true,+ subtree: true,+ characterData: true,+ attributes: true,+ attributeFilter: [...SHEET_ATTRIBUTES],+ });+ const interval = source.defaultView?.setInterval(sync, RESYNC_INTERVAL_MS);++ return () => {+ observer.disconnect();+ if (interval != null) {+ source.defaultView?.clearInterval(interval);+ }+ for (const entry of mirrored) {+ entry.clone.remove();+ }+ mirrored = [];+ touched.clear();+ };+}++/**+ * Sandpack listens for preview frames on the window its module was loaded in —+ * the host window — while an iframe inside the popup posts to `window.parent`,+ * which is the popup. Re-dispatch those frames on the host, preserving+ * `source` so Sandpack's "is this my iframe?" check still matches; without this+ * the preview would sit at its loading state forever once undocked.+ */+export function relayFrameMessages(source: Window, detached: Window): () => void {+ const relay = (event: MessageEvent) => {+ if (event.source == null || event.source === detached || event.source === source) {+ return;+ }+ source.dispatchEvent(+ new MessageEvent('message', {+ data: event.data,+ origin: event.origin,+ lastEventId: event.lastEventId,+ source: event.source,+ ports: [...event.ports],+ }),+ );+ };++ detached.addEventListener('message', relay);+ return () => detached.removeEventListener('message', relay);+}++/** Cross-realm: the popup's elements are not the host's `HTMLElement`. */+const isFocusable = (node: Element | null): node is HTMLElement =>+ node != null && typeof (node as HTMLElement).focus === 'function';++/**+ * The pre-Clipboard-API copy, run in a chosen document.+ *+ * `copy-to-clipboard` always drives `document.execCommand` in the realm it was+ * imported into — the host window — and an unfocused document copies nothing,+ * so an undocked pane on a non-secure deployment needs the selection dance+ * performed where the user actually is.+ */+export function copyWithinDocument(target: Document, text: string): boolean {+ const field = target.createElement('textarea');+ field.value = text;+ field.setAttribute('readonly', '');+ field.setAttribute('aria-hidden', 'true');+ field.style.cssText = 'position:fixed;top:0;left:-9999px;opacity:0;';+ target.body.appendChild(field);+ /* The element belongs to the popup's realm, so the host's `HTMLElement` is+ * not its constructor and `instanceof` would quietly refuse to restore the+ * user's place. Test the capability instead. */+ const activeElement = target.activeElement;+ const focusable = isFocusable(activeElement) ? activeElement : null;+ try {+ field.select();+ field.setSelectionRange(0, text.length);+ return target.execCommand('copy');+ } catch {+ return false;+ } finally {+ field.remove();+ focusable?.focus();+ }+}diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex 7cddaa218e..92db695e29 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -53,7 +53,16 @@ function LoadingSpinner() {);}-function ChatView({ index = 0, project }: { index?: number; project?: TChatProject }) {+function ChatView({+ index = 0,+ project,+ routePending = false,+}: {+ index?: number;+ project?: TChatProject;+ /** The route is loading another conversation, or failed to. */+ routePending?: boolean;+}) {const { conversationId } = useParams();const localize = useLocalize();const rootSubmission = useRecoilValue(store.submissionByIndex(index));@@ -181,7 +190,7 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje<ChatContext.Provider value={chatHelpers}><AddedChatContext.Provider value={addedChatHelpers}><ApprovalProvider pendingAction={pendingAction}>- <Presentation>+ <Presentation routePending={routePending}><TraceSurface conversationId={conversationId}><h1 className="sr-only">{pageHeading}</h1>{/* Marks the header's controls as this pane's, so a pane-scopeddiff --git a/client/src/components/Chat/Presentation.test.tsx b/client/src/components/Chat/Presentation.test.tsxindex a556ab7893..663d1bd556 100644--- a/client/src/components/Chat/Presentation.test.tsx+++ b/client/src/components/Chat/Presentation.test.tsx@@ -1,11 +1,13 @@import React from 'react';import { useSetAtom } from 'jotai';import { RecoilRoot, useSetRecoilState } from 'recoil';-import { fireEvent, render, screen } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { TConversation } from 'librechat-data-provider';import type { Artifact } from '~/common';+import { prepareUndockedDocument } from '~/components/Artifacts/undockedWindow';import { activeSubagentPanel } from '~/components/Chat/Subagents/state';+import { undockedArtifacts } from '~/components/Artifacts/state';import { ChatSurfaceHarness } from 'test/harness';import Presentation from './Presentation';import store from '~/store';@@ -69,19 +71,24 @@ jest.mock('~/Providers', () => ({EditorProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,}));-jest.mock('~/hooks/Artifacts/useResetArtifactsOnConversationChange', () => ({+jest.mock('~/hooks/Artifacts/useArtifactsRegistryLifetime', () => ({__esModule: true,default: jest.fn(),}));jest.mock('~/data-provider', () => ({useDeleteFilesMutation: () => ({ mutateAsync: jest.fn() }),+ useGetStartupConfig: () => ({ data: undefined }),useParentSubagentsQuery: (conversationId: string, config?: unknown, isSubmitting?: boolean) =>mockUseParentSubagentsQuery(conversationId, config, isSubmitting),}));jest.mock('~/hooks', () => ({useSetFilesToDelete: () => jest.fn(),+ useLocalize:+ () =>+ (key: string): string =>+ key,}));const OpenArtifactPanel = () => {@@ -234,4 +241,45 @@ describe('Presentation Artifact loading', () => {expect(await screen.findByText(mockArtifactPanelLabel)).toBeInTheDocument();expect(screen.queryByText(mockChildPanelLabel)).not.toBeInTheDocument();});++ /* Undocked, the artifacts pane is in its own window and the side panel is+ * free: a child-activity panel opened there has to stay open. */+ it('keeps child activity in the side panel while the artifacts pane is undocked', async () => {+ const detachedDocument = document.implementation.createHTMLDocument('');+ const root = prepareUndockedDocument(document, detachedDocument);+ const detachedWindow = {+ document: detachedDocument,+ closed: false,+ outerWidth: 900,+ outerHeight: 700,+ screenX: 0,+ screenY: 0,+ focus: jest.fn(),+ addEventListener: jest.fn(),+ removeEventListener: jest.fn(),+ close: jest.fn(),+ } as unknown as Window;++ renderPresentation(+ <ChatSurfaceHarness+ seed={(store) => store.set(undockedArtifacts, { window: detachedWindow, root })}+ >+ <RecoilRoot>+ <Presentation>+ <OpenSubagentPanel />+ <OpenArtifactPanel />+ </Presentation>+ </RecoilRoot>+ </ChatSurfaceHarness>,+ );++ fireEvent.click(screen.getByRole('button', { name: mockOpenArtifactLabel }));+ fireEvent.click(screen.getByRole('button', { name: mockOpenChildLabel }));++ expect(await screen.findByText(mockChildPanelLabel)).toBeInTheDocument();+ expect(screen.queryByText(mockArtifactPanelLabel)).not.toBeInTheDocument();+ await waitFor(() =>+ expect(detachedDocument.body.textContent).toContain(mockArtifactPanelLabel),+ );+ });});diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsxindex 0628dff715..7fe4c32b35 100644--- a/client/src/components/Chat/Presentation.tsx+++ b/client/src/components/Chat/Presentation.tsx@@ -3,12 +3,14 @@ import { useRecoilValue } from 'recoil';import { useAtomValue, useSetAtom } from 'jotai';import { EModelEndpoint, FileSources, LocalStorageKeys } from 'librechat-data-provider';import type { ExtendedFile } from '~/common';-import useResetArtifactsOnConversationChange from '~/hooks/Artifacts/useResetArtifactsOnConversationChange';import { ParentSubagentsProvider } from '~/components/Chat/Subagents/ParentSubagentsProvider';+import useArtifactsRegistryLifetime from '~/hooks/Artifacts/useArtifactsRegistryLifetime';+import { useDeleteFilesMutation, useGetStartupConfig } from '~/data-provider';import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';+import UndockedArtifacts from '~/components/Artifacts/UndockedArtifacts';import { activeSubagentPanel } from '~/components/Chat/Subagents/state';+import { artifactsUndocked } from '~/components/Artifacts/state';import { EditorProvider, ArtifactsProvider } from '~/Providers';-import { useDeleteFilesMutation } from '~/data-provider';import { SidePanelGroup } from '~/components/SidePanel';import AppChatSurface from '~/components/Chat/Surface';import { useSetFilesToDelete } from '~/hooks';@@ -18,7 +20,13 @@ import store from '~/store';const Artifacts = lazy(() => import('~/components/Artifacts/Artifacts'));const SubagentThreadPanel = lazy(() => import('~/components/Chat/Subagents/SubagentThreadPanel'));-export default function Presentation({ children }: { children: React.ReactNode }) {+export default function Presentation({+ children,+ routePending = false,+}: {+ children: React.ReactNode;+ routePending?: boolean;+}) {const artifacts = useRecoilValue(store.artifactsState);const artifactsVisibility = useRecoilValue(store.artifactsVisibility);// Render-gating the panel on `currentArtifactId != null` (in addition@@ -33,12 +41,13 @@ export default function Presentation({ children }: { children: React.ReactNode }const conversationEndpoint = useRecoilValue(store.effectiveEndpointByIndex(0));const conversationAgentId = useRecoilValue(store.conversationAgentIdByIndex(0));const isSubmitting = useRecoilValue(store.isSubmittingFamily(0));+ const isUndocked = useAtomValue(artifactsUndocked);const selectedSubagent = useAtomValue(activeSubagentPanel);const setSelectedSubagent = useSetAtom(activeSubagentPanel);const resetSelectedSubagent = useCallback(() => setSelectedSubagent(null), [setSelectedSubagent]);const previousConversationIdRef = useRef<string | null>(null);- useResetArtifactsOnConversationChange();+ useArtifactsRegistryLifetime(conversationId);useEffect(() => {const previous = previousConversationIdRef.current;@@ -49,6 +58,7 @@ export default function Presentation({ children }: { children: React.ReactNode }const setFilesToDelete = useSetFilesToDelete();+ const { data: startupConfig, isSuccess: hasStartupConfig } = useGetStartupConfig();const { mutateAsync } = useDeleteFilesMutation({onSuccess: (result) => {console.log('Temporary Files deleted');@@ -100,6 +110,14 @@ export default function Presentation({ children }: { children: React.ReactNode }mutateAsync({ files });}, [mutateAsync]);+ /* The deployment's answer about the undocked window, resolved once by the+ * host and handed to the pane. Until the config has actually answered the+ * capability is unknown, and offering the control then would both let a user+ * undock a pane the deployment forbids and take the Dock control away from+ * them when the answer arrived. */+ const canUndock = hasStartupConfig && startupConfig?.interface?.artifactUndocking !== false;+ const artifactsProviderValue = useMemo(() => ({ canUndock }), [canUndock]);+const artifactsElement = useMemo(() => {if (artifactsVisibility === true &&@@ -107,21 +125,24 @@ export default function Presentation({ children }: { children: React.ReactNode }Object.keys(artifacts ?? {}).length > 0) {return (- <ArtifactsProvider>- <EditorProvider>- <Suspense fallback={null}>- <Artifacts />- </Suspense>- </EditorProvider>+ <ArtifactsProvider value={artifactsProviderValue}>+ <Suspense fallback={null}>+ <Artifacts />+ </Suspense></ArtifactsProvider>);}return null;- }, [artifactsVisibility, artifacts, currentArtifactId]);+ }, [artifactsVisibility, artifacts, currentArtifactId, artifactsProviderValue]);+ /* The two panels are mutually exclusive only while they compete for the same+ * slot. Undocked, the artifacts pane is in its own window and the side panel+ * is free, so a child-activity panel opened there must survive. */useEffect(() => {- if (artifactsElement != null && selectedSubagent != null) resetSelectedSubagent();- }, [artifactsElement, resetSelectedSubagent, selectedSubagent]);+ if (!isUndocked && artifactsElement != null && selectedSubagent != null) {+ resetSelectedSubagent();+ }+ }, [artifactsElement, isUndocked, resetSelectedSubagent, selectedSubagent]);const subagentElement = useMemo(() => {if (@@ -138,22 +159,31 @@ export default function Presentation({ children }: { children: React.ReactNode });}, [conversationId, selectedSubagent]);- const panelElement = artifactsElement ?? subagentElement;+ /* Undocked, the pane renders into its own window: the side panel gives its+ * width back to the conversation instead of holding an empty column. */+ const panelElement = (isUndocked ? null : artifactsElement) ?? subagentElement;return (<DragDropWrapper className="bg-surface-primary-alt relative flex w-full grow overflow-hidden"><AppChatSurface>- <ParentSubagentsProvider- conversationId={conversationId ?? ''}- enabled={conversationEndpoint === EModelEndpoint.agents && conversationAgentId != null}- isSubmitting={isSubmitting}- >- <SidePanelGroup panel={panelElement}>- <main className="flex h-full flex-col overflow-y-auto" role="main">- {children}- </main>- </SidePanelGroup>- </ParentSubagentsProvider>+ {/* The editor buffer belongs to the pane's session, not to the window+ it happens to be in: hoisted, an undock keeps unsaved edits. */}+ <EditorProvider>+ <ParentSubagentsProvider+ conversationId={conversationId ?? ''}+ enabled={conversationEndpoint === EModelEndpoint.agents && conversationAgentId != null}+ isSubmitting={isSubmitting}+ >+ <SidePanelGroup panel={panelElement}>+ <main className="flex h-full flex-col overflow-y-auto" role="main">+ {children}+ </main>+ </SidePanelGroup>+ </ParentSubagentsProvider>+ {isUndocked && artifactsElement != null && (+ <UndockedArtifacts hidden={routePending}>{artifactsElement}</UndockedArtifacts>+ )}+ </EditorProvider></AppChatSurface></DragDropWrapper>);diff --git a/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts b/client/src/components/Messages/Content/Mermaid/useMermaidZoom.tsindex 37153e4003..bb420182fb 100644--- a/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts+++ b/client/src/components/Messages/Content/Mermaid/useMermaidZoom.ts@@ -56,13 +56,17 @@ export default function useMermaidZoom({ containerRef, wheelDep }: UseMermaidZoo});};const onUp = () => setIsPanning(false);- document.addEventListener('mousemove', onMove);- document.addEventListener('mouseup', onUp);+ /* The diagram can be portaled into another window (the undocked artifacts+ * pane), where pointer events stay in that document and never reach the+ * opener's: drag and release must be observed where the canvas lives. */+ const eventDocument = containerRef?.current?.ownerDocument ?? document;+ eventDocument.addEventListener('mousemove', onMove);+ eventDocument.addEventListener('mouseup', onUp);return () => {- document.removeEventListener('mousemove', onMove);- document.removeEventListener('mouseup', onUp);+ eventDocument.removeEventListener('mousemove', onMove);+ eventDocument.removeEventListener('mouseup', onUp);};- }, [isPanning]);+ }, [containerRef, isPanning]);useEffect(() => {const container = containerRef?.current;diff --git a/client/src/components/Share/ShareArtifacts.tsx b/client/src/components/Share/ShareArtifacts.tsxindex e704c56b89..0dc3fa131d 100644--- a/client/src/components/Share/ShareArtifacts.tsx+++ b/client/src/components/Share/ShareArtifacts.tsx@@ -1,4 +1,5 @@import { lazy, Suspense, useState, useMemo } from 'react';+import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import {useMediaQuery,@@ -8,8 +9,13 @@ import {} from '@librechat/client';import type { TMessage } from 'librechat-data-provider';import type { ArtifactsContextValue } from '~/Providers';+import useArtifactsRegistryLifetime from '~/hooks/Artifacts/useArtifactsRegistryLifetime';+import UndockedArtifacts from '~/components/Artifacts/UndockedArtifacts';+import { artifactsUndocked } from '~/components/Artifacts/state';import { ArtifactsProvider, EditorProvider } from '~/Providers';+import { useGetSharedStartupConfig } from '~/data-provider';import { isCodeOnlyArtifact } from '~/utils/artifacts';+import { useShareContext } from '~/Providers';import { getLatestText } from '~/utils';import store from '~/store';@@ -43,7 +49,7 @@ const getInitialArtifactPanelSize = () => {interface ShareArtifactsContainerProps {messages: TMessage[];- conversationId: string;+ conversationId: string | null | undefined;mainContent: React.ReactNode;}@@ -59,7 +65,25 @@ export function ShareArtifactsContainer({const artifactsVisibility = useRecoilValue(store.artifactsVisibility);const currentArtifactId = useRecoilValue(store.currentArtifactId);const isSmallScreen = useMediaQuery('(max-width: 1023px)');+ const isUndocked = useAtomValue(artifactsUndocked);const [artifactPanelSize, setArtifactPanelSize] = useState(getInitialArtifactPanelSize);+ /* This is the shared conversation's identity, not the chat tab's Recoil+ * slot. It may be absent while shared data loads; the lifetime hook keeps+ * the last real identity through that loading transition. */+ useArtifactsRegistryLifetime(conversationId);++ const { shareId } = useShareContext();+ const { data: sharedStartupConfig, isSuccess: hasSharedConfig } = useGetSharedStartupConfig(+ shareId,+ {+ enabled: typeof shareId === 'string' && shareId !== '',+ },+ );+ /* An absent field reads as enabled, which is the default and today's pane,+ * but only once the config has answered: offering the control while the+ * request is still in flight would let a viewer undock a pane the+ * deployment forbids, and the answer would then strand it. */+ const canUndock = hasSharedConfig && sharedStartupConfig?.interface?.artifactUndocking !== false;const artifactsContextValue = useMemo<ArtifactsContextValue | null>(() => {const latestMessage =@@ -76,8 +100,9 @@ export function ShareArtifactsContainer({latestMessageId: latestMessage.messageId ?? null,latestMessageText,conversationId: conversationId ?? null,+ canUndock,};- }, [messages, conversationId]);+ }, [messages, conversationId, canUndock]);const hasSelectedArtifact = currentArtifactId != null && artifacts?.[currentArtifactId] != null;const hasAutoOpenableArtifact = Object.values(artifacts ?? {}).some(@@ -102,42 +127,48 @@ export function ShareArtifactsContainer({}};- if (!shouldRenderArtifacts || !artifactsContextValue) {- return <>{mainContent}</>;- }-- if (isSmallScreen) {- return (- <>- {mainContent}- <ShareArtifactsOverlay contextValue={artifactsContextValue} />- </>- );- }-+ const paneContext = shouldRenderArtifacts ? artifactsContextValue : null;+ const pane = paneContext != null ? <ShareArtifactsPanel contextValue={paneContext} /> : null;+ const overlay = paneContext != null ? <ShareArtifactsOverlay contextValue={paneContext} /> : null;+ const showDockedPanel = pane != null && !isUndocked && !isSmallScreen;++ /* The transcript keeps one place in the tree through every state: React+ * cannot preserve it across a change of ancestry, so opening the pane,+ * undocking it or docking it again would each remount the conversation and+ * throw away the reader's scroll position. Only the pane's host changes —+ * a second resizable panel, a mobile overlay, or its own window — and the+ * provider that owns the editor buffer stays mounted above all of them. */return (- <ResizablePanelGroup- orientation="horizontal"- className="h-full w-full"- onLayoutChanged={handleLayoutChanged}- >- <ResizablePanel- defaultSize={`${100 - normalizedArtifactSize}`}- minSize="35"- id="share-content"- >- {mainContent}- </ResizablePanel>- <ResizableHandleAlt withHandle className="bg-border-medium text-text-primary" />- <ResizablePanel- defaultSize={`${normalizedArtifactSize}`}- minSize="20"- maxSize="60"- id="share-artifacts"+ <EditorProvider>+ <ResizablePanelGroup+ orientation="horizontal"+ className="h-full w-full"+ onLayoutChanged={handleLayoutChanged}>- <ShareArtifactsPanel contextValue={artifactsContextValue} />- </ResizablePanel>- </ResizablePanelGroup>+ <ResizablePanel+ defaultSize={`${showDockedPanel ? 100 - normalizedArtifactSize : 100}`}+ minSize="35"+ id="share-content"+ >+ {mainContent}+ </ResizablePanel>+ {showDockedPanel && (+ <ResizableHandleAlt withHandle className="bg-border-medium text-text-primary" />+ )}+ {showDockedPanel && (+ <ResizablePanel+ defaultSize={`${normalizedArtifactSize}`}+ minSize="20"+ maxSize="60"+ id="share-artifacts"+ >+ {pane}+ </ResizablePanel>+ )}+ </ResizablePanelGroup>+ {pane != null && isUndocked && <UndockedArtifacts>{pane}</UndockedArtifacts>}+ {pane != null && !isUndocked && isSmallScreen && overlay}+ </EditorProvider>);}@@ -151,13 +182,11 @@ interface ShareArtifactsPanelProps {function ShareArtifactsPanel({ contextValue }: ShareArtifactsPanelProps) {return (<ArtifactsProvider value={contextValue}>- <EditorProvider>- <div className="flex h-full w-full border-l border-border-light bg-surface-primary shadow-2xl">- <Suspense fallback={null}>- <Artifacts />- </Suspense>- </div>- </EditorProvider>+ <div className="border-border-light bg-surface-primary flex h-full w-full border-l shadow-2xl">+ <Suspense fallback={null}>+ <Artifacts />+ </Suspense>+ </div></ArtifactsProvider>);}diff --git a/client/src/data-provider/Messages/mutations.ts b/client/src/data-provider/Messages/mutations.tsindex 20be61b914..b643974e72 100644--- a/client/src/data-provider/Messages/mutations.ts+++ b/client/src/data-provider/Messages/mutations.ts@@ -1,5 +1,5 @@import { useMutation, useQueryClient } from '@tanstack/react-query';-import { dataService, QueryKeys, Constants } from 'librechat-data-provider';+import { dataService, QueryKeys, MutationKeys, Constants } from 'librechat-data-provider';import type { UseMutationResult, UseMutationOptions } from '@tanstack/react-query';import type * as t from 'librechat-data-provider';@@ -25,6 +25,7 @@ export const useEditArtifact = (t.TEditArtifactRequest,EditArtifactContext> = {+ mutationKey: [MutationKeys.editArtifact],mutationFn: (variables: t.TEditArtifactRequest) => dataService.editArtifact(variables),/*** onMutate: No optimistic updates for artifact editingdiff --git a/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts b/client/src/hooks/Artifacts/__tests__/useArtifacts.test.tsindex 57a9dcb4a6..d5d63abf04 100644--- a/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts+++ b/client/src/hooks/Artifacts/__tests__/useArtifacts.test.ts@@ -1,6 +1,12 @@+import { getDefaultStore } from 'jotai';import { Constants } from 'librechat-data-provider';import { renderHook, act } from '@testing-library/react';import type { Artifact } from '~/common';+import { artifactsActiveTab } from '~/components/Artifacts/state';++/* Referenced only when `useCodeState` is called, so the mock factory running+ * before these initialize is fine. */+const mockEndCodeSession = jest.fn();/** Mock dependencies */jest.mock('~/Providers', () => ({@@ -13,6 +19,10 @@ jest.mock('~/utils', () => ({},}));+jest.mock('~/Providers/EditorContext', () => ({+ useCodeState: () => ({ endCodeSession: mockEndCodeSession }),+}));+/** Mock store before importing */jest.mock('~/store', () => ({__esModule: true,@@ -30,12 +40,13 @@ jest.mock('recoil', () => {useRecoilValue: jest.fn(),useRecoilState: jest.fn(),useResetRecoilState: jest.fn(),+ useRecoilCallback: jest.fn(),};});/** Import mocked functions after mocking */import { useArtifactsContext } from '~/Providers';-import { useRecoilValue, useRecoilState, useResetRecoilState } from 'recoil';+import { useRecoilValue, useRecoilState, useRecoilCallback, useResetRecoilState } from 'recoil';import { logger } from '~/utils';import useArtifacts from '../useArtifacts';@@ -60,6 +71,15 @@ describe('useArtifacts', () => {latestMessageText: '',conversationId: 'conv-1',};+ /** What a fresh snapshot reports while the hook's cleanup runs. */+ const paneSnapshot: Record<string, unknown> = {+ artifactsVisibility: false,+ currentArtifactId: null,+ };+ /** `useRecoilCallback` hands back one stable callback; a mock that returned a+ * new function per render would re-run every effect that depends on it. */+ let builtPaneCallback: () => unknown = () => undefined;+ const stablePaneCallback = () => builtPaneCallback();beforeEach(() => {jest.clearAllMocks();@@ -77,6 +97,23 @@ describe('useArtifacts', () => {}return jest.fn();});+ paneSnapshot.artifactsVisibility = false;+ paneSnapshot.currentArtifactId = null;+ (useRecoilCallback as jest.Mock).mockImplementation(+ (build: (iface: unknown) => () => unknown) => {+ builtPaneCallback = build({+ snapshot: {+ getLoadable: (atom: { key: string }) => ({+ valueMaybe: () => paneSnapshot[atom.key],+ }),+ },+ });+ return stablePaneCallback;+ },+ );+ /* The tab is pane state in a module-global store now, so one test's switch+ * would otherwise be the next test's starting point. */+ getDefaultStore().set(artifactsActiveTab, 'preview');});afterEach(() => {@@ -603,17 +640,40 @@ describe('useArtifacts', () => {});describe('cleanup on unmount', () => {- it('should reset artifacts when unmounting', () => {+ it('should reset artifacts and the tab when the pane closed', () => {(useRecoilValue as jest.Mock).mockReturnValue({});- const { unmount } = renderHook(() => useArtifacts());+ const { result, unmount } = renderHook(() => useArtifacts());+ act(() => result.current.setActiveTab('code'));unmount();expect(mockResetArtifacts).toHaveBeenCalled();expect(mockResetCurrentArtifactId).toHaveBeenCalled();+ expect(getDefaultStore().get(artifactsActiveTab)).toBe('preview');+ /* A buffer kept past the close would come back on the next open and be+ * submitted by the drain, so closing has to discard it. */+ expect(mockEndCodeSession).toHaveBeenCalled();expect(logger.log).toHaveBeenCalledWith('artifacts_visibility', 'Unmounting artifacts');});++ /* Moving the pane to another host — mobile sheet, undocked window —+ * unmounts one instance and mounts another while the pane stays open;+ * wiping the registry or the tab then would undo the move the user made. */+ it('keeps the artifacts and the tab when the pane is only changing hosts', () => {+ (useRecoilValue as jest.Mock).mockReturnValue({});+ paneSnapshot.artifactsVisibility = true;+ paneSnapshot.currentArtifactId = 'artifact-1';++ const { result, unmount } = renderHook(() => useArtifacts());+ act(() => result.current.setActiveTab('code'));+ unmount();++ expect(mockResetArtifacts).not.toHaveBeenCalled();+ expect(mockResetCurrentArtifactId).not.toHaveBeenCalled();+ expect(mockEndCodeSession).not.toHaveBeenCalled();+ expect(getDefaultStore().get(artifactsActiveTab)).toBe('code');+ });});describe('manual tab switching', () => {diff --git a/client/src/hooks/Artifacts/__tests__/useArtifactsRegistryLifetime.test.tsx b/client/src/hooks/Artifacts/__tests__/useArtifactsRegistryLifetime.test.tsxnew file mode 100644index 0000000000..f0e9db9ed7--- /dev/null+++ b/client/src/hooks/Artifacts/__tests__/useArtifactsRegistryLifetime.test.tsx@@ -0,0 +1,219 @@+import React, { useState } from 'react';+import { getDefaultStore } from 'jotai';+import { act, render } from '@testing-library/react';+import { RecoilRoot, useRecoilCallback } from 'recoil';+import type { TConversation } from 'librechat-data-provider';+import type { MutableSnapshot } from 'recoil';+import type { Artifact } from '~/common';+import { artifactsActiveTab, artifactsOpenedArtifactId } from '~/components/Artifacts/state';+import useArtifactsRegistryLifetime from '../useArtifactsRegistryLifetime';+import store from '~/store';++const buildArtifact = (id: string): Artifact => ({+ id,+ title: id,+ type: 'text/html',+ content: '<h1>x</h1>',+ messageId: 'msg-1',+ lastUpdateTime: 1,+});++const buildConversation = (conversationId: string | null): TConversation =>+ ({ conversationId }) as TConversation;++interface HarnessHandle {+ setConversation: (conversationId: string | null | undefined) => void;+ readArtifacts: () => Record<string, Artifact | undefined> | null;+ readCurrentId: () => string | null;+ readActiveTab: () => string;+ readOpenedArtifactId: () => string | null;+}++const Harness = ({+ handleRef,+ initialConversationId,+}: {+ handleRef: React.MutableRefObject<HarnessHandle | null>;+ initialConversationId: string | null | undefined;+}) => {+ const [conversationId, setConversationId] = useState<string | null | undefined>(+ initialConversationId,+ );+ useArtifactsRegistryLifetime(conversationId);+ const readArtifacts = useRecoilCallback(+ ({ snapshot }) =>+ () =>+ snapshot.getLoadable(store.artifactsState).getValue(),+ [],+ );+ const readCurrentId = useRecoilCallback(+ ({ snapshot }) =>+ () =>+ snapshot.getLoadable(store.currentArtifactId).getValue(),+ [],+ );++ if (handleRef.current == null) {+ handleRef.current = {+ setConversation: setConversationId,+ readArtifacts,+ readCurrentId,+ readActiveTab: () => getDefaultStore().get(artifactsActiveTab),+ readOpenedArtifactId: () => getDefaultStore().get(artifactsOpenedArtifactId),+ };+ }+ return null;+};++const renderHarness = (initial: {+ conversationId: string | null | undefined;+ artifacts: Record<string, Artifact>;+ currentId: string | null;+}) => {+ const initializeState = (snapshot: MutableSnapshot) => {+ snapshot.set(store.conversationByIndex(0), buildConversation(initial.conversationId ?? null));+ snapshot.set(store.artifactsState, initial.artifacts);+ snapshot.set(store.currentArtifactId, initial.currentId);+ };+ const handleRef: React.MutableRefObject<HarnessHandle | null> = { current: null };+ render(+ <RecoilRoot initializeState={initializeState}>+ <Harness handleRef={handleRef} initialConversationId={initial.conversationId} />+ </RecoilRoot>,+ );+ if (!handleRef.current) {+ throw new Error('Harness did not attach handle');+ }+ return handleRef.current;+};++describe('useArtifactsRegistryLifetime', () => {+ it('does not reset on first render (no previous conversation to compare against)', () => {+ const handle = renderHarness({+ conversationId: 'conv-A',+ artifacts: { 'art-1': buildArtifact('art-1') },+ currentId: 'art-1',+ });+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });+ expect(handle.readCurrentId()).toBe('art-1');+ });++ it('preserves artifacts when the conversation id stays the same', () => {+ const handle = renderHarness({+ conversationId: 'conv-A',+ artifacts: { 'art-1': buildArtifact('art-1') },+ currentId: 'art-1',+ });+ act(() => handle.setConversation('conv-A'));+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });+ expect(handle.readCurrentId()).toBe('art-1');+ });++ /* The leak this guard exists for: the panel was closed in one conversation,+ * a ToolArtifactCard's self-heal effect re-registered its entry while+ * `artifactsVisibility` stayed false, and the user moved on. Without the+ * wipe the next panel open — in the next chat or the next shared link —+ * would list the previous conversation's artifacts, and the pane would open+ * on the tab and artifact the reader left behind. */+ it('wipes all registry and pane session state when the passed identity changes', () => {+ const jotaiStore = getDefaultStore();+ jotaiStore.set(artifactsActiveTab, 'code');+ jotaiStore.set(artifactsOpenedArtifactId, 'leftover-from-A');+ const handle = renderHarness({+ conversationId: 'shared-A',+ artifacts: { 'leftover-from-A': buildArtifact('leftover-from-A') },+ currentId: 'leftover-from-A',+ });++ act(() => handle.setConversation('shared-B'));++ expect(handle.readArtifacts()).toBeNull();+ expect(handle.readCurrentId()).toBeNull();+ expect(handle.readActiveTab()).toBe('preview');+ expect(handle.readOpenedArtifactId()).toBeNull();+ });++ it('keeps the registry through an absent id while shared data is loading', () => {+ const handle = renderHarness({+ conversationId: undefined,+ artifacts: { 'art-1': buildArtifact('art-1') },+ currentId: 'art-1',+ });++ act(() => handle.setConversation('shared-A'));++ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });+ expect(handle.readCurrentId()).toBe('art-1');+ });++ /* A shared link's data can refetch and hand back nothing for a render. That+ * is the same conversation loading, so the reader must not lose the artifact+ * they have open — and its return must not read as a first sighting either,+ * because the next real switch still has to wipe. */+ it('keeps the registry when a loaded identity goes absent and comes back', () => {+ const handle = renderHarness({+ conversationId: 'shared-A',+ artifacts: { 'art-1': buildArtifact('art-1') },+ currentId: 'art-1',+ });++ act(() => handle.setConversation(undefined));+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });++ act(() => handle.setConversation('shared-A'));+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });+ expect(handle.readCurrentId()).toBe('art-1');++ act(() => handle.setConversation('shared-B'));+ expect(handle.readArtifacts()).toBeNull();+ expect(handle.readCurrentId()).toBeNull();+ });++ it('treats an initial null → defined transition as a first observation, not a switch', () => {+ // Initial conversation can flicker through `null` while a fresh chat+ // is still loading. Treating that null as a "previous" id would+ // wipe the very first artifacts that arrive.+ const handle = renderHarness({+ conversationId: null,+ artifacts: {},+ currentId: null,+ });+ act(() => handle.setConversation('conv-A'));+ expect(handle.readArtifacts()).toEqual({});+ });++ /* The pane's own cleanup keeps the registry while it only changes hosts, so+ * the host leaving the route is what has to clear it — otherwise the next+ * route (a shared conversation, say) opens showing this chat's artifact. */+ it('wipes the registry when the host unmounts', () => {+ const handleRef: React.MutableRefObject<HarnessHandle | null> = { current: null };+ const Host = () => {+ useArtifactsRegistryLifetime('conv-A');+ return null;+ };+ const App = ({ hostMounted }: { hostMounted: boolean }) => (+ <RecoilRoot+ initializeState={(snapshot: MutableSnapshot) => {+ snapshot.set(store.conversationByIndex(0), buildConversation('conv-A'));+ snapshot.set(store.artifactsState, { 'art-1': buildArtifact('art-1') });+ snapshot.set(store.currentArtifactId, 'art-1');+ }}+ >+ <Harness handleRef={handleRef} initialConversationId="conv-A" />+ {hostMounted && <Host />}+ </RecoilRoot>+ );++ const { rerender } = render(<App hostMounted={true} />);+ const handle = handleRef.current;+ if (!handle) {+ throw new Error('Harness did not attach handle');+ }+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });++ rerender(<App hostMounted={false} />);++ expect(handle.readArtifacts()).toBeNull();+ expect(handle.readCurrentId()).toBeNull();+ });+});diff --git a/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsx b/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsxdeleted file mode 100644index 2a41257568..0000000000--- a/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsx+++ /dev/null@@ -1,129 +0,0 @@-import React from 'react';-import { act, render } from '@testing-library/react';-import { RecoilRoot, useRecoilCallback, useSetRecoilState } from 'recoil';-import type { MutableSnapshot } from 'recoil';-import type { Artifact } from '~/common';-import type { TConversation } from 'librechat-data-provider';-import useResetArtifactsOnConversationChange from '../useResetArtifactsOnConversationChange';-import store from '~/store';--const buildArtifact = (id: string): Artifact => ({- id,- title: id,- type: 'text/html',- content: '<h1>x</h1>',- messageId: 'msg-1',- lastUpdateTime: 1,-});--const buildConversation = (conversationId: string | null): TConversation =>- ({ conversationId }) as TConversation;--interface HarnessHandle {- setConversation: (conversationId: string | null) => void;- readArtifacts: () => Record<string, Artifact | undefined> | null;- readCurrentId: () => string | null;-}--const Harness = ({ handleRef }: { handleRef: React.MutableRefObject<HarnessHandle | null> }) => {- useResetArtifactsOnConversationChange();- const setConvo = useSetRecoilState(store.conversationByIndex(0));- // useRecoilCallback's snapshot is read fresh at call time, so the test- // sees the latest committed atom values rather than a stale render-time- // closure.- const readArtifacts = useRecoilCallback(- ({ snapshot }) =>- () =>- snapshot.getLoadable(store.artifactsState).getValue(),- [],- );- const readCurrentId = useRecoilCallback(- ({ snapshot }) =>- () =>- snapshot.getLoadable(store.currentArtifactId).getValue(),- [],- );-- if (handleRef.current == null) {- handleRef.current = {- setConversation: (conversationId) => setConvo(buildConversation(conversationId)),- readArtifacts,- readCurrentId,- };- }- return null;-};--const renderHarness = (initial: {- conversationId: string | null;- artifacts: Record<string, Artifact>;- currentId: string | null;-}) => {- const initializeState = (snapshot: MutableSnapshot) => {- snapshot.set(store.conversationByIndex(0), buildConversation(initial.conversationId));- snapshot.set(store.artifactsState, initial.artifacts);- snapshot.set(store.currentArtifactId, initial.currentId);- };- const handleRef: React.MutableRefObject<HarnessHandle | null> = { current: null };- render(- <RecoilRoot initializeState={initializeState}>- <Harness handleRef={handleRef} />- </RecoilRoot>,- );- if (!handleRef.current) {- throw new Error('Harness did not attach handle');- }- return handleRef.current;-};--describe('useResetArtifactsOnConversationChange', () => {- it('does not reset on first render (no previous conversation to compare against)', () => {- const handle = renderHarness({- conversationId: 'conv-A',- artifacts: { 'art-1': buildArtifact('art-1') },- currentId: 'art-1',- });- expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });- expect(handle.readCurrentId()).toBe('art-1');- });-- it('preserves artifacts when the conversation id stays the same', () => {- const handle = renderHarness({- conversationId: 'conv-A',- artifacts: { 'art-1': buildArtifact('art-1') },- currentId: 'art-1',- });- act(() => handle.setConversation('conv-A'));- expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });- expect(handle.readCurrentId()).toBe('art-1');- });-- it('wipes artifactsState and currentArtifactId when the conversation id changes', () => {- // Reproduces the codex-flagged leak: panel was closed in conv-A, the- // ToolArtifactCard's self-heal effect re-registered while- // artifactsVisibility stayed false, and then the user switched to- // conv-B. Without this hook the next panel open in conv-B would show- // conv-A's artifacts in the version list.- const handle = renderHarness({- conversationId: 'conv-A',- artifacts: { 'leftover-from-A': buildArtifact('leftover-from-A') },- currentId: 'leftover-from-A',- });- act(() => handle.setConversation('conv-B'));- expect(handle.readArtifacts()).toBeNull();- expect(handle.readCurrentId()).toBeNull();- });-- it('treats an initial null → defined transition as a first observation, not a switch', () => {- // Initial conversation can flicker through `null` while a fresh chat- // is still loading. Treating that null as a "previous" id would- // wipe the very first artifacts that arrive.- const handle = renderHarness({- conversationId: null,- artifacts: {},- currentId: null,- });- act(() => handle.setConversation('conv-A'));- expect(handle.readArtifacts()).toEqual({});- });-});diff --git a/client/src/hooks/Artifacts/useArtifactDownload.ts b/client/src/hooks/Artifacts/useArtifactDownload.tsindex cd2b5252a6..69e5635ee7 100644--- a/client/src/hooks/Artifacts/useArtifactDownload.ts+++ b/client/src/hooks/Artifacts/useArtifactDownload.ts@@ -11,7 +11,7 @@ import {isLocallyStoredSource,} from '~/components/Chat/Messages/Content/Parts/LogLink';import useArtifactProps from '~/hooks/Artifacts/useArtifactProps';-import { useCodeState } from '~/Providers/EditorContext';+import { useArtifactCode } from '~/Providers/EditorContext';import useLocalize from '~/hooks/useLocalize';export interface ArtifactDownload {@@ -37,7 +37,11 @@ export interface ArtifactDownload {* bytes should be.*/export default function useArtifactDownload(artifact: Artifact): ArtifactDownload {- const { currentCode } = useCodeState();+ /* The buffer outlives a pane remount and belongs to whichever artifact last+ * wrote it, so downloading another artifact must not export those edits; a+ * copy this artifact left behind when another displaced it is still its own+ * unsaved text and exports with it. */+ const editedCode = useArtifactCode(artifact.id);const { showToast } = useToastContext();const localize = useLocalize();const [isDownloaded, setIsDownloaded] = useState(false);@@ -61,7 +65,7 @@ export default function useArtifactDownload(artifact: Artifact): ArtifactDownloa(download?.file_id != null &&download?.user != null &&isLocallyStoredSource(download?.source));- const hasEdits = currentCode != null && currentCode !== artifact.content;+ const hasEdits = editedCode != null && editedCode !== artifact.content;/*** Mermaid is no exception, even though the panel renders the diagram* straight from `content`: that content is the cached extraction, and@@ -99,7 +103,7 @@ export default function useArtifactDownload(artifact: Artifact): ArtifactDownloa}return downloaded;}- const content = currentCode ?? artifact.content;+ const content = editedCode ?? artifact.content;if (content == null) {/* Nothing to serialize and no route to fetch: the press has to* say something, or it looks like the download worked. */@@ -125,9 +129,9 @@ export default function useArtifactDownload(artifact: Artifact): ArtifactDownloa},[artifact,- currentCode,downloadAttachment,downloadOriginalFile,+ editedCode,fileName,localize,markDownloaded,diff --git a/client/src/hooks/Artifacts/useArtifacts.ts b/client/src/hooks/Artifacts/useArtifacts.tsindex 897e79c37b..414ceadb9a 100644--- a/client/src/hooks/Artifacts/useArtifacts.ts+++ b/client/src/hooks/Artifacts/useArtifacts.ts@@ -1,6 +1,13 @@-import { useMemo, useState, useEffect, useRef } from 'react';+import { useMemo, useEffect, useRef } from 'react';+import { useAtom, useSetAtom } from 'jotai';import { Constants } from 'librechat-data-provider';-import { useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil';+import { useRecoilCallback, useRecoilState, useRecoilValue, useResetRecoilState } from 'recoil';+import {+ artifactsActiveTab,+ artifactsOpenedArtifactId,+ artifactsPaneFocusRequest,+} from '~/components/Artifacts/state';+import { useCodeState } from '~/Providers/EditorContext';import { isCodeOnlyArtifact } from '~/utils/artifacts';import { useArtifactsContext } from '~/Providers';import { logger } from '~/utils';@@ -136,7 +143,12 @@ const hasEnclosedArtifact = (messageText: string): boolean => {};export default function useArtifacts() {- const [activeTab, setActiveTab] = useState('preview');+ /* Pane state, not instance state: the pane is remounted when it changes+ * hosts, and the tab the user was on has to come with it. */+ const [activeTab, setActiveTab] = useAtom(artifactsActiveTab);+ const setPaneFocusRequest = useSetAtom(artifactsPaneFocusRequest);+ const setOpenedArtifactId = useSetAtom(artifactsOpenedArtifactId);+ const { endCodeSession } = useCodeState();const { isSubmitting, latestMessageId, latestMessageText, conversationId } =useArtifactsContext();@@ -165,10 +177,36 @@ export default function useArtifacts() {const lastRunMessageIdRef = useRef<string | null>(null);const prevConversationIdRef = useRef<string | null>(null);+ /**+ * Whether the pane is closing for good rather than moving. The pane changes+ * hosts — side panel, mobile sheet, undocked window — by unmounting one+ * instance and mounting another, and clearing the registry on that unmount+ * would close the pane the user was moving. Closing clears visibility and+ * the focused id first, so a fresh snapshot distinguishes the two; the+ * component's own render props cannot, because the parent stops rendering+ * it before it sees the new values.+ */+ const isPaneClosed = useRecoilCallback(+ ({ snapshot }) =>+ () =>+ snapshot.getLoadable(store.artifactsVisibility).valueMaybe() !== true ||+ snapshot.getLoadable(store.currentArtifactId).valueMaybe() == null,+ [],+ );+useEffect(() => {const resetState = () => {resetArtifacts();resetCurrentArtifactId();+ /* The tab and the editor buffer outlive a host move but not the session:+ * the next artifact opens on the default view, with its own text, as it+ * did when both lived in the pane instance. Ending the code session also+ * tells a save still in flight that its callbacks have nothing to+ * restore here. */+ setActiveTab('preview');+ setOpenedArtifactId(null);+ endCodeSession();+ setPaneFocusRequest(false);prevConversationIdRef.current = conversationId;lastRunMessageIdRef.current = null;lastContentRef.current = null;@@ -181,12 +219,24 @@ export default function useArtifacts() {resetState();}prevConversationIdRef.current = conversationId;- /** Resets artifacts when unmounting */+ /** Resets artifacts when the pane closes */return () => {+ if (!isPaneClosed()) {+ return;+ }logger.log('artifacts_visibility', 'Unmounting artifacts');resetState();};- }, [conversationId, resetArtifacts, resetCurrentArtifactId]);+ }, [+ conversationId,+ isPaneClosed,+ resetArtifacts,+ resetCurrentArtifactId,+ setActiveTab,+ endCodeSession,+ setPaneFocusRequest,+ setOpenedArtifactId,+ ]);/*** Read currentArtifactId in effects without subscribing as a dependency.@@ -256,6 +306,7 @@ export default function useArtifacts() {latestMessageId,latestMessageText,orderedArtifactIds,+ setActiveTab,setCurrentArtifactId,]);@@ -274,7 +325,7 @@ export default function useArtifacts() {hasEnclosedArtifactRef.current = true;hasAutoSwitchedToCodeRef.current = false;}- }, [isSubmitting, latestMessageText]);+ }, [isSubmitting, latestMessageText, setActiveTab]);useEffect(() => {if (latestMessageId !== lastRunMessageIdRef.current) {diff --git a/client/src/hooks/Artifacts/useArtifactsRegistryLifetime.ts b/client/src/hooks/Artifacts/useArtifactsRegistryLifetime.tsnew file mode 100644index 0000000000..8858f122dd--- /dev/null+++ b/client/src/hooks/Artifacts/useArtifactsRegistryLifetime.ts@@ -0,0 +1,63 @@+import { useCallback, useEffect, useRef } from 'react';+import { useSetAtom } from 'jotai';+import { useResetRecoilState } from 'recoil';+import { artifactsActiveTab, artifactsOpenedArtifactId } from '~/components/Artifacts/state';+import store from '~/store';++/**+ * Bounds the artifact registry to one host and one conversation.+ *+ * The identity comes from the host, because which conversation is on screen is+ * the host's question to answer: the chat tab reads its Recoil slot, and a+ * shared conversation has its own id that slot never carries.+ *+ * Wipes `artifactsState` / `currentArtifactId` whenever that identity+ * changes. `useArtifacts` already runs this cleanup, but+ * only while the pane is mounted — so without a top-level guard,+ * tool-artifact cards that self-heal their entries while the panel is+ * closed would leak into the next conversation's panel on open. The+ * matching cards for the new conversation re-register via their own+ * self-heal subscription after this wipe lands.+ *+ * It also wipes on unmount, which is the host leaving: the pane's own cleanup+ * deliberately keeps the registry when it is only changing hosts (side panel,+ * mobile sheet, undocked window), so navigating away from this route — to a+ * shared conversation, say — has to be what clears it.+ */+export default function useArtifactsRegistryLifetime(+ conversationId: string | null | undefined,+): void {+ const resetArtifacts = useResetRecoilState(store.artifactsState);+ const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);+ const setActiveTab = useSetAtom(artifactsActiveTab);+ const setOpenedArtifactId = useSetAtom(artifactsOpenedArtifactId);+ const prevConversationIdRef = useRef<string | null>(null);++ /** The pane's view state belongs to the session the registry belongs to. */+ const endSession = useCallback(() => {+ resetArtifacts();+ resetCurrentArtifactId();+ setActiveTab('preview');+ setOpenedArtifactId(null);+ }, [resetArtifacts, resetCurrentArtifactId, setActiveTab, setOpenedArtifactId]);++ useEffect(() => {+ /* An absent id is a host that has nothing to report yet, not a different+ * conversation: a shared link's data can refetch, and the chat tab reads+ * its slot before it is filled. Wiping on the way through would take the+ * registry away from the conversation that owns it and then treat its+ * return as a first sighting, so the last real identity stays the one the+ * next id is compared against. */+ if (conversationId == null) {+ return;+ }+ const prev = prevConversationIdRef.current;+ prevConversationIdRef.current = conversationId;+ if (prev === null || prev === conversationId) {+ return;+ }+ endSession();+ }, [conversationId, endSession]);++ useEffect(() => () => endSession(), [endSession]);+}diff --git a/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.ts b/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.tsdeleted file mode 100644index 81151fcc1f..0000000000--- a/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.ts+++ /dev/null@@ -1,30 +0,0 @@-import { useEffect, useRef } from 'react';-import { useRecoilValue, useResetRecoilState } from 'recoil';-import store from '~/store';--/**- * Wipes `artifactsState` / `currentArtifactId` whenever the active- * conversation changes. `useArtifacts` already runs this cleanup, but- * only while the side panel is mounted — so without a top-level guard,- * tool-artifact cards that self-heal their entries while the panel is- * closed would leak into the next conversation's panel on open. The- * matching cards for the new conversation re-register via their own- * self-heal subscription after this wipe lands.- */-export default function useResetArtifactsOnConversationChange(): void {- const conversationId = useRecoilValue(store.conversationIdByIndex(0));- const resetArtifacts = useResetRecoilState(store.artifactsState);- const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);- const prevConversationIdRef = useRef<string | null>(null);-- useEffect(() => {- const prev = prevConversationIdRef.current;- const next = conversationId ?? null;- prevConversationIdRef.current = next;- if (prev == null || prev === next) {- return;- }- resetArtifacts();- resetCurrentArtifactId();- }, [conversationId, resetArtifacts, resetCurrentArtifactId]);-}diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 23d7e00198..c2e9973cc8 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1532,6 +1532,7 @@"com_ui_disabled": "Disabled","com_ui_disabling": "Disabling...","com_ui_dismiss": "Dismiss",+ "com_ui_dock_artifacts": "Dock back to panel","com_ui_done": "Done","com_ui_download": "Download","com_ui_download_artifact": "Download Artifact",@@ -3105,6 +3106,8 @@"com_ui_unarchive": "Unarchive","com_ui_unarchive_conversation": "Unarchive conversation","com_ui_unarchive_error": "Failed to unarchive conversation",+ "com_ui_undock_artifacts": "Open in new window",+ "com_ui_undock_artifacts_blocked": "Your browser blocked the new window. Allow pop-ups for this site and try again.","com_ui_unfavorite": "Remove from favorites","com_ui_unknown": "Unknown","com_ui_unknown_file_type": "Unknown file type",diff --git a/client/src/routes/ChatRoute.tsx b/client/src/routes/ChatRoute.tsxindex 6a3b7f4ee1..99fdab53aa 100644--- a/client/src/routes/ChatRoute.tsx+++ b/client/src/routes/ChatRoute.tsx@@ -383,7 +383,11 @@ export default function ChatRoute() {</div>)}<div hidden={routeState.pending} className={routeState.pending ? 'hidden' : 'contents'}>- <ChatView index={index} project={verifiedChatProjectId ? projectQuery.data : undefined} />+ <ChatView+ index={index}+ project={verifiedChatProjectId ? projectQuery.data : undefined}+ routePending={routeState.pending}+ /></div></ToolCallsMapProvider>);diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 62bc084e08..3c41b6bf39 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -74,6 +74,7 @@ const PARAGRAPHS_REPLY_MARKER = 'E2E_PARAGRAPHS_REPLY';const MERMAID_ARTIFACT_REPLY_MARKER = 'E2E_MERMAID_ARTIFACT_REPLY';const LARGE_MERMAID_ARTIFACT_REPLY_MARKER = 'E2E_LARGE_MERMAID_ARTIFACT_REPLY';const HTML_ARTIFACT_REPLY_MARKER = 'E2E_HTML_ARTIFACT_REPLY';+const TWO_ARTIFACT_REPLY_MARKER = 'E2E_TWO_ARTIFACT_REPLY';const BACKGROUND_DISPATCH_MARKER = 'E2E_BACKGROUND_DISPATCH:';const BACKGROUND_COLLECT_MARKER = 'E2E_BACKGROUND_COLLECT:';const TOOL_APPROVAL_MARKER = 'E2E_TOOL_APPROVAL:';@@ -577,6 +578,22 @@ function replyResponses(text) {};}+ if (text.includes(TWO_ARTIFACT_REPLY_MARKER)) {+ return {+ responses: [+ [+ ':::artifact{identifier="e2e-first" type="text/html" title="E2E First Artifact"}',+ '<h1>First sandbox fixture</h1>',+ ':::',+ '',+ ':::artifact{identifier="e2e-second" type="text/html" title="E2E Second Artifact"}',+ '<h1>Second sandbox fixture</h1>',+ ':::',+ ].join('\n'),+ ],+ };+ }+if (text.includes(MARKDOWN_REPLY_MARKER)) {return {responses: [diff --git a/e2e/specs/mock/scenarios/artifact-edit-refetch.spec.ts b/e2e/specs/mock/scenarios/artifact-edit-refetch.spec.tsnew file mode 100644index 0000000000..f4f63389bb--- /dev/null+++ b/e2e/specs/mock/scenarios/artifact-edit-refetch.spec.ts@@ -0,0 +1,100 @@+import { expect, test } from '@playwright/test';+import type { Page, Response } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ escapeRegExp,+ getAccessToken,+ messagesView,+ requestJson,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * An edit replaces whatever the last save wrote, and until the edited message+ * propagates the editor reads that from its own record of the save. The record+ * stops being the truth once the artifact changes somewhere else: content+ * refetched from another session is newer than every save made here, and+ * rebasing on the local record would have the endpoint refuse every further+ * edit.+ */++const HTML_ARTIFACT = 'E2E HTML Artifact';++/* The phone sheet is modal and its new-chat control lives in the collapsed+ * navigation; the refetch this case needs is reached from the desktop layout. */+test.use({ viewport: { width: 1280, height: 800 } });++type ArtifactSave = { index: number; original: string; updated: string };++const isArtifactSave = (response: Response) =>+ response.request().method() === 'POST' && response.url().includes('/api/messages/artifact/');++async function openCode(page: Page) {+ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();+ await panel.getByRole('radio', { name: 'Code' }).click();+ const editor = panel.locator('#artifacts-code .monaco-editor').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ return { panel, editor };+}++test('an edit saves after another session changed the artifact @scenario:an-edit-after-another-session-changed-the-artifact-saves', async ({+ page,+}) => {+ test.setTimeout(150000);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ const first = await openCode(page);+ await first.editor.click();+ await page.keyboard.press('End');+ const [localSave] = await Promise.all([+ page.waitForResponse(isArtifactSave, { timeout: 20000 }),+ page.keyboard.type('<!-- local-save -->'),+ ]);+ expect(localSave.status()).toBe(200);+ const saved = localSave.request().postDataJSON() as ArtifactSave;+ const messageId = decodeURIComponent(new URL(localSave.url()).pathname.split('/').pop() ?? '');++ /* Another tab edits the same artifact on top of what this one saved. */+ const token = await getAccessToken(page);+ await requestJson(page, {+ path: `/api/messages/artifact/${encodeURIComponent(messageId)}`,+ token,+ method: 'POST',+ body: {+ index: saved.index,+ original: saved.updated,+ updated: `${saved.updated}\n<!-- other-session -->`,+ },+ });++ /* Leaving and coming back refetches the conversation without a reload, so+ * this tab's record of its own save is still there. */+ const conversationPath = new URL(page.url()).pathname;+ await page.getByTestId('new-chat-button').click();+ await expect(page).toHaveURL(/\/c\/new/);+ await page.goBack();+ await expect(page).toHaveURL(new RegExp(escapeRegExp(conversationPath)));++ const second = await openCode(page);+ await expect(second.panel.locator('#artifacts-code')).toContainText('other-session', {+ timeout: 30000,+ });+ await second.editor.click();+ await page.keyboard.press('Control+End');+ const [nextSave] = await Promise.all([+ page.waitForResponse(isArtifactSave, { timeout: 20000 }),+ page.keyboard.type('<!-- after-refetch -->'),+ ]);+ expect(nextSave.status()).toBe(200);+ const next = nextSave.request().postDataJSON() as ArtifactSave;+ expect(next.original).toContain('other-session');+});diff --git a/e2e/specs/mock/scenarios/displaced-artifact-buffer.spec.ts b/e2e/specs/mock/scenarios/displaced-artifact-buffer.spec.tsnew file mode 100644index 0000000000..deb4c2b980--- /dev/null+++ b/e2e/specs/mock/scenarios/displaced-artifact-buffer.spec.ts@@ -0,0 +1,182 @@+import { readFileSync } from 'node:fs';+import { expect, test } from '@playwright/test';+import type { Locator, Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * The editor keeps one active buffer, and it belongs to whichever artifact+ * last wrote it. Editing a second artifact used to evict the first one's+ * unsaved text outright: the selection change had cancelled that edit's+ * debounce, so the overwritten copy was the only place it lived, and coming+ * back to the artifact fell through to its persisted content. A displaced+ * buffer is retained under the artifact it belongs to, so the artifact the+ * user returns to lands on its own unsaved text and sends it.+ */++/* On a phone the pane is a modal sheet: reaching another artifact's trigger+ * means closing it, which ends the pane session, so an edit can only be+ * displaced by another artifact's edit where the pane sits beside the chat. */+test.use({ viewport: { width: 1280, height: 800 } });++const FIRST_ARTIFACT = 'E2E First Artifact';+const SECOND_ARTIFACT = 'E2E Second Artifact';++const artifactTrigger = (page: Page, title: string) =>+ messagesView(page).getByRole('button', {+ name: new RegExp(title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),+ });++test('an edit another artifact displaced is kept for its own @scenario:a-displaced-edit-returns-with-its-artifact', async ({+ page,+}) => {+ test.setTimeout(150000);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_TWO_ARTIFACT_REPLY', { timeout: 60000 });++ /* Edit the first artifact and leave before its debounce has to have fired:+ * whether or not the save went out, the text has to survive. */+ await artifactTrigger(page, FIRST_ARTIFACT).click();+ const first = page.getByRole('region', { name: FIRST_ARTIFACT });+ await expect(first).toBeVisible();+ await first.getByRole('radio', { name: 'Code' }).click();+ const firstEditor = first.locator('#artifacts-code .monaco-editor').first();+ await expect(firstEditor).toBeVisible({ timeout: 30000 });+ await firstEditor.click();+ await page.keyboard.press('End');+ await page.keyboard.type('<!-- displaced-keep -->');+ await expect(first.locator('#artifacts-code')).toContainText('displaced-keep', {+ timeout: 15000,+ });++ /* Editing the second artifact is what displaces the first one's buffer. */+ await artifactTrigger(page, SECOND_ARTIFACT).click();+ const second = page.getByRole('region', { name: SECOND_ARTIFACT });+ await expect(second).toBeVisible();+ await second.getByRole('radio', { name: 'Code' }).click();+ const secondEditor = second.locator('#artifacts-code .monaco-editor').first();+ await expect(secondEditor).toBeVisible({ timeout: 30000 });+ await secondEditor.click();+ await page.keyboard.press('End');+ await page.keyboard.type('<!-- second-edit -->');+ await expect(second.locator('#artifacts-code')).toContainText('second-edit', {+ timeout: 15000,+ });++ /* Back to the first artifact: its own unsaved text, not the persisted+ * content the eviction used to fall through to. */+ await artifactTrigger(page, FIRST_ARTIFACT).click();+ await expect(first).toBeVisible();+ await first.getByRole('radio', { name: 'Code' }).click();+ await expect(first.locator('#artifacts-code')).toContainText('displaced-keep', {+ timeout: 30000,+ });+});++const ARTIFACT_SAVE = '**/api/messages/artifact/**';++/** Leaves an edit on an artifact's code tab and waits until it is on screen. */+async function editArtifact(page: Page, title: string, marker: string): Promise<Locator> {+ await artifactTrigger(page, title).click();+ const panel = page.getByRole('region', { name: title });+ await expect(panel).toBeVisible();+ await panel.getByRole('radio', { name: 'Code' }).click();+ const editor = panel.locator('#artifacts-code .monaco-editor').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await editor.click();+ await page.keyboard.press('End');+ await page.keyboard.type(marker);+ await expect(panel.locator('#artifacts-code')).toContainText(marker, { timeout: 15000 });+ return panel;+}++/** Every save is refused, the way the endpoint answers an edit it cannot apply. */+async function refuseSaves(page: Page) {+ const attempts: string[] = [];+ await page.context().route(ARTIFACT_SAVE, async (route) => {+ const body = route.request().postDataJSON() as { updated?: string } | null;+ attempts.push(body?.updated ?? '');+ await route.fulfill({+ status: 400,+ contentType: 'application/json',+ body: JSON.stringify({ error: 'Original content not found in target artifact' }),+ });+ });+ return attempts;+}++/* The code tab is not the only surface that reads the unsaved text: the+ * download exports it too, and a copy displaced by another artifact's edit is+ * still this artifact's text when the user comes back to it. */+test('a displaced edit is what its artifact exports @scenario:a-displaced-edit-downloads-with-its-artifact', async ({+ page,+}) => {+ test.setTimeout(150000);+ const attempts = await refuseSaves(page);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_TWO_ARTIFACT_REPLY', { timeout: 60000 });++ await editArtifact(page, FIRST_ARTIFACT, '<!-- export-keep -->');+ await expect.poll(() => attempts.length, { timeout: 20000 }).toBeGreaterThan(0);+ await editArtifact(page, SECOND_ARTIFACT, '<!-- export-other -->');++ await artifactTrigger(page, FIRST_ARTIFACT).click();+ const first = page.getByRole('region', { name: FIRST_ARTIFACT });+ await expect(first).toBeVisible();+ const [download] = await Promise.all([+ page.waitForEvent('download'),+ first.getByRole('button', { name: 'Download Artifact' }).click(),+ ]);+ const path = await download.path();+ const exported = readFileSync(path, 'utf8');+ expect(exported).toContain('export-keep');+ expect(exported).not.toContain('export-other');+});++/* A refusal is remembered for the artifact it was given for. A second+ * artifact's refusal must not replace the first one's, or coming back to the+ * first would send the text the endpoint already refused all over again. */+test('each refused edit stays refused when the user returns to it @scenario:a-refused-edit-is-not-resent-on-return', async ({+ page,+}) => {+ test.setTimeout(150000);+ const attempts = await refuseSaves(page);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_TWO_ARTIFACT_REPLY', { timeout: 60000 });++ await editArtifact(page, FIRST_ARTIFACT, '<!-- refused-first -->');+ await expect+ .poll(() => attempts.filter((text) => text.includes('refused-first')).length, {+ timeout: 20000,+ })+ .toBe(1);+ await editArtifact(page, SECOND_ARTIFACT, '<!-- refused-second -->');+ await expect+ .poll(() => attempts.filter((text) => text.includes('refused-second')).length, {+ timeout: 20000,+ })+ .toBe(1);++ await artifactTrigger(page, FIRST_ARTIFACT).click();+ const first = page.getByRole('region', { name: FIRST_ARTIFACT });+ await expect(first).toBeVisible();+ await first.getByRole('radio', { name: 'Code' }).click();+ await expect(first.locator('#artifacts-code')).toContainText('refused-first', {+ timeout: 30000,+ });++ /* Waits out the resend a return used to trigger; nothing else settles it. */+ await page.waitForTimeout(3000);+ expect(attempts.filter((text) => text.includes('refused-first'))).toHaveLength(1);+});diff --git a/e2e/specs/mock/scenarios/shared-undocked-artifacts.spec.ts b/e2e/specs/mock/scenarios/shared-undocked-artifacts.spec.tsnew file mode 100644index 0000000000..5574977bc8--- /dev/null+++ b/e2e/specs/mock/scenarios/shared-undocked-artifacts.spec.ts@@ -0,0 +1,109 @@+import { expect, test } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * A shared conversation renders the artifacts pane through its own host+ * (`ShareArtifactsContainer`), which resolves the undock capability from the+ * shared-link config rather than the viewer's startup config and bounds the+ * artifact registry to the shared conversation it is showing. A reader of a+ * shared link therefore gets the same pane, in its own window, without an+ * account.+ *+ * The reader is a browser context of its own, with none of the owner's+ * storage or session: that is who opens a shared link. The pane arrives open,+ * because a shared snapshot's artifact is one the host offers straight away.+ */++const UNDOCK = 'Open in new window';+const DOCK = 'Dock back to panel';+const HTML_ARTIFACT = 'E2E HTML Artifact';+const UNDOCKED_PANE = '#undocked-artifacts-root #artifact-viewer';+const READER_VIEWPORT = { width: 1280, height: 800 };++/** The undock control is desktop-only: it is hidden below 868px. */+test.use({ viewport: READER_VIEWPORT });++test('a shared link can undock its artifacts pane @scenario:a-shared-link-can-undock-its-artifacts-pane', async ({+ page,+ browser,+ baseURL,+}) => {+ test.setTimeout(180000);++ if (typeof baseURL !== 'string') {+ throw new Error('baseURL must be configured for shared-link mock e2e tests');+ }++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ await expect(page).toHaveURL(/\/c\/(?!new)[0-9a-fA-F-]{36}$/);+ const conversationId = new URL(page.url()).pathname.split('/').pop();+ if (!conversationId) {+ throw new Error(`Could not parse conversation id from ${page.url()}`);+ }++ await page.getByRole('button', { name: 'Export/Share' }).click();+ await page.getByTestId('share-conversation-menu-item').click();+ const shareDialog = page.getByRole('dialog', { name: 'Share link to chat' });+ await expect(shareDialog).toBeVisible();++ const [shareResponse] = await Promise.all([+ page.waitForResponse(+ (res) =>+ res.request().method() === 'POST' &&+ res.url().includes(`/api/share/${conversationId}`) &&+ res.status() === 200,+ { timeout: 30000 },+ ),+ page.getByRole('button', { name: 'Create a shared link' }).click(),+ ]);+ expect(shareResponse.ok()).toBeTruthy();++ /** The share URL is rendered into a read-only <input>, so read its value. */+ const sharedLinkInput = page.getByTestId('shared-link-url');+ await expect(sharedLinkInput).toHaveValue(/\/share\//);+ const sharedLinkUrl = (await sharedLinkInput.inputValue()).trim();++ const readerContext = await browser.newContext({ viewport: READER_VIEWPORT });+ try {+ const reader = await readerContext.newPage();+ await reader.goto(new URL(sharedLinkUrl, baseURL).toString(), { timeout: 20000 });++ const panel = reader.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible({ timeout: 20000 });++ const [popup] = await Promise.all([+ reader.waitForEvent('popup'),+ panel.getByRole('button', { name: UNDOCK }).click(),+ ]);+ await expect(popup.locator(UNDOCKED_PANE)).toBeVisible({ timeout: 20000 });+ await expect(popup.getByRole('region', { name: HTML_ARTIFACT })).toBeVisible();+ /* The shared transcript gets its column back, and nothing of the pane is+ * left behind in the page the reader came from. */+ await expect(reader.locator('#artifact-viewer')).toHaveCount(0);++ /* Docking closes the window the click was made in, so the click itself+ * can resolve against a page that is already gone; what matters is where+ * the pane ends up. */+ const closed = popup.waitForEvent('close').catch(() => undefined);+ await popup+ .getByRole('button', { name: DOCK })+ .click()+ .catch(() => undefined);+ await closed;++ await expect(reader.getByRole('region', { name: HTML_ARTIFACT })).toBeVisible({+ timeout: 20000,+ });+ await expect(reader.getByRole('button', { name: UNDOCK })).toBeVisible();+ } finally {+ await readerContext.close();+ }+});diff --git a/e2e/specs/mock/scenarios/undocked-artifact-generation.spec.ts b/e2e/specs/mock/scenarios/undocked-artifact-generation.spec.tsnew file mode 100644index 0000000000..2dfdbb32fd--- /dev/null+++ b/e2e/specs/mock/scenarios/undocked-artifact-generation.spec.ts@@ -0,0 +1,79 @@+import { expect, test } from '@playwright/test';+import type { Response } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ isAgentsStream,+ messagesView,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * A response makes the editor read-only. An edit typed just before one starts+ * has not been saved yet, and when the pane changes hosts during the response+ * that edit is inherited by an editor that cannot save it. It has to wait for+ * editing to come back and be saved then, and stay on screen, instead of+ * giving way to the persisted content.+ */++const UNDOCK = 'Open in new window';+const HTML_ARTIFACT = 'E2E HTML Artifact';+const UNDOCKED_PANE = '#undocked-artifacts-root #artifact-viewer';++const isArtifactSave = (response: Response) =>+ response.request().method() === 'POST' && response.url().includes('/api/messages/artifact/');++/** The undock control is desktop-only: it is hidden below 868px. */+test.use({ viewport: { width: 1280, height: 800 } });++test('an edit carried through a response is saved once it ends @scenario:an-edit-carried-through-a-response-saves-after-it', async ({+ page,+}) => {+ test.setTimeout(150000);++ const saves: string[] = [];+ page.on('request', (request) => {+ if (request.method() === 'POST' && request.url().includes('/api/messages/artifact/')) {+ saves.push((request.postDataJSON() as { updated?: string } | null)?.updated ?? '');+ }+ });++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();+ await panel.getByRole('radio', { name: 'Code' }).click();+ const editor = panel.locator('#artifacts-code .monaco-editor').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await editor.click();+ await page.keyboard.press('End');++ /* The response has to start inside the editor's debounce, so the edit is+ * still unsaved when the editor turns read-only. */+ await page.keyboard.type('<!-- carried-edit -->');+ const input = page.getByRole('textbox', { name: 'Message input' });+ await input.fill('E2E_SLOW_REPLY:carried');+ await Promise.all([+ page.waitForResponse(isAgentsStream, { timeout: 30000 }),+ input.press('Enter'),+ ]);+ expect(saves).toHaveLength(0);++ const [popup] = await Promise.all([+ page.waitForEvent('popup'),+ panel.getByRole('button', { name: UNDOCK }).click(),+ ]);+ const pane = popup.locator(UNDOCKED_PANE);+ await expect(pane).toBeVisible({ timeout: 20000 });++ const saved = await page.waitForResponse(isArtifactSave, { timeout: 60000 });+ expect(saved.status()).toBe(200);+ expect((saved.request().postDataJSON() as { updated: string }).updated).toContain('carried-edit');+ await expect(pane.locator('#artifacts-code')).toContainText('carried-edit', { timeout: 30000 });+});diff --git a/e2e/specs/mock/scenarios/undocked-artifact-save-rejection.spec.ts b/e2e/specs/mock/scenarios/undocked-artifact-save-rejection.spec.tsnew file mode 100644index 0000000000..6bbac9230e--- /dev/null+++ b/e2e/specs/mock/scenarios/undocked-artifact-save-rejection.spec.ts@@ -0,0 +1,81 @@+import { expect, test } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * The artifact editor's buffer outlives the pane, because moving the pane to+ * another host remounts it. So does the knowledge that the server rejected a+ * particular text: an edit the endpoint answered with 400 is deterministic, and+ * re-sending it because the user undocked the pane spends a request on a+ * failure that has already been reported and cannot succeed on its own.+ */++const UNDOCK = 'Open in new window';+const HTML_ARTIFACT = 'E2E HTML Artifact';+const UNDOCKED_PANE = '#undocked-artifacts-root #artifact-viewer';+const ARTIFACT_SAVE = '**/api/messages/artifact/**';++/** The undock control is desktop-only: it is hidden below 868px. */+test.use({ viewport: { width: 1280, height: 800 } });++test('an edit the server rejected is not re-sent when the pane changes hosts @scenario:a-rejected-edit-is-not-resent-when-the-pane-changes-hosts', async ({+ page,+}) => {+ test.setTimeout(150000);++ /* Routed on the context: the pane renders into its own window but its+ * requests are issued by the tab that owns the React tree, and after the+ * move the click that triggers them happens in the popup. */+ let saveAttempts = 0;+ await page.context().route(ARTIFACT_SAVE, async (route) => {+ saveAttempts += 1;+ await route.fulfill({+ status: 400,+ contentType: 'application/json',+ body: JSON.stringify({ message: 'Original content not found' }),+ });+ });++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();++ await panel.getByRole('radio', { name: 'Code' }).click();+ const editor = panel.locator('#artifacts-code .monaco-editor').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await editor.click();+ await page.keyboard.press('End');+ await page.keyboard.type('<!-- rejected-edit -->');++ /* The editor debounces, so the rejection is what settles, not the keystroke. */+ await expect.poll(() => saveAttempts, { timeout: 20000 }).toBeGreaterThan(0);+ const attemptsBeforeMove = saveAttempts;++ const [popup] = await Promise.all([+ page.waitForEvent('popup'),+ panel.getByRole('button', { name: UNDOCK }).click(),+ ]);+ await expect(popup.locator(UNDOCKED_PANE)).toBeVisible({ timeout: 20000 });++ /* The text is still the user's to keep editing — it travels with the pane. */+ await expect(popup.locator(`${UNDOCKED_PANE} #artifacts-code`)).toContainText('rejected-edit', {+ timeout: 30000,+ });++ /* What must not happen is the app deciding on its own to send it again. The+ * window is settled by the assertion above; this waits out the drain that+ * runs once the save pipeline reports idle. */+ await page.waitForTimeout(3000);+ expect(saveAttempts).toBe(attemptsBeforeMove);+});diff --git a/e2e/specs/mock/scenarios/undocked-artifacts-blocked-popup.spec.ts b/e2e/specs/mock/scenarios/undocked-artifacts-blocked-popup.spec.tsnew file mode 100644index 0000000000..c3e21796c3--- /dev/null+++ b/e2e/specs/mock/scenarios/undocked-artifacts-blocked-popup.spec.ts@@ -0,0 +1,57 @@+import { expect, test } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ selectMockEndpoint,+ sendMessage,+} from '../helpers';++/**+ * Popup permission belongs to the browser, and a blocked `window.open` returns+ * null rather than throwing. The pane has to stay where it is and say what+ * happened: a control that silently does nothing reads as a broken feature,+ * and a pane that half-moves would leave the artifact nowhere.+ */++const UNDOCK = 'Open in new window';+const HTML_ARTIFACT = 'E2E HTML Artifact';+const BLOCKED_NOTICE =+ 'Your browser blocked the new window. Allow pop-ups for this site and try again.';++/** The undock control is desktop-only: it is hidden below 868px. */+test.use({ viewport: { width: 1280, height: 800 } });++test('a blocked popup keeps the pane docked and says why @scenario:a-blocked-popup-keeps-the-pane-docked', async ({+ page,+}) => {+ test.setTimeout(90000);++ /* What a popup blocker looks like to the page: activation or not, the call+ * hands back null. Installed before the app loads so the pane never sees a+ * window it could keep. */+ await page.addInitScript(() => {+ window.open = () => null;+ });++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ const response = await sendMessage(page, 'E2E_HTML_ARTIFACT_REPLY');+ expect(response.ok()).toBeTruthy();++ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();++ await panel.getByRole('button', { name: UNDOCK }).click();++ /* The notice is both shown and announced, so the same text is in the toast+ * and in the live region — either one proves the user was told. */+ await expect(page.getByText(BLOCKED_NOTICE).first()).toBeVisible({ timeout: 15000 });+ /* Still here, still showing the artifact, and still offering the move. */+ await expect(panel).toBeVisible();+ await expect(panel.getByRole('button', { name: UNDOCK })).toBeVisible();+ await expect(page.locator('#undocked-artifacts-root')).toHaveCount(0);+});diff --git a/e2e/specs/mock/scenarios/undocked-artifacts.spec.ts b/e2e/specs/mock/scenarios/undocked-artifacts.spec.tsnew file mode 100644index 0000000000..530f3184c5--- /dev/null+++ b/e2e/specs/mock/scenarios/undocked-artifacts.spec.ts@@ -0,0 +1,353 @@+import { expect, test } from '@playwright/test';+import type { Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ selectMockEndpoint,+ sendMessage,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * The artifacts pane can leave the side panel for a window of its own. The pane+ * stays in this tab's React tree and is portaled into that window, so these+ * scenarios are about what survives the move: the artifact itself, its styling,+ * its preview frame, its menus, and unsaved editor text.+ *+ * There is deliberately no scenario for a browser that denies Web Storage. The+ * pane's own fallback to default bounds is covered where it can be observed, in+ * `client/src/components/Artifacts/__tests__/undockedWindow.spec.ts`; denying+ * storage in the browser takes the whole app into its error boundary before any+ * of this is reachable, so asserting it here would test a capability the shell+ * does not have.+ */++const UNDOCK = 'Open in new window';+const DOCK = 'Dock back to panel';+const HTML_ARTIFACT = 'E2E HTML Artifact';+const UNDOCKED_PANE = '#undocked-artifacts-root #artifact-viewer';+/**+ * The trigger row's accessible name carries its format badge and whether+ * opening it renders a preview, alongside the title and the action — so it is+ * matched on the title rather than spelled out here.+ */+const artifactTrigger = (page: Page, title: string) =>+ messagesView(page).getByRole('button', {+ name: new RegExp(title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),+ });++async function openHtmlArtifact(page: Page) {+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ /* Opened while the reply is still finalizing, the pane follows the stream+ * onto the code tab; these cases start from a settled reply. */+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ await artifactTrigger(page, HTML_ARTIFACT).click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();+ return panel;+}++async function undock(page: Page) {+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ const [popup] = await Promise.all([+ page.waitForEvent('popup'),+ panel.getByRole('button', { name: UNDOCK }).click(),+ ]);+ await expect(popup.locator(UNDOCKED_PANE)).toBeVisible({ timeout: 20000 });+ return popup;+}++/** The undock control is desktop-only: it is hidden below 868px. */+test.use({ viewport: { width: 1280, height: 800 } });++test.describe('undocked artifacts pane', () => {+ test('the pane moves into a window of its own @scenario:artifacts-pane-moves-into-its-own-window', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);++ const popup = await undock(page);++ await expect(popup.getByRole('region', { name: HTML_ARTIFACT })).toBeVisible();+ /* The conversation gets its column back: nothing of the pane is left here. */+ await expect(page.locator('#artifact-viewer')).toHaveCount(0);+ await expect(page.getByRole('region', { name: HTML_ARTIFACT })).toHaveCount(0);+ });++ test('the artifact renders in the window with the app styling @scenario:undocked-pane-renders-the-artifact-preview', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);++ const popup = await undock(page);+ const pane = popup.locator(UNDOCKED_PANE);++ /* A portal carries nodes, not the document that styled them: an unstyled+ * pane would render transparent and collapsed. The mirrored sheet is a+ * fetch, so the painted canvas is what settles, not what renders first. */+ await expect+ .poll(+ () =>+ pane.evaluate(+ (node) => node.ownerDocument.defaultView?.getComputedStyle(node).backgroundColor ?? '',+ ),+ { timeout: 15000 },+ )+ .not.toBe('rgba(0, 0, 0, 0)');+ const paneBox = await pane.boundingBox();+ expect(paneBox).not.toBeNull();+ expect(paneBox!.height).toBeGreaterThan(200);++ /* The preview lives in the window too, in its own frame. The runtime+ * bundler compiles it there, which on a loaded machine takes a while. */+ await expect(pane.locator('iframe')).toHaveCount(1, { timeout: 30000 });+ await expect(popup.getByRole('button', { name: 'Refresh' })).toBeVisible();+ });++ test('docking back returns the pane to the side panel @scenario:undocked-pane-returns-to-the-side-panel', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);+ const popup = await undock(page);++ await popup.getByRole('button', { name: DOCK }).click();++ await expect(page.getByRole('region', { name: HTML_ARTIFACT })).toBeVisible({ timeout: 20000 });+ await expect(page.getByRole('button', { name: UNDOCK })).toBeVisible();+ await expect.poll(() => popup.isClosed(), { timeout: 10000 }).toBe(true);+ });++ test('closing the window brings the pane home @scenario:closing-the-undocked-window-returns-the-pane', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);+ const popup = await undock(page);++ await popup.close();++ await expect(page.getByRole('region', { name: HTML_ARTIFACT })).toBeVisible({ timeout: 20000 });+ await expect(page.getByRole('button', { name: UNDOCK })).toBeVisible();+ });++ test('docking hands focus to the control that replaces it @scenario:docking-returns-focus-to-the-pane-control', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);+ const popup = await undock(page);++ /* Keyboard path: the button pressed in the window disappears with it, so+ * the press resolves against a page that is already gone. */+ const dockButton = popup.getByRole('button', { name: DOCK });+ await dockButton.focus();+ const closed = popup.waitForEvent('close');+ await popup.keyboard.press('Enter').catch(() => undefined);+ await closed;++ const undockButton = page.getByRole('button', { name: UNDOCK });+ await expect(undockButton).toBeVisible({ timeout: 20000 });+ await expect(undockButton).toBeFocused();+ });++ test('undocking hands focus to the pane in its new window @scenario:undocking-moves-focus-into-the-window', async ({+ page,+ }) => {+ test.setTimeout(90000);+ const panel = await openHtmlArtifact(page);++ /* Keyboard path: the control pressed here disappears with the docked+ * toolbar, so focus has to follow the pane rather than stay on an empty+ * document in the window that just opened. */+ const undockButton = panel.getByRole('button', { name: UNDOCK });+ await undockButton.focus();+ const [popup] = await Promise.all([page.waitForEvent('popup'), page.keyboard.press('Enter')]);++ await expect(popup.locator(UNDOCKED_PANE)).toBeVisible({ timeout: 20000 });+ await expect(popup.getByRole('button', { name: DOCK })).toBeFocused();+ });++ test('unsaved editor text moves with the pane @scenario:unsaved-artifact-edits-survive-undocking', async ({+ page,+ }) => {+ test.setTimeout(120000);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });++ await artifactTrigger(page, HTML_ARTIFACT).click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible();++ await panel.getByRole('radio', { name: 'Code' }).click();+ const editor = panel.locator('#artifacts-code .monaco-editor').first();+ await expect(editor).toBeVisible({ timeout: 30000 });+ await editor.click();+ await page.keyboard.press('End');+ await page.keyboard.type('<!-- undock-edit -->');+ await expect(panel.locator('#artifacts-code')).toContainText('undock-edit', {+ timeout: 15000,+ });++ const popup = await undock(page);++ /* Landing back on the preview would read as the edit having been lost.+ * Polled, because a tab reset lands a frame after the move and a+ * first-match assertion would accept the frame before it. */+ await expect+ .poll(async () => popup.getByRole('radio', { name: 'Code' }).getAttribute('aria-checked'), {+ timeout: 10000,+ })+ .toBe('true');+ await expect(popup.locator(`${UNDOCKED_PANE} #artifacts-code`)).toBeVisible({ timeout: 30000 });+ await expect(popup.locator(`${UNDOCKED_PANE} #artifacts-code`)).toContainText('undock-edit', {+ timeout: 30000,+ });+ });++ test('pane menus open in the window that owns them @scenario:undocked-pane-menus-open-in-its-own-window', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ const response = await sendMessage(page, 'E2E_MERMAID_ARTIFACT_REPLY');+ expect(response.ok()).toBeTruthy();++ const messages = messagesView(page);+ await expect(messages.getByRole('img', { name: 'Mermaid diagram' })).toBeVisible();+ await messages.getByRole('button', { name: 'Open as artifact', exact: true }).click();++ const panel = page.getByRole('region', { name: 'Mermaid diagram' });+ await expect(panel.getByRole('img', { name: 'Mermaid diagram' })).toBeVisible();++ const [popup] = await Promise.all([+ page.waitForEvent('popup'),+ panel.getByRole('button', { name: UNDOCK }).click(),+ ]);+ const pane = popup.locator(UNDOCKED_PANE);+ await expect(pane).toBeVisible({ timeout: 20000 });+ await expect(pane.getByRole('img', { name: 'Mermaid diagram' })).toBeVisible({+ timeout: 20000,+ });++ await popup.getByRole('button', { name: 'Export diagram' }).click();++ /* Radix portals default to the host document's body; the menu has to open+ * where the user clicked instead. */+ await expect(popup.getByRole('menuitem', { name: 'Export as SVG', exact: true })).toBeVisible();+ await expect(page.getByRole('menuitem', { name: 'Export as SVG', exact: true })).toHaveCount(0);+ });++ test('a failure raised in the window is reported there @scenario:undocked-pane-reports-failures-in-its-own-window', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await openHtmlArtifact(page);+ const popup = await undock(page);++ /* Take both clipboard paths away inside the window, which is what a+ * non-secure context with a refused selection copy looks like. */+ await popup.evaluate(() => {+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText: () => Promise.reject(new Error('denied')) },+ });+ document.execCommand = () => false;+ });++ await popup.getByRole('button', { name: 'Copy' }).click();++ /* The app's toast viewport lives in the chat tab, which the user is not+ * looking at: the notice has to appear in the window they are. */+ await expect(popup.getByText('Failed to copy to clipboard')).toBeVisible({ timeout: 15000 });+ });++ /* The capability is a deployment choice, and a viewer must not be able to+ * act on it before the deployment has answered. */+ test('a deployment can keep the pane docked @scenario:a-deployment-can-turn-undocking-off', async ({+ page,+ }) => {+ test.setTimeout(90000);+ await page.route('**/api/config', async (route) => {+ const response = await route.fetch();+ const config = await response.json();+ await route.fulfill({+ response,+ json: { ...config, interface: { ...config.interface, artifactUndocking: false } },+ });+ });++ const panel = await openHtmlArtifact(page);++ await expect(panel.getByRole('button', { name: 'Copy' })).toBeVisible();+ await expect(panel.getByRole('button', { name: UNDOCK })).toHaveCount(0);+ });++ /* The tab is pane state, and the pane is a new instance in every host. A+ * reset driven by the instance rather than by the artifact sends the user+ * back to Preview on both transitions, which reads as their code being gone.+ * Asserting the settled tab matters: the reset lands a frame after the move,+ * so a first-match assertion can pass on the frame before it. */+ test('the pane keeps the code tab across both host changes @scenario:the-code-tab-survives-a-host-change', async ({+ page,+ }) => {+ test.setTimeout(120000);+ const panel = await openHtmlArtifact(page);++ await panel.getByRole('radio', { name: 'Code' }).click();+ await expect(panel.locator('#artifacts-code')).toBeVisible({ timeout: 30000 });++ const popup = await undock(page);++ const popupCodeTab = popup.getByRole('radio', { name: 'Code' });+ await expect(popupCodeTab).toBeVisible({ timeout: 20000 });+ await expect+ .poll(async () => popupCodeTab.getAttribute('aria-checked'), { timeout: 10000 })+ .toBe('true');+ /* Visible, not merely present: the code pane stays mounted when the tab+ * changes, so presence alone would not show which tab is on screen. */+ await expect(popup.locator(`${UNDOCKED_PANE} #artifacts-code`)).toBeVisible({+ timeout: 30000,+ });++ await popup.getByRole('button', { name: DOCK }).click();++ const docked = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(docked).toBeVisible({ timeout: 20000 });+ const dockedCodeTab = docked.getByRole('radio', { name: 'Code' });+ await expect+ .poll(async () => dockedCodeTab.getAttribute('aria-checked'), { timeout: 10000 })+ .toBe('true');+ await expect(docked.locator('#artifacts-code')).toBeVisible({ timeout: 30000 });+ });+});++test.describe('artifacts sheet on a phone', () => {+ test.use({ viewport: { width: 390, height: 844 } });++ test('the sheet offers no undock action @scenario:mobile-artifacts-sheet-offers-no-undock-action', async ({+ page,+ }) => {+ test.setTimeout(90000);+ expect(page.viewportSize()?.width ?? 0).toBeLessThan(868);++ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ const response = await sendMessage(page, 'E2E_HTML_ARTIFACT_REPLY');+ expect(response.ok()).toBeTruthy();++ await artifactTrigger(page, HTML_ARTIFACT).click();++ const sheet = page.getByRole('dialog', { name: HTML_ARTIFACT });+ await expect(sheet).toBeVisible();+ await expect(sheet.getByRole('button', { name: UNDOCK })).toHaveCount(0);+ await expect(sheet.getByRole('button', { name: 'Close' })).toBeVisible();+ });+});diff --git a/librechat.example.yaml b/librechat.example.yamlindex 338567613f..ddd55f2c1b 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -238,6 +238,9 @@ interface:public: falsebookmarks: truemultiConvo: true+ # Allow the artifacts pane to be moved into its own browser window+ # (desktop only; the mobile sheet is unaffected). Default: true.+ artifactUndocking: trueagents:use: truecreate: truediff --git a/packages/api/src/shared-links/config.ts b/packages/api/src/shared-links/config.tsindex 987ae5efec..f65e81d963 100644--- a/packages/api/src/shared-links/config.ts+++ b/packages/api/src/shared-links/config.ts@@ -103,16 +103,25 @@ export function buildSharedLinkStartupPayload(payload.customFooter = env.CUSTOM_FOOTER;}- const { privacyPolicy, termsOfService, codeHighlightThrottleMs } =+ const { privacyPolicy, termsOfService, codeHighlightThrottleMs, artifactUndocking } =appConfig?.interfaceConfig ?? {};const parsedTheme = deploymentThemeSchema.safeParse(appConfig?.interfaceConfig?.theme);const theme = parsedTheme.success ? parsedTheme.data : undefined;- if (privacyPolicy || termsOfService || codeHighlightThrottleMs != null || theme) {+ /* A shared conversation shows the same artifacts pane, so it needs the same+ * answer about opening that pane in its own window. */+ if (+ privacyPolicy ||+ termsOfService ||+ codeHighlightThrottleMs != null ||+ theme ||+ artifactUndocking === false+ ) {payload.interface = {...(codeHighlightThrottleMs != null ? { codeHighlightThrottleMs } : {}),...(privacyPolicy ? { privacyPolicy } : {}),...(termsOfService ? { termsOfService } : {}),...(theme ? { theme } : {}),+ ...(artifactUndocking === false ? { artifactUndocking } : {}),};}diff --git a/packages/client/src/components/Toast.tsx b/packages/client/src/components/Toast.tsxindex dbcfd948b3..8bdd1f9d36 100644--- a/packages/client/src/components/Toast.tsx+++ b/packages/client/src/components/Toast.tsx@@ -1,8 +1,31 @@+import * as React from 'react';import { X } from 'lucide-react';import { JSX } from 'react/jsx-runtime';import * as RadixToast from '@radix-ui/react-toast';import { NotificationSeverity } from '~/common';import { useToast, useLocalize } from '~/hooks';+import { cn } from '~/utils';++/**+ * Shared by the app shell and undocked artifacts window so toast viewport+ * positioning stays in sync between both hosts.+ */+const ToastViewport: React.ForwardRefExoticComponent<+ RadixToast.ToastViewportProps & React.RefAttributes<HTMLOListElement>+> = React.forwardRef<+ React.ElementRef<typeof RadixToast.Viewport>,+ React.ComponentPropsWithoutRef<typeof RadixToast.Viewport>+>(({ className, ...props }, ref) => (+ <RadixToast.Viewport+ ref={ref}+ className={cn(+ 'pointer-events-none fixed inset-x-0 top-0 z-[1000] mx-auto my-2 flex max-w-[560px] flex-col items-stretch justify-start',+ className,+ )}+ {...props}+ />+));+ToastViewport.displayName = RadixToast.Viewport.displayName;export function Toast(): JSX.Element {const { toast, onOpenChange } = useToast();@@ -69,3 +92,4 @@ export function Toast(): JSX.Element {</RadixToast.Root>);}+export { ToastViewport };diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex a6eb88a251..8cb0a15cca 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -2431,6 +2431,10 @@ export const interfaceSchema = zwebSearch: z.boolean().optional(),contextUsage: z.boolean().optional(),contextCost: z.boolean().optional(),+ /** Opening the artifacts pane in its own browser window. Enabled by+ * default; a deployment that cannot use popups can turn it off and keep+ * the docked pane. */+ artifactUndocking: z.boolean().optional(),feedback: z.boolean().optional(),currency: z.object({@@ -2620,6 +2624,7 @@ export const interfaceSchema = zwebSearch: true,contextUsage: true,contextCost: false,+ artifactUndocking: true,feedback: true,peoplePicker: {users: true,@@ -2931,7 +2936,7 @@ export type TStartupConfig = {export type TSharedLinkStartupInterface = Pick<Partial<TInterfaceConfig>,- 'privacyPolicy' | 'termsOfService' | 'codeHighlightThrottleMs' | 'theme'+ 'privacyPolicy' | 'termsOfService' | 'codeHighlightThrottleMs' | 'theme' | 'artifactUndocking'>;export type TSharedLinkStartupConfig = Pick<TStartupConfig, 'appTitle'> &diff --git a/packages/data-provider/src/keys.ts b/packages/data-provider/src/keys.tsindex 3d4c9b563d..f81b97e5e7 100644--- a/packages/data-provider/src/keys.ts+++ b/packages/data-provider/src/keys.ts@@ -172,6 +172,9 @@ export enum MutationKeys {updateSkillNode = 'updateSkillNode',deleteSkillNode = 'deleteSkillNode',updateSkillNodeContent = 'updateSkillNodeContent',+ /** Artifact code save, keyed so the editor pane can see a save started by+ * another instance of itself — the pane is remounted when it changes hosts. */+ editArtifact = 'editArtifact',convoPin = 'convoPin',archiveAllConversations = 'archiveAllConversations',createSchedule = 'createSchedule',diff --git a/packages/data-schemas/src/app/interface.spec.ts b/packages/data-schemas/src/app/interface.spec.tsindex 78760b0b99..6f00713121 100644--- a/packages/data-schemas/src/app/interface.spec.ts+++ b/packages/data-schemas/src/app/interface.spec.ts@@ -164,6 +164,30 @@ describe('loadDefaultInterface', () => {expect(interfaceConfig?.buildInfo).toBe(true);});+ it('carries a disabled artifact undocking flag to the clients', async () => {+ const config: Partial<TCustomConfig> = {+ interface: {+ artifactUndocking: false,+ },+ };++ const interfaceConfig = await loadDefaultInterface({+ config,+ configDefaults: getConfigDefaults(),+ });++ expect(interfaceConfig?.artifactUndocking).toBe(false);+ });++ it('uses the schema default for artifact undocking when not configured', async () => {+ const interfaceConfig = await loadDefaultInterface({+ config: {},+ configDefaults: getConfigDefaults(),+ });++ expect(interfaceConfig?.artifactUndocking).toBe(true);+ });+it('preserves enabled build info config', async () => {const config: Partial<TCustomConfig> = {interface: {diff --git a/packages/data-schemas/src/app/interface.ts b/packages/data-schemas/src/app/interface.tsindex fb14fe7f8a..96739f3cd4 100644--- a/packages/data-schemas/src/app/interface.ts+++ b/packages/data-schemas/src/app/interface.ts@@ -44,6 +44,7 @@ export async function loadDefaultInterface({autoSubmitFromUrl: interfaceConfig?.autoSubmitFromUrl ?? defaults.autoSubmitFromUrl,buildInfo: interfaceConfig?.buildInfo ?? defaults.buildInfo,contextUsage: interfaceConfig?.contextUsage ?? defaults.contextUsage,+ artifactUndocking: interfaceConfig?.artifactUndocking ?? defaults.artifactUndocking,contextCost: interfaceConfig?.contextCost ?? defaults.contextCost,feedback: interfaceConfig?.feedback ?? defaults.feedback,currency: interfaceConfig?.currency ?? defaults.currency,