diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/find/use-markdown-find.ts b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/find/use-markdown-find.ts index d3a103a69c1..1c541ffb9a4 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/find/use-markdown-find.ts +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/find/use-markdown-find.ts @@ -86,9 +86,9 @@ export function useMarkdownFind({ */ const revealActiveMatch = useCallback(() => { requestAnimationFrame(() => { - editorRef.current?.view.dom - .querySelector(`.${ACTIVE_MATCH_CLASS}`) - ?.scrollIntoView({ block: 'center' }) + const current = editorRef.current + if (!current || current.isDestroyed) return + current.view.dom.querySelector(`.${ACTIVE_MATCH_CLASS}`)?.scrollIntoView({ block: 'center' }) }) }, []) @@ -99,7 +99,7 @@ export function useMarkdownFind({ */ const syncTally = useCallback(() => { const current = editorRef.current - if (!current) return + if (!current || current.isDestroyed) return const { matches, activeIndex, truncated } = getFindTally(current.state) setTally((previous) => previous.count === matches.length && @@ -116,7 +116,7 @@ export function useMarkdownFind({ * on each of those. Not subscribed while the bar is closed, so typing costs nothing then. */ useEffect(() => { - if (!editor || !isOpen) return + if (!editor || editor.isDestroyed || !isOpen) return syncTally() editor.on('transaction', syncTally) return () => { @@ -132,7 +132,7 @@ export function useMarkdownFind({ const queryRef = useRef(query) queryRef.current = query useEffect(() => { - if (!editor || queryRef.current.length === 0) return + if (!editor || editor.isDestroyed || queryRef.current.length === 0) return setFindQuery(editor, queryRef.current) }, [editor]) @@ -140,7 +140,7 @@ export function useMarkdownFind({ (next: string) => { setQueryState(next) const current = editorRef.current - if (!current) return + if (!current || current.isDestroyed) return setFindQuery(current, next) revealActiveMatch() }, @@ -150,7 +150,7 @@ export function useMarkdownFind({ const step = useCallback( (delta: number) => { const current = editorRef.current - if (!current) return + if (!current || current.isDestroyed) return stepFindMatch(current, delta) revealActiveMatch() }, @@ -162,13 +162,18 @@ export function useMarkdownFind({ const replaceCurrent = useCallback(() => { const current = editorRef.current - if (!current || !replaceActiveFindMatch(current, replacement, warnReplacementLimit)) return + if ( + !current || + current.isDestroyed || + !replaceActiveFindMatch(current, replacement, warnReplacementLimit) + ) + return revealActiveMatch() }, [replacement, revealActiveMatch]) const replaceAll = useCallback(() => { const current = editorRef.current - if (!current) return + if (!current || current.isDestroyed) return replaceAllFindMatches(current, replacement, warnReplacementLimit) }, [replacement]) @@ -179,7 +184,7 @@ export function useMarkdownFind({ setReplacement('') setTally(EMPTY_TALLY) const current = editorRef.current - if (current) setFindQuery(current, '') + if (current && !current.isDestroyed) setFindQuery(current, '') requestAnimationFrame(() => { if (current && !current.isDestroyed) current.commands.focus() }) diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/bubble-menu.tsx b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/bubble-menu.tsx index 3e863ef2d62..8a255dd4f58 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/bubble-menu.tsx +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/bubble-menu.tsx @@ -221,6 +221,7 @@ export function EditorBubbleMenu({ * preventing a lost pointer release from suppressing later keyboard selections. */ useEffect(() => { + if (editor.isDestroyed) return const dom = editor.view.dom const onPointerDown = () => { isPointerDownRef.current = true @@ -255,6 +256,7 @@ export function EditorBubbleMenu({ } useEffect(() => { + if (editor.isDestroyed) return const dom = editor.view.dom const openLinkOnShortcut = (event: KeyboardEvent) => { if (!editor.isEditable) return diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/link-hover-card.tsx b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/link-hover-card.tsx index a135a173099..bedbbc9a124 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/link-hover-card.tsx +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/link-hover-card.tsx @@ -95,6 +95,8 @@ export function LinkHoverCard({ editor }: LinkHoverCardProps) { }, [cancelHide, isEditing]) useEffect(() => { + // Cached routes reconnect child effects before useEditor replaces the disposed editor. + if (editor.isDestroyed) return const dom = editor.view.dom const onOver = (event: Event) => { if ( diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/suggestion-list.tsx b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/suggestion-list.tsx index f196bf34975..6a50196e266 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/suggestion-list.tsx +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/suggestion-list.tsx @@ -64,6 +64,7 @@ export function SuggestionList({ const activeOptionId = hasOptions ? `${optionIdPrefix}-${activeIndex}` : null useEffect(() => { + if (editor.isDestroyed) return const dom = editor.view.dom dom.setAttribute('aria-haspopup', 'listbox') dom.setAttribute('aria-expanded', 'true') @@ -76,6 +77,7 @@ export function SuggestionList({ }, [editor]) useEffect(() => { + if (editor.isDestroyed) return const dom = editor.view.dom if (activeOptionId) { dom.setAttribute('aria-controls', listboxId) diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-bubble-menu-floating.ts b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-bubble-menu-floating.ts index 4e7b2b401b7..accf9f83f1c 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-bubble-menu-floating.ts +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-bubble-menu-floating.ts @@ -21,6 +21,7 @@ export function bubbleMenuAnchorRange(selection: Selection): { from: number; to: * editor mounts so the caller skips positioning. */ function selectionVirtualElement(editor: Editor) { + if (editor.isDestroyed) return null const { view, state } = editor if (!view.dom.isConnected) return null const { from, to } = bubbleMenuAnchorRange(state.selection) @@ -53,10 +54,11 @@ export function useBubbleMenuFloating( useEffect(() => { const menu = menuRef.current - if (!menu) return + if (!menu || editor.isDestroyed) return let stop: (() => void) | undefined const trackSelection = () => { stop?.() + if (editor.isDestroyed) return const { node } = editor.view.domAtPos(editor.state.selection.from) const reference = node instanceof Element ? node : (node.parentElement ?? editor.view.dom) stop = autoUpdate(reference, menu, () => { diff --git a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-editor-toolbar.ts b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-editor-toolbar.ts index f86e2220fde..a29fc5865f9 100644 --- a/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-editor-toolbar.ts +++ b/apps/sim/app/workspace/[workspaceId]/files/components/file-viewer/rich-markdown-editor/menus/use-editor-toolbar.ts @@ -54,6 +54,7 @@ export function useEditorToolbar({ }) useEffect(() => { + if (editor.isDestroyed) return let frame: number | undefined const enterToolbar = (event: globalThis.KeyboardEvent) => { if ( diff --git a/apps/sim/scripts/test-markdown-viewer-e2e.ts b/apps/sim/scripts/test-markdown-viewer-e2e.ts index 7726a0e529b..08808b78fcb 100644 --- a/apps/sim/scripts/test-markdown-viewer-e2e.ts +++ b/apps/sim/scripts/test-markdown-viewer-e2e.ts @@ -44,6 +44,8 @@ const shareToken = generateShortId() const token = generateShortId() const cookie = `${token}.${await makeSignature(token, secret)}` const cookieHeader = `better-auth.session_token=${cookie}` +// Keep the polling verifier's public content quota separate from browser visitors. +const verifierIp = `2001:db8:${Array.from(crypto.getRandomValues(new Uint16Array(6)), (value) => value.toString(16)).join(':')}` const checks: { name: string; passed: boolean; durationMs: number; error?: string }[] = [] const errors: string[] = [] let fileId: string | undefined @@ -118,7 +120,12 @@ async function request( // boundary-raw-fetch: standalone browser proof calls an explicitly supplied loopback app with its own session. const response = await fetch(new URL(path, base), { method, - headers: { Cookie: cookieHeader, Origin: base.origin, 'Content-Type': 'application/json' }, + headers: { + Cookie: cookieHeader, + Origin: base.origin, + 'Content-Type': 'application/json', + 'X-Forwarded-For': verifierIp, + }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120_000), }) @@ -143,6 +150,8 @@ async function check(name: string, run: () => Promise, page?: Page) { const selection = getSelection() const editable = document.querySelector('.rich-markdown-prose[contenteditable="true"]') return { + url: location.href, + body: document.body.innerText.slice(0, 2000), documentFocused: document.hasFocus(), editorFocused: document.activeElement === editable, activeTag: document.activeElement?.tagName, @@ -366,7 +375,7 @@ async function editLastCell(page: Page, marker: string) { ]) { assert(saved.includes(preserved), `Saving lost ${preserved}`) } - await page.reload() + await page.reload({ waitUntil: 'domcontentloaded' }) await expect(page.locator('.rich-markdown-prose').filter({ visible: true })).toContainText( marker, { timeout: 120_000 } @@ -412,7 +421,9 @@ async function provePastePersistence(page: Page, browserName: string) { (await request(`/api/files/public/${pastedShareToken}/content`)).text() try { await sql`insert into public_share (id, resource_type, resource_id, entity_type, entity_id, workspace_id, created_by, token) values (${pastedShareId}, 'file', ${pastedFileId}, 'workspace', ${workspaceId}, ${workspaceId}, ${userId}, ${pastedShareToken})` - await page.goto(new URL(`/workspace/${workspaceId}/files/${pastedFileId}`, base).href) + await page.goto(new URL(`/workspace/${workspaceId}/files/${pastedFileId}`, base).href, { + waitUntil: 'domcontentloaded', + }) const editor = page.locator('.rich-markdown-prose[contenteditable="true"]') await expect(editor).toBeVisible({ timeout: 120_000 }) await expect(editor).toContainText('Start here.') @@ -513,7 +524,7 @@ async function provePastePersistence(page: Page, browserName: string) { `\\*\\*${marker} literal\\*\\*`, ]) assert(saved.includes(preserved), `Pasted content did not persist: ${preserved}`) - await page.reload() + await page.reload({ waitUntil: 'domcontentloaded' }) await expect(editor).toBeVisible({ timeout: 120_000 }) await expect(editor.locator('h1').filter({ hasText: `${marker} title` })).toBeVisible() await expect(editor.locator('table').filter({ hasText: `${marker} measure` })).toContainText( @@ -561,11 +572,195 @@ async function provePastePersistence(page: Page, browserName: string) { } } +/** Cached routes reconnect effects before useEditor replaces its disposed editor instance. */ +async function proveWarmNavigation(page: Page, browserName: string) { + await page.setViewportSize({ width: 1440, height: 1000 }) + const restoredShareId = generateId() + const restoredShareToken = generateShortId() + const folderName = `Navigation ${browserName}` + const createdFolder = toRecord( + toRecord( + await ( + await request(`/api/workspaces/${workspaceId}/files/folders`, { name: folderName }) + ).json() + ).folder + ) + assert.equal(typeof createdFolder.id, 'string') + const folderId = String(createdFolder.id) + const files: { id: string; name: string }[] = [] + const caughtErrors: string[] = [] + const captureError = (message: import('@playwright/test').ConsoleMessage) => { + if (message.type() === 'error') caughtErrors.push(message.text()) + } + page.on('console', captureError) + try { + for (const label of ['Origin', 'Destination']) { + const name = `navigation-${browserName}-${label.toLowerCase()}.md` + const created = toRecord( + toRecord( + await ( + await request(`/api/workspaces/${workspaceId}/files`, { + name, + folderId, + content: `# ${label} document\n\nA stable [navigation link](https://example.test/navigation).\n\n| Name | Value |\n| --- | --- |\n| Original row | Kept |\n\nLast paragraph.`, + contentType: 'text/markdown', + }) + ).json() + ).file + ) + assert.equal(typeof created.id, 'string') + files.push({ id: String(created.id), name }) + } + const origin = files[0] + const destination = files[1] + await sql`insert into public_share (id, resource_type, resource_id, entity_type, entity_id, workspace_id, created_by, token) values (${restoredShareId}, 'file', ${origin.id}, 'workspace', ${workspaceId}, ${workspaceId}, ${userId}, ${restoredShareToken})` + await page.goto( + new URL(`/workspace/${workspaceId}/files/${origin.id}?folderId=${folderId}`, base).href, + { waitUntil: 'domcontentloaded' } + ) + const editor = page.locator('.rich-markdown-prose[contenteditable="true"]') + await expect(editor).toBeVisible({ timeout: 30_000 }) + for (const keepFindOpen of [false, true]) { + await editor.evaluate((element) => { + const instance = (element as TiptapEditorHTMLElement).editor + if (!instance) throw new Error('The editable surface has no editor instance') + instance.commands.focus() + instance.commands.selectAll() + }) + if (keepFindOpen) { + await page.keyboard.press(process.platform === 'darwin' ? 'Meta+f' : 'Control+f') + const find = page.getByRole('textbox', { name: 'Find in document', exact: true }) + await find.fill('stable') + } + for (const next of [destination, origin]) { + await page.getByRole('button', { name: folderName, exact: true }).click() + await page.locator('[data-resource-row]').filter({ hasText: next.name }).click() + await expect(editor).toBeVisible({ timeout: 30_000 }) + await expect(editor.locator('h1')).toHaveText( + next === origin ? 'Origin document' : 'Destination document' + ) + } + } + // Restored controls must bind to the replacement editor, including their keyboard listeners. + const find = page.getByRole('textbox', { name: 'Find in document', exact: true }) + if (await find.isVisible()) + await page.getByRole('button', { name: 'Close find', exact: true }).click() + const lastParagraph = editor.locator(':scope > p').filter({ hasText: /^Last paragraph\.$/ }) + await lastParagraph.evaluate((element) => { + const instance = (element.closest('.rich-markdown-prose') as TiptapEditorHTMLElement).editor + if (!instance) throw new Error('The restored paragraph has no editor instance') + instance + .chain() + .focus() + .setTextSelection(instance.view.posAtDOM(element, element.childNodes.length)) + .run() + }) + await expect(editor).toBeFocused() + await page.keyboard.press('Enter') + await page.keyboard.type('/h2') + const commands = page.getByRole('listbox', { name: 'Commands', exact: true }) + await expect(commands.getByRole('option')).toHaveCount(1) + await expect(commands.getByRole('option')).toContainText('Heading 2') + await page.keyboard.press('Enter') + const restoredHeading = `Restored document controls ${browserName}` + await page.keyboard.insertText(restoredHeading) + const heading = editor.locator('h2').filter({ hasText: restoredHeading }) + await expect(heading).toHaveText(restoredHeading) + await expect(commands).toHaveCount(0) + + await lastParagraph.evaluate((element) => { + const instance = (element.closest('.rich-markdown-prose') as TiptapEditorHTMLElement).editor + if (!instance) throw new Error('The restored paragraph has no editor instance') + instance + .chain() + .focus() + .setTextSelection({ + from: instance.view.posAtDOM(element, 0), + to: instance.view.posAtDOM(element, element.childNodes.length), + }) + .run() + }) + await expect.poll(() => page.evaluate(() => getSelection()?.toString())).toBe('Last paragraph.') + await page.keyboard.press('Alt+F10') + const toolbar = page.getByRole('toolbar', { name: 'Text formatting', exact: true }) + await expect + .poll(() => toolbar.evaluate((element) => element.contains(document.activeElement))) + .toBe(true) + await toolbar.getByRole('button', { name: 'Bold', exact: true }).click() + await expect(lastParagraph.locator('strong')).toHaveText('Last paragraph.') + await expect(editor).toBeFocused() + + await page.keyboard.press(process.platform === 'darwin' ? 'Meta+f' : 'Control+f') + await find.fill('document') + await expect(page.getByText('1 of 2', { exact: true })).toBeVisible() + await expect(editor.locator('.rich-find-match')).toHaveCount(2) + await expect(editor.locator('h1 .rich-find-match-active')).toHaveText('document') + await find.press('Enter') + await expect(page.getByText('2 of 2', { exact: true })).toBeVisible() + await expect(heading.locator('.rich-find-match-active')).toHaveText('document') + await find.press('Shift+Enter') + await expect(page.getByText('1 of 2', { exact: true })).toBeVisible() + await expect(editor.locator('h1 .rich-find-match-active')).toHaveText('document') + await page.getByRole('button', { name: 'Close find', exact: true }).click() + await expect(editor.locator('.rich-find-match')).toHaveCount(0) + + // The restored collaboration room persists both control edits and subsequent typing. + await heading.evaluate((element) => { + const instance = (element.closest('.rich-markdown-prose') as TiptapEditorHTMLElement).editor + if (!instance) throw new Error('The restored heading has no editor instance') + instance + .chain() + .focus() + .setTextSelection(instance.view.posAtDOM(element, element.childNodes.length)) + .run() + }) + await expect(editor).toBeFocused() + const marker = ` persisted after cached navigation ${browserName}` + await page.keyboard.insertText(marker) + const readRestoredSource = async () => + (await request(`/api/files/public/${restoredShareToken}/content`)).text() + await expect.poll(readRestoredSource, { timeout: 30_000 }).toContain(marker) + const saved = await readRestoredSource() + assert.equal( + saved.match(/^# Origin document$/gm)?.length, + 1, + 'Navigation duplicated the document' + ) + assert(saved.includes('[navigation link](https://example.test/navigation)')) + assert(saved.includes('Original row')) + assert(saved.includes('**Last paragraph.**'), 'Restored toolbar formatting did not persist') + assert(saved.includes(`## ${restoredHeading}`), 'Restored slash command did not persist') + assert(!saved.includes('/h2'), 'The slash query remained in the saved document') + await editor.getByRole('link', { name: 'navigation link' }).hover() + await expect(page.getByRole('dialog', { name: 'Link', exact: true })).toBeVisible() + assert.deepEqual(caughtErrors, [], 'Cached navigation raised a caught browser error') + await page.screenshot({ path: resolve(artifactDir, `navigation-${browserName}.png`) }) + } finally { + page.off('console', captureError) + const deletions = await Promise.allSettled( + files.map((file) => + request(`/api/workspaces/${workspaceId}/files/${file.id}`, undefined, 'DELETE') + ) + ) + const cleanup = await Promise.allSettled([ + sql`delete from public_share where id=${restoredShareId}`, + sql`delete from folder where id=${folderId} and workspace_id=${workspaceId}`, + ]) + for (const deletion of [...deletions, ...cleanup]) { + assert.equal( + deletion.status, + 'fulfilled', + deletion.status === 'rejected' ? getErrorMessage(deletion.reason) : undefined + ) + } + } +} + async function proveCollaborationCursor(page: Page) { const peer = await page.context().newPage() peer.on('pageerror', (error) => errors.push(error.message)) try { - await peer.goto(page.url(), { timeout: 360_000 }) + await peer.goto(page.url(), { waitUntil: 'domcontentloaded', timeout: 360_000 }) await expect(peer.locator('.rich-markdown-prose[contenteditable="true"]')).toBeVisible({ timeout: 120_000, }) @@ -664,7 +859,7 @@ async function proveCollaborationScroll(page: Page) { const peer = await page.context().newPage() peer.on('pageerror', (error) => errors.push(error.message)) try { - await peer.goto(page.url(), { timeout: 360_000 }) + await peer.goto(page.url(), { waitUntil: 'domcontentloaded', timeout: 360_000 }) await expect(peer.locator('.rich-markdown-prose[contenteditable="true"]')).toBeVisible({ timeout: 120_000, }) @@ -772,16 +967,29 @@ try { page.on('pageerror', (error) => errors.push(`${browserName}: ${error.message}`)) for (const width of widths) { await page.setViewportSize({ width, height: 1000 }) - await page.goto(new URL(`/f/${shareToken}`, base).href, { timeout: 360_000 }) - await check(`${browserName} public ${width}: readable and reachable wide columns`, () => - wideTableProof(page) + await page.goto(new URL(`/f/${shareToken}`, base).href, { + waitUntil: 'domcontentloaded', + timeout: 360_000, + }) + await check( + `${browserName} public ${width}: readable and reachable wide columns`, + () => wideTableProof(page), + page + ) + await check( + `${browserName} public ${width}: prose and long content stay contained`, + () => contained(page), + page ) - await check(`${browserName} public ${width}: prose and long content stay contained`, () => - contained(page) + await check( + `${browserName} public ${width}: long code scrolls`, + () => proveCode(page), + page ) - await check(`${browserName} public ${width}: long code scrolls`, () => proveCode(page)) - await check(`${browserName} public ${width}: alignment, images, and diagrams`, () => - proveFeatures(page) + await check( + `${browserName} public ${width}: alignment, images, and diagrams`, + () => proveFeatures(page), + page ) await page.locator('.rich-markdown-prose h1').scrollIntoViewIfNeeded() await page.screenshot({ path: resolve(artifactDir, `${browserName}-public-${width}.png`) }) @@ -796,6 +1004,7 @@ try { for (const width of widths) { await page.setViewportSize({ width, height: 1000 }) await page.goto(new URL(`/workspace/${workspaceId}/files/${fileId}`, base).href, { + waitUntil: 'domcontentloaded', timeout: 360_000, }) await expect(page.locator('.rich-markdown-prose[contenteditable="true"]')).toBeVisible({ @@ -848,6 +1057,11 @@ try { () => provePastePersistence(page, browserName), page ) + await check( + `${browserName}: cached file navigation restores editing, menus, and persistence`, + () => proveWarmNavigation(page, browserName), + page + ) } finally { await browser.close() }