AI-native design editor. Open-source Figma alternative.
fix(app): reuse tabs for repeated file opens (#423)
Danila Poyarkovf6e446a78957
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6cdeff391..7e1e41243 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,7 @@- Preserve Hangul IME composition while editing text.- Share public app links from the desktop collaboration panel and send the current document to newly joined collaborators.- Resolve published package types correctly for TypeScript consumers and keep file-backed CLI commands working under Node.+- Reuse the existing tab when reopening a file through its desktop path or browser file handle, avoiding duplicate watchers and conflicting saves (#297).### Securitydiff --git a/src/app/automation/bridge/file-handlers.ts b/src/app/automation/bridge/file-handlers.tsindex 6b0921463..39695f6ae 100644--- a/src/app/automation/bridge/file-handlers.ts+++ b/src/app/automation/bridge/file-handlers.ts@@ -3,6 +3,7 @@ import {responseWithTarget,type AutomationTarget} from '@/app/automation/bridge/target'+import { resolveBrowserFileURL } from '@/app/document/io/browser'import { openFileFromPath } from '@/app/shell/menu/use'import { createTab, getActiveStore, openFileInNewTab } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'@@ -52,11 +53,12 @@ export async function handleOpenFile(_target: AutomationTarget, args: unknown):if (isTauri()) {await openFileFromPath(path)} else {- const response = await fetch(path)+ const resourceURL = resolveBrowserFileURL(path)+ const response = await fetch(resourceURL)if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`)- const name = path.split(/[\\/]/).pop() ?? 'file.fig'+ const name = resourceURL.pathname.split('/').pop() ?? 'file.fig'const file = new File([await response.blob()], name)- await openFileInNewTab(file, undefined, path)+ await openFileInNewTab(file, undefined, resourceURL.href)}const target = resolveAutomationTarget(getActiveStore(), undefined)return responseWithTarget({ ok: true, result: { opened: true } }, target)diff --git a/src/app/document/io/browser.ts b/src/app/document/io/browser.tsindex e9cdabb00..3d09761ee 100644--- a/src/app/document/io/browser.ts+++ b/src/app/document/io/browser.ts@@ -1,5 +1,11 @@import type { ViewportSize } from '@/app/document/io/types'+export function resolveBrowserFileURL(path: string): URL {+ const url = new URL(path, window.location.href)+ url.hash = ''+ return url+}+export function yieldToUI(): Promise<void> {return new Promise((resolve) => {requestAnimationFrame(() => resolve())diff --git a/src/app/document/io/create.ts b/src/app/document/io/create.tsindex 50aa5d096..bb8bba9b3 100644--- a/src/app/document/io/create.ts+++ b/src/app/document/io/create.ts@@ -68,6 +68,7 @@ export function createDocumentIOActions(setViewportSize,fitCurrentPageToViewport,getDocumentFilePath: sourceState.getFilePath,+ getSourceIdentity: sourceState.getSourceIdentity,setDocumentSource: sourceActions.setDocumentSource,setPlannedFilePath: sourceActions.setPlannedFilePath,startWatchingCurrentFile: sourceActions.startWatchingCurrentFile,diff --git a/src/app/document/io/save.ts b/src/app/document/io/save.tsindex dba296f81..cc6baef87 100644--- a/src/app/document/io/save.ts+++ b/src/app/document/io/save.ts@@ -3,6 +3,7 @@ import type { EditorState } from '@open-pencil/core/editor'import { downloadBlob } from '@/app/document/io/browser'import { documentNameFromFigPath } from '@/app/document/io/names'import { chooseBrowserFigSaveHandle, chooseTauriFigSavePath } from '@/app/document/io/save-targets'+import type { DocumentSourceIdentity } from '@/app/document/io/types'import { createDocumentWriter } from '@/app/document/io/write'import { IS_TAURI } from '@/constants'@@ -17,6 +18,7 @@ type SaveActionsOptions = {setFileHandle: (handle: FileSystemFileHandle | null) => voidgetDownloadName: () => string | nullsetDownloadName: (name: string | null) => void+ setSourceIdentity: (identity: DocumentSourceIdentity) => voidsetSavedVersion: (version: number) => voidsetLastWriteTime: (time: number) => voidstartWatchingFile: () => void@@ -31,6 +33,7 @@ export function createSaveActions({setFileHandle,getDownloadName,setDownloadName,+ setSourceIdentity,setSavedVersion,setLastWriteTime,startWatchingFile@@ -48,7 +51,8 @@ export function createSaveActions({const fileHandle = getFileHandle()const downloadName = getDownloadName()if (filePath || fileHandle) {- await writeFile(await buildFigFile())+ const wrote = await writeFile(await buildFigFile())+ if (wrote) setSourceIdentity({ handle: fileHandle, path: filePath })} else if (downloadName) {downloadBlob(new Uint8Array(await buildFigFile()), downloadName, 'application/octet-stream')} else {@@ -65,7 +69,7 @@ export function createSaveActions({setFilePath(path)setFileHandle(null)state.documentName = documentNameFromFigPath(path)- await writeFile(data)+ if (await writeFile(data)) setSourceIdentity({ handle: null, path })startWatchingFile()return}@@ -76,7 +80,7 @@ export function createSaveActions({setFileHandle(handle)setFilePath(null)state.documentName = documentNameFromFigPath(handle.name)- await writeFile(data)+ if (await writeFile(data)) setSourceIdentity({ handle, path: null })startWatchingFile()return}diff --git a/src/app/document/io/source-state.ts b/src/app/document/io/source-state.tsindex 8efe78f57..43d49b9bc 100644--- a/src/app/document/io/source-state.ts+++ b/src/app/document/io/source-state.ts@@ -1,7 +1,10 @@+import type { DocumentSourceIdentity } from '@/app/document/io/types'+export function createDocumentSourceState() {let fileHandle: FileSystemFileHandle | null = nulllet filePath: string | null = nulllet downloadName: string | null = null+ let sourceIdentity: DocumentSourceIdentity = { handle: null, path: null }let savedVersion = 0let lastWriteTime = 0@@ -18,6 +21,10 @@ export function createDocumentSourceState() {setDownloadName: (name: string | null) => {downloadName = name},+ getSourceIdentity: () => sourceIdentity,+ setSourceIdentity: (identity: DocumentSourceIdentity) => {+ sourceIdentity = identity+ },getSavedVersion: () => savedVersion,setSavedVersion: (version: number) => {savedVersion = versiondiff --git a/src/app/document/io/source.ts b/src/app/document/io/source.tsindex 1be3b5fe3..7467ec78f 100644--- a/src/app/document/io/source.ts+++ b/src/app/document/io/source.ts@@ -9,6 +9,7 @@ import {} from '@/app/document/io/names'import { createSaveActions } from '@/app/document/io/save'import { createDocumentSourceState } from '@/app/document/io/source-state'+import type { DocumentSourceIdentity } from '@/app/document/io/types'type DocumentSourceState = EditorState & {documentName: string@@ -28,6 +29,7 @@ type DocumentSourceOptions = {setFilePath: (path: string | null) => voidgetDownloadName: () => string | nullsetDownloadName: (name: string | null) => void+ setSourceIdentity: (identity: DocumentSourceIdentity) => voidgetSavedVersion: () => numbersetSavedVersion: (version: number) => voidsetLastWriteTime: (time: number) => void@@ -45,6 +47,7 @@ export function createDocumentSourceActions({setFilePath,getDownloadName,setDownloadName,+ setSourceIdentity,getSavedVersion,setSavedVersion,setLastWriteTime,@@ -63,6 +66,7 @@ export function createDocumentSourceActions({setFileHandle,getDownloadName,setDownloadName,+ setSourceIdentity,setSavedVersion,setLastWriteTime,startWatchingFile: () => {@@ -74,7 +78,9 @@ export function createDocumentSourceActions({state,getSavedVersion,hasWritableSource: () => !!getFileHandle() || !!getFilePath(),- saveCurrentDocument: async () => writeFile(await buildFigFile())+ saveCurrentDocument: async () => {+ await writeFile(await buildFigFile())+ }})function setDocumentSource(@@ -88,6 +94,7 @@ export function createDocumentSourceActions({setFileHandle(isFig ? (handle ?? null) : null)setFilePath(isFig ? (path ?? null) : null)setDownloadName(figDownloadName(fileName, sourceFormat))+ setSourceIdentity({ handle: handle ?? null, path: path ?? null })setSavedVersion(state.sceneVersion)if (isFig && (handle || path)) {void startWatchingFile()diff --git a/src/app/document/io/types.ts b/src/app/document/io/types.tsindex e60a19b7e..48a9a92f5 100644--- a/src/app/document/io/types.ts+++ b/src/app/document/io/types.ts@@ -1 +1,6 @@+export type DocumentSourceIdentity = Readonly<{+ handle: FileSystemFileHandle | null+ path: string | null+}>+export type ViewportSize = { width: number; height: number }diff --git a/src/app/document/io/write.ts b/src/app/document/io/write.tsindex 776623084..daacf2c34 100644--- a/src/app/document/io/write.ts+++ b/src/app/document/io/write.ts@@ -27,13 +27,15 @@ export function createDocumentWriter({const { writeFile: tauriWrite } = await import('@tauri-apps/plugin-fs')await tauriWrite(filePath, data)setSavedVersion(state.sceneVersion)- return+ return true}if (fileHandle) {const writable = await fileHandle.createWritable()await writable.write(new Uint8Array(data))await writable.close()setSavedVersion(state.sceneVersion)+ return true}+ return false}}diff --git a/src/app/editor/session/modules.ts b/src/app/editor/session/modules.tsindex c5be2b90a..c8d4087a7 100644--- a/src/app/editor/session/modules.ts+++ b/src/app/editor/session/modules.ts@@ -76,6 +76,7 @@ export function createEditorStoreModules(saveFigFile: documentIO.saveFigFile,saveFigFileAs: documentIO.saveFigFileAs,getDocumentFilePath: documentIO.getDocumentFilePath,+ getSourceIdentity: documentIO.getSourceIdentity,setDocumentSource: documentIO.setDocumentSource,setPlannedFilePath: documentIO.setPlannedFilePath,startWatchingCurrentFile: documentIO.startWatchingCurrentFile,diff --git a/src/app/shell/menu/files.ts b/src/app/shell/menu/files.tsindex e2a2fd8e6..c3c2e1a2a 100644--- a/src/app/shell/menu/files.ts+++ b/src/app/shell/menu/files.ts@@ -1,6 +1,7 @@import { useFileDialog } from '@vueuse/core'import { setOpenPencilOpenFileHandler } from '@/app/browser-bridge'+import { resolveBrowserFileURL } from '@/app/document/io/browser'import { openFileInNewTab } from '@/app/tabs'import { isTauri } from '@/app/tauri/env'import { IS_BROWSER } from '@/constants'@@ -18,11 +19,12 @@ fileDialog.onChange((files) => {if (IS_BROWSER && 'window' in globalThis) {setOpenPencilOpenFileHandler(async (path: string) => {- const response = await fetch(path)+ const resourceURL = resolveBrowserFileURL(path)+ const response = await fetch(resourceURL)const blob = await response.blob()- const name = path.split('/').pop() ?? 'file.fig'+ const name = resourceURL.pathname.split('/').pop() ?? 'file.fig'const file = new File([blob], name, { type: 'application/octet-stream' })- await openFileInNewTab(file, undefined, path)+ await openFileInNewTab(file, undefined, resourceURL.href)})}diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.tsindex 7b93ed9e7..a4e13bd50 100644--- a/src/app/tabs/index.ts+++ b/src/app/tabs/index.ts@@ -6,9 +6,12 @@ import { computeAllLayouts } from '@open-pencil/core/layout'import type { SceneGraph } from '@open-pencil/scene-graph'import { setOpenPencilStore } from '@/app/browser-bridge'+import type { DocumentSourceIdentity } from '@/app/document/io/types'import { setActiveEditorStore } from '@/app/editor/active-store'import { createEditorStore } from '@/app/editor/session'import type { EditorStore } from '@/app/editor/session'+import { createFileOpenCoordinator } from '@/app/tabs/open/coordinator'+import { findTabByFileIdentity } from '@/app/tabs/open/identity'export interface Tab {id: string@@ -16,6 +19,7 @@ export interface Tab {}const io = new IORegistry(BUILTIN_IO_FORMATS)+const fileOpenCoordinator = createFileOpenCoordinator()let nextTabId = 1@@ -116,22 +120,53 @@ export async function openFileInNewTab(handle?: FileSystemFileHandle,path?: string): Promise<void> {- const current = activeTab.value- const isUntouched =- current?.store.state.documentName === 'Untitled' && !current.store.undo.canUndo- const store = isUntouched ? current.store : createTab().store- if (isDOMImportFile(file)) {- await store.openDOMFile(file, { handle, path })- return+ const identity: DocumentSourceIdentity = {+ handle: handle ?? null,+ path: path ?? null}+ const decision = await fileOpenCoordinator.decide(async () => {+ const pending = await fileOpenCoordinator.findPending(identity)+ if (pending) {+ const tab = getTabForStore(pending.store)+ if (tab) switchTab(tab.id)+ return { kind: 'pending' as const, completion: pending.completion }+ }++ const existing = await findTabByFileIdentity(tabsRef.value, identity)+ if (existing) {+ switchTab(existing.id)+ return { kind: 'existing' as const }+ }++ const current = activeTab.value+ const isUntouched =+ current?.store.state.documentName === 'Untitled' && !current.store.undo.canUndo+ const store = isUntouched ? current.store : createTab().store+ store.state.documentName = file.name.replace(/\.[^.]+$/i, '')+ store.state.loading = true++ const completion = Promise.withResolvers<undefined>()+ void completion.promise.catch(() => undefined)+ const pendingOpen = { completion: completion.promise, identity, store }+ fileOpenCoordinator.add(pendingOpen)+ return { kind: 'owner' as const, completion, pendingOpen, store }+ })- const documentName = file.name.replace(/\.[^.]+$/i, '')-- store.state.documentName = documentName- store.state.loading = true- await yieldToUI()+ if (decision.kind === 'existing') return+ if (decision.kind === 'pending') {+ await decision.completion+ return+ }+ const { completion, pendingOpen, store } = decisiontry {+ if (isDOMImportFile(file)) {+ await store.openDOMFile(file, { handle, path })+ completion.resolve(undefined)+ return+ }++ await yieldToUI()const isFig = file.name.toLowerCase().endsWith('.fig')const { graph: imported, sourceFormat } = isFig? { graph: await readFigFile(file, { populate: 'first-page' }), sourceFormat: 'fig' }@@ -150,8 +185,13 @@ export async function openFileInNewTab(const pageId = store.graph.getPages()[0]?.id ?? store.graph.rootIdawait store.switchPage(pageId)await store.fitCurrentPageToViewport()+ completion.resolve(undefined)+ } catch (error) {+ completion.reject(error)+ throw error} finally {store.state.loading = false+ fileOpenCoordinator.remove(pendingOpen)}}diff --git a/src/app/tabs/open/coordinator.ts b/src/app/tabs/open/coordinator.tsnew file mode 100644index 000000000..741e95d85--- /dev/null+++ b/src/app/tabs/open/coordinator.ts@@ -0,0 +1,47 @@+import type { DocumentSourceIdentity } from '@/app/document/io/types'+import type { EditorStore } from '@/app/editor/session'+import { fileIdentitiesMatch, hasFileIdentity } from '@/app/tabs/open/identity'++type PendingOpen = {+ completion: Promise<undefined>+ identity: DocumentSourceIdentity+ store: EditorStore+}++export function createFileOpenCoordinator() {+ const pending: PendingOpen[] = []+ let decisionTail = Promise.resolve()++ async function decide<T>(operation: () => Promise<T>): Promise<T> {+ const previous = decisionTail+ let release: () => void = () => undefined+ decisionTail = new Promise<void>((resolve) => {+ release = resolve+ })+ await previous+ try {+ return await operation()+ } finally {+ release()+ }+ }++ async function findPending(identity: DocumentSourceIdentity): Promise<PendingOpen | null> {+ if (!hasFileIdentity(identity)) return null+ for (const candidate of pending) {+ if (await fileIdentitiesMatch(candidate.identity, identity)) return candidate+ }+ return null+ }++ function add(entry: PendingOpen) {+ pending.push(entry)+ }++ function remove(entry: PendingOpen) {+ const index = pending.indexOf(entry)+ if (index !== -1) pending.splice(index, 1)+ }++ return { add, decide, findPending, remove }+}diff --git a/src/app/tabs/open/identity.ts b/src/app/tabs/open/identity.tsnew file mode 100644index 000000000..37cc7fc5c--- /dev/null+++ b/src/app/tabs/open/identity.ts@@ -0,0 +1,51 @@+import type { DocumentSourceIdentity } from '@/app/document/io/types'++type IdentitySource = {+ getSourceIdentity: () => DocumentSourceIdentity+}++type IdentifiedTab = {+ store: IdentitySource+}++export function hasFileIdentity(identity: DocumentSourceIdentity): boolean {+ return !!(identity.handle || identity.path)+}++async function handlesMatch(+ first: FileSystemFileHandle | null,+ second: FileSystemFileHandle | null+): Promise<boolean> {+ if (!first || !second) return false+ if (first === second) return true+ try {+ return await first.isSameEntry(second)+ } catch {+ return false+ }+}++export async function fileIdentitiesMatch(+ first: DocumentSourceIdentity,+ second: DocumentSourceIdentity+): Promise<boolean> {+ if (first.path && second.path && first.path === second.path) return true+ return handlesMatch(first.handle, second.handle)+}++export async function findTabByFileIdentity<T extends IdentifiedTab>(+ tabs: readonly T[],+ identity: DocumentSourceIdentity+): Promise<T | null> {+ if (!hasFileIdentity(identity)) return null+ for (const tab of tabs) {+ const storedIdentity = tab.store.getSourceIdentity()+ if (+ (await fileIdentitiesMatch(storedIdentity, identity)) &&+ tab.store.getSourceIdentity() === storedIdentity+ ) {+ return tab+ }+ }+ return null+}diff --git a/tests/engine/app/document/io/source-identity.test.ts b/tests/engine/app/document/io/source-identity.test.tsnew file mode 100644index 000000000..73447536d--- /dev/null+++ b/tests/engine/app/document/io/source-identity.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test, vi } from 'bun:test'++import { createDefaultEditorState } from '@open-pencil/core/editor'++import { createSaveActions } from '@/app/document/io/save'++function makeWritableHandle(name: string): FileSystemFileHandle {+ return {+ kind: 'file',+ name,+ createWritable: vi.fn(async () => ({+ write: vi.fn(async () => undefined),+ close: vi.fn(async () => undefined)+ }))+ } as FileSystemFileHandle+}++function createSaveHarness(handle: FileSystemFileHandle) {+ const state = {+ ...createDefaultEditorState('page'),+ documentName: 'Untitled'+ }+ const setSourceIdentity = vi.fn()+ const actions = createSaveActions({+ state,+ buildFigFile: () => new Uint8Array([1, 2, 3]),+ getFilePath: () => null,+ setFilePath: vi.fn(),+ getFileHandle: () => handle,+ setFileHandle: vi.fn(),+ getDownloadName: () => null,+ setDownloadName: vi.fn(),+ setSourceIdentity,+ setSavedVersion: vi.fn(),+ setLastWriteTime: vi.fn(),+ startWatchingFile: vi.fn()+ })+ return { actions, setSourceIdentity }+}++describe('saved document identity', () => {+ test('publishes the writable handle after a successful save', async () => {+ const handle = makeWritableHandle('saved.fig')+ const { actions, setSourceIdentity } = createSaveHarness(handle)++ await actions.saveFigFile()++ expect(setSourceIdentity).toHaveBeenCalledWith({ handle, path: null })+ })++ test('does not publish an identity when writing fails', async () => {+ const handle = {+ kind: 'file',+ name: 'failed.fig',+ createWritable: vi.fn(async () => {+ throw new Error('write failed')+ })+ } as FileSystemFileHandle+ const { actions, setSourceIdentity } = createSaveHarness(handle)++ await expect(actions.saveFigFile()).rejects.toThrow('write failed')+ expect(setSourceIdentity).not.toHaveBeenCalled()+ })+})diff --git a/tests/engine/app/tabs/open-file-dedup.test.ts b/tests/engine/app/tabs/open-file-dedup.test.tsnew file mode 100644index 000000000..c39bae377--- /dev/null+++ b/tests/engine/app/tabs/open-file-dedup.test.ts@@ -0,0 +1,200 @@+import { afterEach, beforeEach, describe, expect, test, vi } from 'bun:test'++import * as figModule from '@open-pencil/core/io/formats/fig'+import * as layoutModule from '@open-pencil/core/layout'+import { SceneGraph } from '@open-pencil/scene-graph'++import { resolveBrowserFileURL } from '@/app/document/io/browser'+import type { DocumentSourceIdentity } from '@/app/document/io/types'+import { createTab, getActiveStore, openFileInNewTab, tabCount } from '@/app/tabs'+import { fileIdentitiesMatch, findTabByFileIdentity } from '@/app/tabs/open/identity'++function setupGlobals() {+ globalThis.window = {+ innerWidth: 1024,+ innerHeight: 768,+ requestAnimationFrame: (callback: FrameRequestCallback) => {+ callback(0)+ return 0+ },+ cancelAnimationFrame: vi.fn(),+ openPencil: {},+ location: { href: 'http://localhost/' } as Location,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn()+ } as Window & typeof globalThis+ globalThis.document = {+ fonts: { add: vi.fn(), ready: Promise.resolve() }+ } as Document+ globalThis.requestAnimationFrame = window.requestAnimationFrame+ globalThis.cancelAnimationFrame = window.cancelAnimationFrame+}++function makeHandle(+ name: string,+ isSameEntry: (other: FileSystemFileHandle) => Promise<boolean>+): FileSystemFileHandle {+ return { kind: 'file', name, isSameEntry } as FileSystemFileHandle+}++describe('file identity', () => {+ test('matches equivalent handles without using file names as identity', async () => {+ const stored = makeHandle('design.fig', async (other) => other.name === 'alias.fig')+ const alias = makeHandle('alias.fig', async () => false)+ const sameName = makeHandle('design.fig', async () => false)++ await expect(+ fileIdentitiesMatch({ handle: stored, path: null }, { handle: alias, path: null })+ ).resolves.toBe(true)+ await expect(+ fileIdentitiesMatch({ handle: stored, path: null }, { handle: sameName, path: null })+ ).resolves.toBe(false)+ })++ test('ignores an asynchronous handle match after the tab source changes', async () => {+ const comparison = Promise.withResolvers<boolean>()+ const started = Promise.withResolvers<undefined>()+ const storedHandle = makeHandle('stored.fig', async () => {+ started.resolve(undefined)+ return comparison.promise+ })+ const incomingHandle = makeHandle('incoming.fig', async () => false)+ let storedIdentity: DocumentSourceIdentity = { handle: storedHandle, path: null }+ const tab = { store: { getSourceIdentity: () => storedIdentity } }++ const finding = findTabByFileIdentity([tab], {+ handle: incomingHandle,+ path: null+ })+ await started.promise+ storedIdentity = { handle: storedHandle, path: '/other.fig' }+ comparison.resolve(true)++ await expect(finding).resolves.toBeNull()+ })++ test('finds a tab by path and ignores tabs without stable identity', async () => {+ const matchedIdentity = { handle: null, path: '/tmp/design.fig' }+ const matched = {+ store: { getSourceIdentity: () => matchedIdentity }+ }+ const unidentifiedIdentity = { handle: null, path: null }+ const unidentified = {+ store: { getSourceIdentity: () => unidentifiedIdentity }+ }++ await expect(+ findTabByFileIdentity([unidentified, matched], {+ handle: null,+ path: '/tmp/design.fig'+ })+ ).resolves.toBe(matched)+ await expect(+ findTabByFileIdentity([unidentified], { handle: null, path: null })+ ).resolves.toBeNull()+ })+})++describe('openFileInNewTab deduplication', () => {+ beforeEach(() => {+ setupGlobals()+ vi.spyOn(layoutModule, 'computeAllLayouts').mockReturnValue(undefined)+ vi.spyOn(figModule, 'readFigFile').mockResolvedValue(new SceneGraph())+ createTab()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ Reflect.deleteProperty(globalThis, 'window')+ Reflect.deleteProperty(globalThis, 'document')+ Reflect.deleteProperty(globalThis, 'requestAnimationFrame')+ Reflect.deleteProperty(globalThis, 'cancelAnimationFrame')+ })++ test('canonicalizes browser URLs before using them as file identity', () => {+ expect(resolveBrowserFileURL('/design.fig#selection').href).toBe('http://localhost/design.fig')+ })++ test('activates the existing tab when the same path is opened again', async () => {+ const initialCount = tabCount()+ const file = new File([], 'design.fig')++ await openFileInNewTab(file, undefined, '/tmp/design.fig')+ const openedStore = getActiveStore()+ await openFileInNewTab(file, undefined, '/tmp/design.fig')++ expect(tabCount()).toBe(initialCount)+ expect(getActiveStore()).toBe(openedStore)+ expect(figModule.readFigFile).toHaveBeenCalledTimes(1)+ })++ test('shares one load between concurrent opens of the same path', async () => {+ const started = Promise.withResolvers<undefined>()+ const read = Promise.withResolvers<SceneGraph>()+ ;(figModule.readFigFile as ReturnType<typeof vi.fn>).mockImplementation(() => {+ started.resolve(undefined)+ return read.promise+ })+ const initialCount = tabCount()+ const file = new File([], 'concurrent.fig')++ const first = openFileInNewTab(file, undefined, '/tmp/concurrent.fig')+ await started.promise+ const second = openFileInNewTab(file, undefined, '/tmp/concurrent.fig')+ await Promise.resolve()++ expect(figModule.readFigFile).toHaveBeenCalledTimes(1)+ read.resolve(new SceneGraph())+ await Promise.all([first, second])+ expect(tabCount()).toBe(initialCount)+ })++ test('allows different files to load concurrently', async () => {+ const reads = [Promise.withResolvers<SceneGraph>(), Promise.withResolvers<SceneGraph>()]+ const bothStarted = Promise.withResolvers<undefined>()+ let readIndex = 0+ ;(figModule.readFigFile as ReturnType<typeof vi.fn>).mockImplementation(() => {+ const read = reads[readIndex++]+ if (readIndex === 2) bothStarted.resolve(undefined)+ return read?.promise ?? Promise.resolve(new SceneGraph())+ })+ const initialCount = tabCount()++ const first = openFileInNewTab(new File([], 'first.fig'), undefined, '/tmp/first.fig')+ const second = openFileInNewTab(new File([], 'second.fig'), undefined, '/tmp/second.fig')+ await bothStarted.promise++ expect(figModule.readFigFile).toHaveBeenCalledTimes(2)+ reads[0].resolve(new SceneGraph())+ reads[1].resolve(new SceneGraph())+ await Promise.all([first, second])+ expect(tabCount()).toBe(initialCount + 1)+ })++ test('removes a failed pending open so the file can be retried', async () => {+ ;(figModule.readFigFile as ReturnType<typeof vi.fn>)+ .mockRejectedValueOnce(new Error('read failed'))+ .mockResolvedValueOnce(new SceneGraph())++ await expect(+ openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig')+ ).rejects.toThrow('read failed')+ await expect(+ openFileInNewTab(new File([], 'retry.fig'), undefined, '/tmp/retry.fig')+ ).resolves.toBeUndefined()++ expect(figModule.readFigFile).toHaveBeenCalledTimes(2)+ expect(getActiveStore().getSourceIdentity().path).toBe('/tmp/retry.fig')+ })++ test('keeps same-named files distinct without a path or handle', async () => {+ const initialCount = tabCount()+ const file = new File([], 'same-name.fig')++ await openFileInNewTab(file)+ await openFileInNewTab(file)++ expect(tabCount()).toBe(initialCount + 1)+ expect(figModule.readFigFile).toHaveBeenCalledTimes(2)+ })+})