Skip to content

AI-native design editor. Open-source Figma alternative.

fix: release documents when their tabs close (#904)

Danila Poyarkovf465da8b812d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1813cf2c4..ac68704c2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -80,6 +80,7 @@
### Fixed
+- Release a document's memory when its tab closes. Every closed tab kept its scene, canvas, and editor panels alive until reload, so memory grew with each document opened and closed. Menus and shortcuts now also follow the active document, so Undo and Redo are offered according to its history rather than the first document opened.
- Start Pi chats with OpenPencil's MCP tools when the Harness companion runs on Node 22.15 or later; the companion now installs the dependency Pi's MCP adapter needs and loads its TypeScript sources. A reopened Pi session starts fresh instead of failing to resume its in-memory sandbox, and npm output from Pi no longer mixes into the companion's protocol.
- Import HTML and CSS with the right shadow and border colors. A shadow whose color follows its lengths, as CSS usually writes it, and a `border` with a color function such as `rgb(226, 232, 240)` came in black. Every layer of a `box-shadow` list now imports, `inset` ones as inner shadows, and lengths in `%`, `em`, or `vh` are no longer read as pixels.
- Accept a CSS `box-shadow` list in design JSX's `shadow` prop: the color may come first, a fourth length sets the spread, several layers add several shadows, and `inset` makes an inner shadow. A color before the lengths or a spread made the shadow black.
diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.ts
index ae3737bfd..40aca9073 100644
--- a/packages/core/src/editor/create.ts
+++ b/packages/core/src/editor/create.ts
@@ -10,7 +10,7 @@ import { prefetchFigmaSchema } from '#core/clipboard'
import { IS_BROWSER } from '#core/constants'
import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'
import { releaseOriginalFigArchive } from '#core/kiwi/fig/session/original-archive'
-import { setTextMeasurer } from '#core/layout'
+import { installTextMeasurer } from '#core/layout'
import { createLayoutRunner } from '#core/layout/mutations'
import { emitNavigationTrace } from '#core/profiler'
import { TextEditor } from '#core/text/editor'
@@ -66,6 +66,7 @@ export function createEditor(options?: EditorOptions) {
let _ck: CanvasKit | null = null
let _renderer: SkiaRenderer | null = null
const _renderers = new Set<SkiaRenderer>()
+ let uninstallTextMeasurer: (() => void) | null = null
const interactiveEdits = new Set<symbol>()
let _textEditor: TextEditor | null = null
const events: Emitter<EditorEvents> = createNanoEvents()
@@ -243,11 +244,16 @@ export function createEditor(options?: EditorOptions) {
_renderer = renderer
_renderers.add(renderer)
_textEditor ??= new TextEditor(ck)
- setTextMeasurer(
+ uninstallTextMeasurer?.()
+ uninstallTextMeasurer =
typeof renderer.measureTextNode === 'function'
- ? (node, maxWidth) => renderer.measureTextNode(node, maxWidth)
+ ? installTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))
: null
- )
+ }
+
+ function releaseTextMeasurer() {
+ uninstallTextMeasurer?.()
+ uninstallTextMeasurer = null
}
function removeCanvasRenderer(renderer: SkiaRenderer) {
@@ -255,6 +261,7 @@ export function createEditor(options?: EditorOptions) {
if (_renderer === renderer) {
_renderer = _renderers.values().next().value ?? null
}
+ if (_renderers.size === 0) releaseTextMeasurer()
}
function replaceGraph(newGraph: SceneGraph) {
@@ -281,6 +288,7 @@ export function createEditor(options?: EditorOptions) {
}
function dispose() {
+ releaseTextMeasurer()
nodes.cancelNodePreviews()
interactiveEdits.clear()
stopFontResolutionEvents()
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 6643594c2..2ca178bbf 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -20,6 +20,7 @@ import { buildGridTree, createGridChildNode } from './layout/grid'
export {
estimateTextSize,
getTextMeasurer,
+ installTextMeasurer,
setTextMeasurer,
type TextMeasurer
} from './layout/text-measurement'
diff --git a/packages/core/src/layout/text-measurement.ts b/packages/core/src/layout/text-measurement.ts
index 294a434b5..bc9e47af7 100644
--- a/packages/core/src/layout/text-measurement.ts
+++ b/packages/core/src/layout/text-measurement.ts
@@ -44,6 +44,23 @@ export function setTextMeasurer(measurer: TextMeasurer | null): void {
globalTextMeasurer = measurer
}
+const installedMeasurers: TextMeasurer[] = []
+
+/**
+ * Makes `measurer` the layout text measurer until the returned function uninstalls it. Then
+ * the most recent measurer still installed takes over, so closing one editor neither leaves
+ * layout measuring with its destroyed renderer nor keeps that editor alive.
+ */
+export function installTextMeasurer(measurer: TextMeasurer): () => void {
+ installedMeasurers.push(measurer)
+ globalTextMeasurer = measurer
+ return () => {
+ const index = installedMeasurers.lastIndexOf(measurer)
+ if (index !== -1) installedMeasurers.splice(index, 1)
+ if (globalTextMeasurer === measurer) globalTextMeasurer = installedMeasurers.at(-1) ?? null
+ }
+}
+
/**
* Run `fn` with `measurer` as the layout text measurer. The measurer is shared, so `fn` must
* be synchronous: an override held across an await would leak into other layouts.
diff --git a/packages/core/tests/layout/text-measurement.test.ts b/packages/core/tests/layout/text-measurement.test.ts
new file mode 100644
index 000000000..28d4653da
--- /dev/null
+++ b/packages/core/tests/layout/text-measurement.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import {
+ getTextMeasurer,
+ installTextMeasurer,
+ setTextMeasurer,
+ type TextMeasurer
+} from '#core/layout/text-measurement'
+
+const measurer =
+ (width: number): TextMeasurer =>
+ () => ({ width, height: 10 })
+
+describe('installTextMeasurer', () => {
+ afterEach(() => setTextMeasurer(null))
+
+ test('falls back to the most recent measurer still installed', () => {
+ const first = measurer(1)
+ const second = measurer(2)
+ const uninstallFirst = installTextMeasurer(first)
+ const uninstallSecond = installTextMeasurer(second)
+ expect(getTextMeasurer()).toBe(second)
+
+ uninstallSecond()
+ expect(getTextMeasurer()).toBe(first)
+ uninstallFirst()
+ expect(getTextMeasurer()).toBeNull()
+ })
+
+ test('uninstalling an earlier measurer keeps the current one', () => {
+ const first = measurer(1)
+ const second = measurer(2)
+ const uninstallFirst = installTextMeasurer(first)
+ const uninstallSecond = installTextMeasurer(second)
+ uninstallFirst()
+ expect(getTextMeasurer()).toBe(second)
+ uninstallSecond()
+ expect(getTextMeasurer()).toBeNull()
+ })
+})
diff --git a/packages/vue/src/canvas/surface/gl-surface.ts b/packages/vue/src/canvas/surface/gl-surface.ts
index 5d7fc84eb..3e4e3b226 100644
--- a/packages/vue/src/canvas/surface/gl-surface.ts
+++ b/packages/vue/src/canvas/surface/gl-surface.ts
@@ -13,8 +13,44 @@ import {
} from './color-space'
type GLContext = ReturnType<CanvasKit['MakeGrContext']>
+type GLHandle = ReturnType<CanvasKit['GetWebGLContext']>
export type CanvasGLContext = GLContext
+export type CanvasGLHandle = GLHandle
+
+const parkingHandles = new WeakMap<CanvasKit, GLHandle>()
+
+/** A 1×1 offscreen WebGL context that stays registered, so another context can become current. */
+function parkingHandle(ck: CanvasKit): GLHandle | null {
+ const existing = parkingHandles.get(ck)
+ if (existing !== undefined) return existing
+ if (typeof document === 'undefined') return null
+ const canvas = document.createElement('canvas')
+ canvas.width = 1
+ canvas.height = 1
+ const handle = ck.GetWebGLContext(canvas)
+ if (!handle) return null
+ parkingHandles.set(ck, handle)
+ return handle
+}
+
+/**
+ * Unregisters a canvas's WebGL context from CanvasKit. `deleteContext` leaves CanvasKit holding
+ * the last current context, which keeps the canvas, and every component its element reaches,
+ * alive; when this context was current, a parking context takes its place.
+ */
+export function releaseWebGLContext(
+ ck: CanvasKit,
+ handle: GLHandle,
+ canvas: HTMLCanvasElement | null
+): void {
+ const context = canvas ? (canvas.getContext('webgl2') ?? canvas.getContext('webgl')) : null
+ const wasCurrent = context !== null && Reflect.get(ck, 'ctx') === context
+ ck.deleteContext(handle)
+ if (!wasCurrent) return
+ const parking = parkingHandle(ck)
+ if (parking) ck.MakeGrContext(parking)?.delete()
+}
export function sizeCanvas(
canvas: HTMLCanvasElement,
@@ -42,12 +78,20 @@ export function makeGLSurface(
): {
surface: Surface | null
glContext: GLContext | null
+ /**
+ * The WebGL context this call registered with CanvasKit, which the caller must release with
+ * `deleteContext`: CanvasKit's context table otherwise keeps the canvas, and everything its
+ * element reaches, alive. Null when the existing context was reused.
+ */
+ glHandle: GLHandle | null
presentation: PresentationColorSpace | null
} {
let context = glContext
const glAttrs = options?.preserveDrawingBuffer ? { preserveDrawingBuffer: 1 } : undefined
const handle = context ? null : ck.GetWebGLContext(canvas, glAttrs)
- if (!context && !handle) return { surface: null, glContext: context, presentation: null }
+ if (!context && !handle) {
+ return { surface: null, glContext: context, glHandle: null, presentation: null }
+ }
const buffer = canvas.getContext('webgl2') ?? canvas.getContext('webgl')
const presentation = configurePresentation(buffer, {
@@ -58,10 +102,13 @@ export function makeGLSurface(
})
if (!presentation) {
if (handle) ck.deleteContext(handle)
- return { surface: null, glContext: context, presentation: null }
+ return { surface: null, glContext: context, glHandle: null, presentation: null }
}
if (!context && handle) context = ck.MakeGrContext(handle)
- if (!context) return { surface: null, glContext: context, presentation: null }
+ if (!context) {
+ if (handle) ck.deleteContext(handle)
+ return { surface: null, glContext: context, glHandle: null, presentation: null }
+ }
return {
surface: ck.MakeOnScreenGLSurface(
@@ -71,6 +118,7 @@ export function makeGLSurface(
presentation === 'display-p3' ? ck.ColorSpace.DISPLAY_P3 : ck.ColorSpace.SRGB
),
glContext: context,
+ glHandle: handle,
presentation
}
}
diff --git a/packages/vue/src/canvas/surface/lifecycle.ts b/packages/vue/src/canvas/surface/lifecycle.ts
index 1120ec754..7de64e9cc 100644
--- a/packages/vue/src/canvas/surface/lifecycle.ts
+++ b/packages/vue/src/canvas/surface/lifecycle.ts
@@ -9,7 +9,13 @@ import {
supportsWideGamutPresentation,
type PresentationColorSpace
} from '#vue/canvas/surface/color-space'
-import { makeGLSurface, sizeCanvas, type CanvasGLContext } from '#vue/canvas/surface/gl-surface'
+import {
+ makeGLSurface,
+ releaseWebGLContext,
+ sizeCanvas,
+ type CanvasGLContext,
+ type CanvasGLHandle
+} from '#vue/canvas/surface/gl-surface'
import { useCanvasKitLoader } from '#vue/canvas/surface/kit-loader'
import { createCanvasRenderLoop } from '#vue/canvas/surface/render-loop'
import { useCanvasResizeObserver } from '#vue/canvas/surface/resize-observer'
@@ -18,6 +24,9 @@ import type { UseCanvasOptions } from '#vue/canvas/surface/types'
type SurfaceManagerState = {
renderer: SkiaRenderer | null
glContext: CanvasGLContext | null
+ glHandle: CanvasGLHandle | null
+ /** The canvas the WebGL context belongs to, kept until the context is released. */
+ glCanvas: HTMLCanvasElement | null
presentation: PresentationColorSpace | null
}
@@ -36,7 +45,13 @@ export function createCanvasSurfaceManager({
isDestroyed: () => boolean
shouldShowRulers: () => boolean
}) {
- const state: SurfaceManagerState = { renderer: null, glContext: null, presentation: null }
+ const state: SurfaceManagerState = {
+ renderer: null,
+ glContext: null,
+ glHandle: null,
+ glCanvas: null,
+ presentation: null
+ }
let sceneBackingRenderTimer: ReturnType<typeof setTimeout> | null = null
function clearSceneBackingRenderTimer() {
@@ -45,6 +60,16 @@ export function createCanvasSurfaceManager({
sceneBackingRenderTimer = null
}
+ /** Releases the Skia context and the WebGL context CanvasKit registered for this canvas. */
+ function releaseGLContext() {
+ state.glContext?.delete()
+ state.glContext = null
+ const ck = getCanvasKit()
+ if (ck && state.glHandle !== null) releaseWebGLContext(ck, state.glHandle, state.glCanvas)
+ state.glHandle = null
+ state.glCanvas = null
+ }
+
function createSurface(
canvas: HTMLCanvasElement,
{ reloadFonts = false }: { reloadFonts?: boolean } = {}
@@ -55,8 +80,7 @@ export function createCanvasSurfaceManager({
if (state.renderer) editor.removeCanvasRenderer(state.renderer)
state.renderer?.destroy()
state.renderer = null
- state.glContext?.delete()
- state.glContext = null
+ releaseGLContext()
sizeCanvas(canvas, editor, options?.onViewportResize)
@@ -68,6 +92,8 @@ export function createCanvasSurfaceManager({
editor.graph.documentColorSpace
)
state.glContext = result.glContext
+ state.glHandle = result.glHandle
+ state.glCanvas = result.glHandle === null ? null : canvas
state.presentation = result.presentation
options?.onPresentation?.(result.presentation)
const surface = result.surface
@@ -194,7 +220,7 @@ export function createCanvasSurfaceManager({
renderLoop.pause()
if (state.renderer) editor.removeCanvasRenderer(state.renderer)
state.renderer?.destroy()
- state.glContext?.delete()
+ releaseGLContext()
}
return {
diff --git a/packages/vue/src/editor/selection-capabilities/use.ts b/packages/vue/src/editor/selection-capabilities/use.ts
index d10a36595..0dfdcbb3f 100644
--- a/packages/vue/src/editor/selection-capabilities/use.ts
+++ b/packages/vue/src/editor/selection-capabilities/use.ts
@@ -1,4 +1,4 @@
-import { computed, shallowRef, triggerRef } from 'vue'
+import { computed, shallowRef } from 'vue'
import { canMakeBooleanSourceNode, hasVisibleStrokeSourceNode } from '@open-pencil/core/canvas'
@@ -16,8 +16,12 @@ import { useSceneComputed } from '#vue/internal/scene-computed/use'
export function useSelectionCapabilities() {
const selection = useSelectionState()
const { editor, selectedIds, selectedNode, selectedCount, hasSelection } = selection
- const history = shallowRef(editor.undo)
- useEditorEvent('history:changed', () => triggerRef(history))
+ // A change counter, not the undo manager itself: an editor that follows the active document
+ // must answer for the document that is active now.
+ const historyVersion = shallowRef(0)
+ useEditorEvent('history:changed', () => {
+ historyVersion.value++
+ })
const selectedNodesCanFlatten = useSceneComputed(() => {
const nodes = editor.getSelectedNodes()
@@ -77,8 +81,12 @@ export function useSelectionCapabilities() {
),
// In vector edit mode, undo/redo route to the session-local history —
// keep the commands enabled so the shortcut reaches them.
- canUndo: useSceneComputed(() => editor.state.nodeEditState != null || history.value.canUndo),
- canRedo: useSceneComputed(() => editor.state.nodeEditState != null || history.value.canRedo),
+ canUndo: useSceneComputed(
+ () => historyVersion.value >= 0 && (editor.state.nodeEditState != null || editor.undo.canUndo)
+ ),
+ canRedo: useSceneComputed(
+ () => historyVersion.value >= 0 && (editor.state.nodeEditState != null || editor.undo.canRedo)
+ ),
canZoomToSelection: computed(() => hasSelection.value)
}
}
diff --git a/src/App.vue b/src/App.vue
index 7b87b582b..2ba2bf4aa 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -8,7 +8,7 @@ import { computed, onMounted } from 'vue'
import { provideEditor, useI18n } from '@open-pencil/vue'
import { useDocumentCloseProtection } from '@/app/document/close/use'
-import { useEditorStore } from '@/app/editor/active-store'
+import { useFollowingEditorStore } from '@/app/editor/active-store'
import { animationsEnabled } from '@/app/shell/motion'
import { useAppTheme } from '@/app/shell/theme'
import { toast } from '@/app/shell/ui'
@@ -23,7 +23,6 @@ import SettingsDialog from '@/components/settings/SettingsDialog.vue'
import AppShell from '@/components/shell/AppShell.vue'
import Toaster from '@/components/shell/Toaster.vue'
-const store = useEditorStore()
const { updates, locale } = useI18n()
useHead({
@@ -34,7 +33,7 @@ useHead({
}
})
-provideEditor(store)
+provideEditor(useFollowingEditorStore())
useAppTheme()
useDocumentCloseProtection()
useEventListener(window, 'pagehide', () => {
diff --git a/src/app/ai/chat/history/controller.ts b/src/app/ai/chat/history/controller.ts
index c7d1228a6..6f1228591 100644
--- a/src/app/ai/chat/history/controller.ts
+++ b/src/app/ai/chat/history/controller.ts
@@ -25,7 +25,8 @@ export function createConversationHistory<TChat extends HistoryChat>(
const readOnly = ref(false)
const busy = ref(false)
let ownerRecoveryId: string | null = null
- let owner: ChatDocumentEditor | null = null
+ // Weak, so the history does not keep a closed document's editor alive.
+ let owner: WeakRef<ChatDocumentEditor> | null = null
let operation: Promise<unknown> = Promise.resolve()
const session = createHistorySession(() => runtime.resetChat())
const { flush, storageError } = createHistoryPersistence({
@@ -61,10 +62,11 @@ export function createConversationHistory<TChat extends HistoryChat>(
}
async function activate(conversation: Conversation) {
- owner = runtime.getEditor()
- ownerRecoveryId = owner.getRecoveryId()
+ const editor = runtime.getEditor()
+ owner = new WeakRef(editor)
+ ownerRecoveryId = editor.getRecoveryId()
session.restoreInterrupted(conversation.interrupted)
- readOnly.value = conversation.documentId !== chatDocumentId(owner)
+ readOnly.value = conversation.documentId !== chatDocumentId(editor)
current.value = conversation
messages.value = restoreMessages(conversation.messages)
if (conversation.messages.length || conversation.titleSource !== 'fallback') {
@@ -93,7 +95,7 @@ export function createConversationHistory<TChat extends HistoryChat>(
function isIdentityChange(editor: ChatDocumentEditor, documentId: string) {
return (
- owner === editor &&
+ owner?.deref() === editor &&
ownerRecoveryId === editor.getRecoveryId() &&
current.value &&
!readOnly.value &&
@@ -115,7 +117,7 @@ export function createConversationHistory<TChat extends HistoryChat>(
if (isIdentityChange(editor, documentId)) await reassignDocument(editor, documentId)
if (current.value?.documentId === documentId) {
readOnly.value = false
- owner = editor
+ owner = new WeakRef(editor)
ownerRecoveryId = editor.getRecoveryId()
return
}
@@ -129,7 +131,7 @@ export function createConversationHistory<TChat extends HistoryChat>(
function ensureChat() {
return serialize(async () => {
- if (readOnly.value && owner === runtime.getEditor()) return null
+ if (readOnly.value && owner?.deref() === runtime.getEditor()) return null
await loadDocument()
// A restored transcript does not restore an external agent session.
if (
diff --git a/src/app/editor/active-store/index.ts b/src/app/editor/active-store/index.ts
index e69989199..366248276 100644
--- a/src/app/editor/active-store/index.ts
+++ b/src/app/editor/active-store/index.ts
@@ -1,4 +1,4 @@
-import { shallowRef, triggerRef } from 'vue'
+import { shallowRef, triggerRef, watch } from 'vue'
import type { EditorStore } from '@/app/editor/session'
@@ -33,3 +33,40 @@ const storeProxy = new Proxy({} as EditorStore, {
export function useEditorStore(): EditorStore {
return storeProxy
}
+
+/**
+ * Subscribes to the active store and moves the subscription along when another tab becomes
+ * active, for consumers that outlive any one document.
+ */
+const onActiveEditorEvent: EditorStore['onEditorEvent'] = (event, handler) => {
+ let stop = storeRef.value?.onEditorEvent(event, handler) ?? null
+ const stopFollowing = watch(
+ storeRef,
+ (store) => {
+ stop?.()
+ stop = store?.onEditorEvent(event, handler) ?? null
+ },
+ { flush: 'sync' }
+ )
+ return () => {
+ stopFollowing()
+ stop?.()
+ stop = null
+ }
+}
+
+const followingStoreProxy = new Proxy({} as EditorStore, {
+ get(_, prop) {
+ if (prop === 'onEditorEvent') return onActiveEditorEvent
+ return Reflect.get(getActiveEditorStore(), prop)
+ }
+})
+
+/**
+ * The editor for app-level UI that outlives tabs, such as menus, shortcuts and banners. Its
+ * event subscriptions follow the active tab, so they neither miss later documents' events nor
+ * keep a closed document alive. UI inside a tab gets that tab's own store instead.
+ */
+export function useFollowingEditorStore(): EditorStore {
+ return followingStoreProxy
+}
diff --git a/src/app/editor/session/create.ts b/src/app/editor/session/create.ts
index e066c8f73..465c523e4 100644
--- a/src/app/editor/session/create.ts
+++ b/src/app/editor/session/create.ts
@@ -27,6 +27,7 @@ import {
createEditorStoreModules,
defineEditorStoreAccessors
} from '@/app/editor/session/modules'
+import { scopedStoreFactory } from '@/app/editor/session/scope'
import { createInitialAppEditorState, type AppEditorState } from '@/app/editor/session/types'
import { notificationMessages } from '@/app/i18n/notifications'
import { createDeferred } from '@/app/runtime/deferred'
@@ -36,7 +37,7 @@ import { IS_BROWSER, IS_TAURI } from '@/constants'
export { EDITOR_TOOLS as TOOLS, TOOL_SHORTCUTS } from '@open-pencil/core/editor'
export type { EditorToolDef as ToolDef, Tool } from '@open-pencil/core/editor'
-export function createEditorStore(initialGraph?: SceneGraph) {
+function buildEditorStore(initialGraph?: SceneGraph) {
const graph = initialGraph ?? new SceneGraph()
const state = shallowReactive<AppEditorState>(createInitialAppEditorState(graph.getPages()[0].id))
@@ -252,6 +253,8 @@ export function createEditorStore(initialGraph?: SceneGraph) {
return store
}
+export const createEditorStore = scopedStoreFactory(buildEditorStore)
+
export type EditorStore = ReturnType<typeof createEditorStore>
export { getActiveEditorStore, setActiveEditorStore, useEditorStore }
diff --git a/src/app/editor/session/scope.ts b/src/app/editor/session/scope.ts
new file mode 100644
index 000000000..ffa8c909c
--- /dev/null
+++ b/src/app/editor/session/scope.ts
@@ -0,0 +1,28 @@
+import { effectScope } from 'vue'
+
+/**
+ * Wraps a store factory so each store runs in an effect scope of its own, stopped by `dispose`.
+ * Effects a store creates inside a component's setup would otherwise join that component's
+ * scope and keep the store, with its whole document, alive after its tab closes.
+ */
+export function scopedStoreFactory<Args extends unknown[], Store extends { dispose(): void }>(
+ build: (...args: Args) => Store
+): (...args: Args) => Store {
+ return (...args) => {
+ const scope = effectScope(true)
+ let store: Store | undefined
+ try {
+ store = scope.run(() => build(...args))
+ } catch (error) {
+ scope.stop()
+ throw error
+ }
+ if (!store) throw new Error('Editor store scope is inactive')
+ const dispose = store.dispose.bind(store)
+ store.dispose = () => {
+ dispose()
+ scope.stop()
+ }
+ return store
+ }
+}
diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vue
index d47b335c9..095726545 100644
--- a/src/components/editor/EditorWorkspace.vue
+++ b/src/components/editor/EditorWorkspace.vue
@@ -2,7 +2,7 @@
import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'
import { tv } from 'tailwind-variants'
-import { formatShortcut, useI18n, useViewportKind } from '@open-pencil/vue'
+import { formatShortcut, provideEditor, useI18n, useViewportKind } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
import { appRuntimeConfig } from '@/app/runtime/config'
@@ -24,6 +24,11 @@ import splitterTheme from '@/theme/splitter'
const showChrome = appRuntimeConfig.showChrome
const store = useEditorStore()
+// WorkspaceView keys this view by tab, so the tab's own store is fixed for its lifetime. Its
+// editor UI stays bound to that document rather than the app-level editor, which follows the
+// active tab and would move these subscriptions to the next document when this tab closes.
+const tab = activeTab.value
+if (tab) provideEditor(tab.store)
const { editor } = useI18n()
const { isMobile } = useViewportKind()
const initialEditorLayout = loadEditorLayout()
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index 355bcafbf..f5215ae75 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -47,11 +47,12 @@ const shouldCreateHome =
!appRuntimeConfig.test &&
!route.meta.demo &&
(isTauri() || appRuntimeConfig.recentFiles)
-let firstTab = activeTab.value
-if (!firstTab) firstTab = shouldCreateHome ? createHomeTab() : createTab()
-
-if (createdInitialTab && route.meta.demo && !appRuntimeConfig.test) {
- void createDemoShapes(firstTab.store)
+// Block-scoped so the view does not keep the first tab's store after that tab closes.
+{
+ const firstTab = activeTab.value ?? (shouldCreateHome ? createHomeTab() : createTab())
+ if (createdInitialTab && route.meta.demo && !appRuntimeConfig.test) {
+ void createDemoShapes(firstTab.store)
+ }
}
useHead({ title: route.meta.demo ? 'Demo' : undefined })
@@ -185,6 +186,6 @@ onUnmounted(() => {
<CommandPalette />
<TabBar />
<HomeWorkspace v-show="activeTab?.kind === 'home'" @new-document="createDocumentInCurrentTab" />
- <EditorWorkspace v-if="activeTab?.kind !== 'home'" />
+ <EditorWorkspace v-if="activeTab && activeTab.kind !== 'home'" :key="activeTab.id" />
</div>
</template>
diff --git a/tests/app/editor/session/scope.test.ts b/tests/app/editor/session/scope.test.ts
new file mode 100644
index 000000000..410788827
--- /dev/null
+++ b/tests/app/editor/session/scope.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, test } from 'bun:test'
+
+import { getCurrentScope, type EffectScope } from 'vue'
+
+import { scopedStoreFactory } from '@/app/editor/session/scope'
+
+describe('scopedStoreFactory', () => {
+ test('stops the store scope after the store disposes', () => {
+ let scope: EffectScope | undefined
+ let disposed = 0
+ const create = scopedStoreFactory(() => {
+ scope = getCurrentScope()
+ return { dispose: () => disposed++ }
+ })
+
+ create().dispose()
+
+ expect(disposed).toBe(1)
+ expect(scope?.active).toBe(false)
+ })
+
+ test('stops the store scope when building the store throws', () => {
+ let scope: EffectScope | undefined
+ const create = scopedStoreFactory((): { dispose(): void } => {
+ scope = getCurrentScope()
+ throw new Error('build failed')
+ })
+
+ expect(() => create()).toThrow('build failed')
+ expect(scope?.active).toBe(false)
+ })
+})
diff --git a/tests/e2e/app/closed-documents.spec.ts b/tests/e2e/app/closed-documents.spec.ts
new file mode 100644
index 000000000..5215189c1
--- /dev/null
+++ b/tests/e2e/app/closed-documents.spec.ts
@@ -0,0 +1,59 @@
+import { fileURLToPath } from 'node:url'
+
+import { expect, test } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+const FIXTURE = 'gold-preview.fig'
+
+// A closed tab must release its document. CanvasKit's WebGL context table, an editor's global
+// text measurer, store effects created during a component's setup, and app-level event
+// subscriptions each kept every closed document alive: store, graph, canvas, and UI tree.
+test('documents closed in tabs are released', async ({ page }) => {
+ test.setTimeout(90_000)
+ await page.route(`**/__fixtures/${FIXTURE}`, (route) =>
+ route.fulfill({ path: fileURLToPath(new URL(`../../fixtures/${FIXTURE}`, import.meta.url)) })
+ )
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const cdp = await page.context().newCDPSession(page)
+ await page.evaluate(() => Reflect.set(window, '__closedGraphs', []))
+
+ for (let cycle = 0; cycle < 3; cycle++) {
+ await page.evaluate(async (fixture) => {
+ const tabs = await import('/src/app/tabs/index.ts')
+ const response = await fetch(`/__fixtures/${fixture}`)
+ await tabs.openFileInNewTab(new File([await response.arrayBuffer()], fixture))
+ }, FIXTURE)
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ return Boolean(store && store.graph.nodes.size > 100 && !store.state.preparation)
+ })
+ )
+ .toBe(true)
+ await page.evaluate(async () => {
+ const tabs = await import('/src/app/tabs/index.ts')
+ const store = tabs.getActiveStore()
+ const graphs = Reflect.get(window, '__closedGraphs') as WeakRef<object>[]
+ graphs.push(new WeakRef(store.graph))
+ await tabs.closeTab(tabs.getActiveTabId(), 'discard')
+ })
+ }
+
+ await expect
+ .poll(
+ async () => {
+ await cdp.send('HeapProfiler.collectGarbage')
+ return page.evaluate(
+ () =>
+ (Reflect.get(window, '__closedGraphs') as WeakRef<object>[]).filter((ref) =>
+ ref.deref()
+ ).length
+ )
+ },
+ { timeout: 15_000 }
+ )
+ .toBe(0)
+})