Skip to content

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

ci: shard unit tests by owner and cut the quick suite from 100 s to 13 s (#715)

Danila Poyarkov92977234cf14
diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml
index 694c5acd0..32ffc6a81 100644
--- a/.github/actions/setup-bun/action.yml
+++ b/.github/actions/setup-bun/action.yml
@@ -11,6 +11,10 @@ inputs:
description: Pull Git LFS files before installing dependencies.
required: false
default: 'false'
+ lfs-include:
+ description: Comma-separated `git lfs pull --include` patterns. Empty pulls every LFS object.
+ required: false
+ default: ''
cache-save:
description: Save the dependency cache; set false for other jobs sharing the same cache key.
@@ -27,10 +31,17 @@ runs:
- name: Pull LFS files
if: inputs.lfs == 'true'
shell: bash
+ env:
+ LFS_INCLUDE: ${{ inputs.lfs-include }}
run: |
git lfs install --force
- git lfs pull
- head -c 4 tests/fixtures/material3.fig | xxd
+ if [ -n "$LFS_INCLUDE" ]; then
+ git lfs pull --include="$LFS_INCLUDE"
+ else
+ git lfs pull
+ head -c 4 tests/fixtures/material3.fig | xxd
+ fi
+ head -c 4 tests/fixtures/gold-preview.fig | xxd
- uses: oven-sh/setup-bun@v2
with:
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e5ea33473..5e2a8bb9f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -230,8 +230,8 @@ jobs:
strategy:
fail-fast: true
matrix:
- group: [app, dom, editor, fig, render, scene, vue]
- name: Engine tests — ${{ matrix.group }}
+ group: [app, cli, core, dom, fig, mcp, render, scene-graph, vue]
+ name: Unit tests — ${{ matrix.group }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
with:
@@ -240,21 +240,14 @@ jobs:
- uses: ./.github/actions/setup-bun
with:
lfs: 'true'
+ # Quick shards read only the small fixtures; heavy-tests.yml pulls the large .fig corpora.
+ lfs-include: tests/fixtures/gold-preview.fig,tests/fixtures/circle-text.fig,tests/fixtures/fonts/*
- name: Build shared Core test dependency
run: bun --filter @open-pencil/core build
- - name: Run ${{ matrix.group }} engine tests
- shell: bash
- run: |
- mapfile -t test_files < <(bun tools/unit-tests/src/list.ts "${{ matrix.group }}")
- if [ "${#test_files[@]}" -eq 0 ]; then
- echo "No tests found for shard ${{ matrix.group }}"
- exit 0
- fi
- bun test "${test_files[@]}"
- env:
- BUN_HEAVY_TESTS: 'false'
+ - name: Run ${{ matrix.group }} unit tests
+ run: bun tools/unit-tests/src/run.ts "${{ matrix.group }}"
result:
name: CI result
diff --git a/.github/workflows/heavy-tests.yml b/.github/workflows/heavy-tests.yml
index 7ad7ccfae..ecfb71509 100644
--- a/.github/workflows/heavy-tests.yml
+++ b/.github/workflows/heavy-tests.yml
@@ -10,7 +10,8 @@ concurrency:
cancel-in-progress: true
jobs:
- fixture-heavy-unit-tests:
+ unit-tests:
+ name: Heavy and isolated unit tests
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
@@ -24,13 +25,11 @@ jobs:
run: bun run build:packages
- name: Heavy fixture unit tests
- shell: bash
- run: |
- mapfile -t test_files < <(bun tools/unit-tests/src/list.ts all --heavy-only)
- if [ "${#test_files[@]}" -eq 0 ]; then
- echo "No heavy unit tests found"
- exit 0
- fi
- bun test --timeout 180000 "${test_files[@]}"
- env:
- BUN_HEAVY_TESTS: 'true'
+ run: bun run test:unit:heavy
+
+ # Fresh global object per file: a suite that only passes because an
+ # earlier file initialized a codec, loaded a font or left a database
+ # open fails here instead of flaking in a PR shard.
+ - name: Quick unit tests with per-file isolation
+ if: ${{ !cancelled() }}
+ run: bun run test:unit:isolated
diff --git a/AGENTS.md b/AGENTS.md
index 1071683fe..896709d8f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -150,7 +150,7 @@ PR titles use Conventional Commits because GitHub uses them as merge subjects. T
- Put code and tests in the established owning domain; inspect nearby structure before adding files.
- `bun run check:arch` enforces boundaries: use public workspace exports, keep Core framework-neutral, keep app services out of views/shared UI, and keep property-panel internals scoped to that panel.
-- Follow the canonical [testing architecture](packages/docs/development/testing.md): package-local tests mirror source domains; central app tests mirror `src/app/**`; central integration requires a genuinely cross-owner contract. E2E follows user workflows; native and Figma acceptance remain explicit exceptions. Existing `tests/engine/**` domains migrate together with runner discovery—do not create competing homes or undiscovered suites. Owner-local helpers/fixtures stay local; only genuinely shared support is central. Specs use domain drivers/probes, not scattered Window/store traversal or unrestricted evaluator wrappers. Test contracts, not source text; never commit temporary/profile specs.
+- Follow the canonical [testing architecture](packages/docs/development/testing.md): package-local tests mirror source domains; central app tests mirror `src/app/**`; central integration requires a genuinely cross-owner contract. E2E follows user workflows; native and Figma acceptance remain explicit exceptions. Existing `tests/engine/**` domains migrate together with runner discovery—`tools/unit-tests/src/shards.ts` lists each owner's canonical home and its current `tests/engine` directories, so a move is a `git mv` plus imports; do not create competing homes or undiscovered suites. Owner-local helpers/fixtures stay local; only genuinely shared support is central. Specs use domain drivers/probes, not scattered Window/store traversal or unrestricted evaluator wrappers. Test contracts, not source text; never commit temporary/profile specs.
### File and folder naming
@@ -255,7 +255,7 @@ Keep responsibilities distinct: engine tests cover state contracts, Playwright b
- Section/frame title text never scales — render at fixed font size, ellipsize to fit
- Rulers are rendered on the canvas (not DOM), with selection range badges that don't overlap tick numbers
- Remote cursors: Figma-style colored arrows with white border + name pill, rendered in screen space
-- Pixel-affecting renderer features need committed visual coverage, not just mock/geometry assertions. Add or update a Playwright canvas snapshot for changes to fills, gradients, images, blend modes, masks, boolean geometry, corners, strokes, shadows, blur, text rendering, or demo showcase scenes. Use targeted snapshot updates such as `bun run test tests/e2e/canvas/renderer-visuals.spec.ts --update-snapshots` and then rerun the same test without `--update-snapshots`.
+- Pixel-affecting renderer features need committed visual coverage, not just mock/geometry assertions. Add or update a Playwright canvas snapshot for changes to fills, gradients, images, blend modes, masks, boolean geometry, corners, strokes, shadows, blur, text rendering, or demo showcase scenes. Use targeted snapshot updates such as `bun run test tests/e2e/canvas/fill-modes-visual.spec.ts --update-snapshots` and then rerun the same test without `--update-snapshots`.
## Scene graph
diff --git a/package.json b/package.json
index 49070b9f2..007477bc2 100644
--- a/package.json
+++ b/package.json
@@ -63,10 +63,11 @@
"test:figma": "OPENPENCIL_TEST_SERVER=app playwright test --project=figma",
"figma:debug": "open -a Figma --args --remote-debugging-port=9222",
"typecheck": "tsgo --noEmit && bun run check:vue",
- "test:unit": "bun test ./tests/engine",
- "test:unit:quick": "bash -lc 'mapfile -t test_files < <(bun tools/unit-tests/src/list.ts all); bun test \"${test_files[@]}\"'",
- "test:unit:heavy": "bash -lc 'mapfile -t test_files < <(bun tools/unit-tests/src/list.ts all --heavy-only); bun test --timeout 180000 \"${test_files[@]}\"'",
- "test:coverage": "bun test --coverage ./tests/engine",
+ "test:unit": "bun tools/unit-tests/src/run.ts all --include-heavy",
+ "test:unit:quick": "bun tools/unit-tests/src/run.ts all -- --parallel",
+ "test:unit:isolated": "bun tools/unit-tests/src/run.ts all -- --isolate",
+ "test:unit:heavy": "bun tools/unit-tests/src/run.ts all --heavy-only -- --timeout 180000",
+ "test:coverage": "bun tools/unit-tests/src/run.ts all --include-heavy -- --coverage",
"test:type-shapes": "bun tools/type-shapes/src/index.ts",
"test:tools": "bun tools/test.ts && bun --filter @open-pencil/harness test",
"test:dupes": "jscpd packages/scene-graph/src packages/pen/src packages/core/src packages/cli/src packages/dom-css/src src --min-lines 5 --min-tokens 50 --format typescript --threshold 0",
@@ -238,5 +239,5 @@
"protobufjs": "7.5.5",
"websocket-driver": "0.7.5"
},
- "packageManager": "[email protected]"
+ "packageManager": "[email protected]"
}
diff --git a/packages/core/src/figma-api/accessors/strokes.ts b/packages/core/src/figma-api/accessors/strokes.ts
new file mode 100644
index 000000000..df41cd68f
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/strokes.ts
@@ -0,0 +1,107 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ nodeId,
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import {
+ setFirstStrokeAlign,
+ setFirstStrokeWeight,
+ setIndependentStrokeWeight
+} from '#core/figma-api/strokes'
+
+type IndependentWeightField =
+ | 'borderTopWeight'
+ | 'borderRightWeight'
+ | 'borderBottomWeight'
+ | 'borderLeftWeight'
+
+function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {
+ return target[internals.graph] as SceneGraph
+}
+
+function independentWeight(internals: NodeProxyInternals, field: IndependentWeightField) {
+ return {
+ get(this: ProxyThis): number {
+ return raw(this, internals)[field]
+ },
+ set(this: ProxyThis, value: number) {
+ setIndependentStrokeWeight(graph(this, internals), nodeId(this, internals), field, value)
+ }
+ }
+}
+
+export function installStrokeNodeProxyAccessors(
+ prototype: object,
+ internals: NodeProxyInternals
+): void {
+ Object.defineProperties(prototype, {
+ strokeWeight: {
+ get(this: ProxyThis): number {
+ const strokes = raw(this, internals).strokes
+ return strokes.length > 0 ? strokes[0].weight : 0
+ },
+ set(this: ProxyThis, value: number) {
+ setFirstStrokeWeight(graph(this, internals), raw(this, internals), value)
+ }
+ },
+ strokeAlign: {
+ get(this: ProxyThis): string {
+ const strokes = raw(this, internals).strokes
+ return strokes.length > 0 ? strokes[0].align : 'INSIDE'
+ },
+ set(this: ProxyThis, value: string) {
+ setFirstStrokeAlign(graph(this, internals), raw(this, internals), value)
+ }
+ },
+ dashPattern: {
+ get(this: ProxyThis): readonly number[] {
+ return Object.freeze([...raw(this, internals).dashPattern])
+ },
+ set(this: ProxyThis, value: readonly number[]) {
+ updateNode(this, internals, { dashPattern: [...value] })
+ }
+ },
+ strokeCap: {
+ get(this: ProxyThis): string {
+ return raw(this, internals).strokeCap
+ },
+ set(this: ProxyThis, value: string) {
+ const strokeCap = value as SceneNode['strokeCap']
+ const node = raw(this, internals)
+ updateNode(this, internals, {
+ strokeCap,
+ strokes: node.strokes.map((stroke) => ({ ...stroke, cap: strokeCap }))
+ })
+ }
+ },
+ strokeJoin: {
+ get(this: ProxyThis): string {
+ return raw(this, internals).strokeJoin
+ },
+ set(this: ProxyThis, value: string) {
+ const strokeJoin = value as SceneNode['strokeJoin']
+ const node = raw(this, internals)
+ updateNode(this, internals, {
+ strokeJoin,
+ strokes: node.strokes.map((stroke) => ({ ...stroke, join: strokeJoin }))
+ })
+ }
+ },
+ strokeMiterLimit: {
+ get(this: ProxyThis): number {
+ return raw(this, internals).strokeMiterLimit
+ },
+ set(this: ProxyThis, value: number) {
+ updateNode(this, internals, { strokeMiterLimit: value })
+ }
+ },
+ strokeTopWeight: independentWeight(internals, 'borderTopWeight'),
+ strokeBottomWeight: independentWeight(internals, 'borderBottomWeight'),
+ strokeLeftWeight: independentWeight(internals, 'borderLeftWeight'),
+ strokeRightWeight: independentWeight(internals, 'borderRightWeight')
+ })
+}
diff --git a/packages/core/src/figma-api/accessors/text.ts b/packages/core/src/figma-api/accessors/text.ts
new file mode 100644
index 000000000..db6f7fafc
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/text.ts
@@ -0,0 +1,64 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ nodeId,
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import type { FigmaFontName } from '#core/figma-api/fonts'
+import { getFontName, setFontName } from '#core/figma-api/text'
+
+function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {
+ return target[internals.graph] as SceneGraph
+}
+
+/** Getter/setter pair for a text property stored verbatim on the node. */
+function field<Field extends keyof SceneNode>(internals: NodeProxyInternals, name: Field) {
+ return {
+ get(this: ProxyThis): SceneNode[Field] {
+ return raw(this, internals)[name]
+ },
+ set(this: ProxyThis, value: SceneNode[Field]) {
+ updateNode(this, internals, { [name]: value } as Partial<SceneNode>)
+ }
+ }
+}
+
+export function installTextNodeProxyAccessors(
+ prototype: object,
+ internals: NodeProxyInternals
+): void {
+ Object.defineProperties(prototype, {
+ characters: {
+ get(this: ProxyThis): string {
+ return raw(this, internals).text
+ },
+ set(this: ProxyThis, value: string) {
+ updateNode(this, internals, { text: value })
+ }
+ },
+ fontName: {
+ get(this: ProxyThis): FigmaFontName {
+ return getFontName(raw(this, internals))
+ },
+ set(this: ProxyThis, value: FigmaFontName) {
+ setFontName(graph(this, internals), nodeId(this, internals), value)
+ }
+ },
+ fontSize: field(internals, 'fontSize'),
+ fontWeight: field(internals, 'fontWeight'),
+ textAlignHorizontal: field(internals, 'textAlignHorizontal'),
+ textAlignVertical: field(internals, 'textAlignVertical'),
+ textDirection: field(internals, 'textDirection'),
+ textAutoResize: field(internals, 'textAutoResize'),
+ letterSpacing: field(internals, 'letterSpacing'),
+ lineHeight: field(internals, 'lineHeight'),
+ textCase: field(internals, 'textCase'),
+ textDecoration: field(internals, 'textDecoration'),
+ maxLines: field(internals, 'maxLines'),
+ textTruncation: field(internals, 'textTruncation'),
+ autoRename: field(internals, 'autoRename')
+ })
+}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 97b031044..91e528ea7 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -21,6 +21,8 @@ import { assertNodeEditable } from '#core/editor/capabilities'
import { installBasicNodeProxyAccessors } from './accessors/basic'
import { installLayoutNodeProxyAccessors } from './accessors/layout'
+import { installStrokeNodeProxyAccessors } from './accessors/strokes'
+import { installTextNodeProxyAccessors } from './accessors/text'
import { installVariableModeNodeProxyAccessors } from './accessors/variables'
import {
installVectorNodeProxyAccessors,
@@ -33,7 +35,6 @@ import type { FigmaFontName } from './fonts'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
import * as PluginData from './plugin-data'
import { nodeProxyToJSON } from './serialization'
-import { setFirstStrokeAlign, setFirstStrokeWeight, setIndependentStrokeWeight } from './strokes'
import * as TextProxy from './text'
import * as Traversal from './traversal'
import type { FigmaTransform } from './types'
@@ -123,6 +124,33 @@ export class FigmaNodeProxy {
declare readonly explicitVariableModes: Readonly<Record<string, string>>
declare readonly resolvedVariableModes: Readonly<Record<string, string>>
+ declare strokeWeight: number
+ declare strokeAlign: string
+ declare dashPattern: readonly number[]
+ declare strokeCap: string
+ declare strokeJoin: string
+ declare strokeMiterLimit: number
+ declare strokeTopWeight: number
+ declare strokeBottomWeight: number
+ declare strokeLeftWeight: number
+ declare strokeRightWeight: number
+
+ declare characters: string
+ declare fontSize: number
+ declare fontName: FigmaFontName
+ declare fontWeight: number
+ declare textAlignHorizontal: string
+ declare textAlignVertical: string
+ declare textDirection: string
+ declare textAutoResize: string
+ declare letterSpacing: number
+ declare lineHeight: number | null
+ declare textCase: string
+ declare textDecoration: string
+ declare maxLines: number | null
+ declare textTruncation: string
+ declare autoRename: boolean
+
constructor(id: string, graph: SceneGraph, api: NodeProxyHost) {
this[INTERNAL_ID] = id
this[INTERNAL_GRAPH] = graph
@@ -150,234 +178,6 @@ export class FigmaNodeProxy {
return n
}
- // --- Stroke details ---
-
- get strokeWeight(): number {
- const s = this._raw().strokes
- return s.length > 0 ? s[0].weight : 0
- }
-
- set strokeWeight(v: number) {
- setFirstStrokeWeight(this[INTERNAL_GRAPH], this._raw(), v)
- }
-
- get strokeAlign(): string {
- const s = this._raw().strokes
- return s.length > 0 ? s[0].align : 'INSIDE'
- }
-
- set strokeAlign(v: string) {
- setFirstStrokeAlign(this[INTERNAL_GRAPH], this._raw(), v)
- }
-
- get dashPattern(): readonly number[] {
- return Object.freeze([...this._raw().dashPattern])
- }
-
- set dashPattern(v: readonly number[]) {
- this._update({ dashPattern: [...v] })
- }
-
- get strokeCap(): string {
- return this._raw().strokeCap
- }
-
- set strokeCap(v: string) {
- const strokeCap = v as SceneNode['strokeCap']
- const node = this._raw()
- this._update({
- strokeCap,
- strokes: node.strokes.map((stroke) => ({ ...stroke, cap: strokeCap }))
- })
- }
-
- get strokeJoin(): string {
- return this._raw().strokeJoin
- }
-
- set strokeJoin(v: string) {
- const strokeJoin = v as SceneNode['strokeJoin']
- const node = this._raw()
- this._update({
- strokeJoin,
- strokes: node.strokes.map((stroke) => ({ ...stroke, join: strokeJoin }))
- })
- }
-
- get strokeMiterLimit(): number {
- return this._raw().strokeMiterLimit
- }
-
- set strokeMiterLimit(v: number) {
- this._update({ strokeMiterLimit: v })
- }
-
- get strokeTopWeight(): number {
- return this._raw().borderTopWeight
- }
-
- set strokeTopWeight(v: number) {
- setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderTopWeight', v)
- }
-
- get strokeBottomWeight(): number {
- return this._raw().borderBottomWeight
- }
-
- set strokeBottomWeight(v: number) {
- setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderBottomWeight', v)
- }
-
- get strokeLeftWeight(): number {
- return this._raw().borderLeftWeight
- }
-
- set strokeLeftWeight(v: number) {
- setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderLeftWeight', v)
- }
-
- get strokeRightWeight(): number {
- return this._raw().borderRightWeight
- }
-
- set strokeRightWeight(v: number) {
- setIndependentStrokeWeight(this[INTERNAL_GRAPH], this[INTERNAL_ID], 'borderRightWeight', v)
- }
-
- // --- Text ---
-
- get characters(): string {
- return this._raw().text
- }
-
- set characters(v: string) {
- this._update({ text: v })
- }
-
- get fontSize(): number {
- return this._raw().fontSize
- }
-
- set fontSize(v: number) {
- this._update({ fontSize: v })
- }
-
- get fontName(): FigmaFontName {
- return TextProxy.getFontName(this._raw())
- }
-
- set fontName(v: FigmaFontName) {
- TextProxy.setFontName(this[INTERNAL_GRAPH], this[INTERNAL_ID], v)
- }
-
- get fontWeight(): number {
- return this._raw().fontWeight
- }
-
- set fontWeight(v: number) {
- this._update({ fontWeight: v })
- }
-
- get textAlignHorizontal(): string {
- return this._raw().textAlignHorizontal
- }
-
- set textAlignHorizontal(v: string) {
- this._update({
- textAlignHorizontal: v as SceneNode['textAlignHorizontal']
- })
- }
-
- get textDirection(): string {
- return this._raw().textDirection
- }
-
- set textDirection(v: string) {
- this._update({
- textDirection: v as SceneNode['textDirection']
- })
- }
-
- get textAlignVertical(): string {
- return this._raw().textAlignVertical
- }
-
- set textAlignVertical(v: string) {
- this._update({
- textAlignVertical: v as SceneNode['textAlignVertical']
- })
- }
-
- get textAutoResize(): string {
- return this._raw().textAutoResize
- }
-
- set textAutoResize(v: string) {
- this._update({
- textAutoResize: v as SceneNode['textAutoResize']
- })
- }
-
- get letterSpacing(): number {
- return this._raw().letterSpacing
- }
-
- set letterSpacing(v: number) {
- this._update({ letterSpacing: v })
- }
-
- get lineHeight(): number | null {
- return this._raw().lineHeight
- }
-
- set lineHeight(v: number | null) {
- this._update({ lineHeight: v })
- }
-
- get textCase(): string {
- return this._raw().textCase
- }
-
- set textCase(v: string) {
- this._update({ textCase: v as SceneNode['textCase'] })
- }
-
- get textDecoration(): string {
- return this._raw().textDecoration
- }
-
- set textDecoration(v: string) {
- this._update({
- textDecoration: v as SceneNode['textDecoration']
- })
- }
-
- get maxLines(): number | null {
- return this._raw().maxLines
- }
-
- set maxLines(v: number | null) {
- this._update({ maxLines: v })
- }
-
- get textTruncation(): string {
- return this._raw().textTruncation
- }
-
- set textTruncation(v: string) {
- this._update({
- textTruncation: v as SceneNode['textTruncation']
- })
- }
-
- get autoRename(): boolean {
- return this._raw().autoRename
- }
-
- set autoRename(v: boolean) {
- this._update({ autoRename: v })
- }
-
insertCharacters(start: number, characters: string): void {
TextProxy.insertCharacters(this[INTERNAL_GRAPH], this._raw(), start, characters)
}
@@ -599,6 +399,8 @@ const proxyInternals = {
api: INTERNAL_API
}
+installStrokeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
+installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)
installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)
diff --git a/packages/docs/development/testing.md b/packages/docs/development/testing.md
index efc585297..25bbd52b2 100644
--- a/packages/docs/development/testing.md
+++ b/packages/docs/development/testing.md
@@ -18,7 +18,13 @@ For example, `packages/core/src/canvas/text/prepared.ts` maps to `packages/core/
Core tests using SceneGraph still belong to Core. Central integration is for contracts without a single owning implementation, such as interoperability between published packages. Name that contract explicitly; do not use integration as a miscellaneous bucket.
-**Migration status:** much existing coverage remains under `tests/engine/**`, alongside package-local suites. The table is the agreed destination, not a claim that migration or runner support is complete. Until a domain migrates, extend its existing suite rather than create a second home. Move a domain together with its discovery/shard configuration and imports. Do not move files into an undiscovered directory. The repository-wide migration is separate from feature work.
+**Migration status:** much existing coverage remains under `tests/engine/**`, alongside package-local suites. The table is the agreed destination, not a claim that migration is complete. Until a domain migrates, extend its existing suite rather than create a second home. The repository-wide migration is separate from feature work.
+
+Discovery already covers the destinations: `tools/unit-tests/src/shards.ts` groups tests by owner and lists each owner's canonical home (`packages/<owner>/tests`, `tests/app`, `tests/integration`) together with the `tests/engine` directories it still owns, so `bun run test:unit` and the CI shards run a file from either place. Moving a domain is therefore a `git mv` plus import fixes; only a new owner or a new top-level home needs a shard entry. Do not move files into a directory the shard map does not list.
+
+`test:unit:quick` runs files in Bun worker processes (`--parallel`), which is the fastest local loop. CI shards still run each group in one process; `test:unit:isolated` (`--isolate`, also run nightly) gives every file a fresh global object and is the check to run when a suite passes alone but fails in a shard. Shards share one Bun process, so module-level state (a `fake-indexeddb/auto` import, an IndexedDB connection left open by `createEditorStore()`, a patched global) leaks into later files in the same shard. A package-local run (`bun test tests` inside the package) is a fresh process and will not reproduce that leak. Close what a test opens and restore what it patches.
+
+Run `bun --filter @open-pencil/core build` before unit tests. Files under `tests/` resolve `@open-pencil/core` and its subpaths to `packages/core/src` through the root tsconfig, but package sources (`packages/dom-css/src`, `packages/mcp/src`, …) use their own tsconfig, where `@open-pencil/core/<subpath>` falls back to the package `exports` and therefore to `dist`. One process can hold both copies; only `packages/vue` maps Core to `src`. Aligning the other package tsconfigs is a packaging change (it affects `tsdown` declaration output), not a test change.
## Test purpose
@@ -69,13 +75,15 @@ Existing global-based helpers are migration debt, not the preferred API. Migrate
Current commands:
-| Suite | Command |
-| ----------------- | ------------------------ |
-| Engine/unit | `bun run test:unit` |
-| App browser E2E | `bun run test` |
-| Storybook browser | `bun run test:storybook` |
-| Figma acceptance | `bun run test:figma` |
-| Native WebView | `bun run test:native` |
+| Suite | Command |
+| ------------------------------ | ---------------------------- |
+| Engine/unit | `bun run test:unit` |
+| Quick unit, parallel | `bun run test:unit:quick` |
+| Quick unit, per-file isolation | `bun run test:unit:isolated` |
+| App browser E2E | `bun run test` |
+| Storybook browser | `bun run test:storybook` |
+| Figma acceptance | `bun run test:figma` |
+| Native WebView | `bun run test:native` |
During implementation, run the affected unit files or one representative browser scenario. Inspect discovery changes without executing the whole suite when reorganizing files. Use the final CI gate after integration; do not rerun full suites for each edit. Report commands actually run, and distinguish focused coverage from full acceptance.
diff --git a/packages/mcp/src/browser-rpc.ts b/packages/mcp/src/browser-rpc.ts
index ed31dedde..82fb77954 100644
--- a/packages/mcp/src/browser-rpc.ts
+++ b/packages/mcp/src/browser-rpc.ts
@@ -15,6 +15,8 @@ const APP_NOT_CONNECTED_MESSAGE =
type BrowserRPCBridgeOptions = {
authToken: string | null
onConnectionChange: () => void
+ /** How long an RPC waits for the app to register before failing with APP_NOT_CONNECTED. Defaults to 10 s. */
+ appWaitTimeoutMs?: number
}
type ConnectionListener = (connected: boolean) => void
@@ -61,7 +63,11 @@ function createSettler<T>(resolve: (value: T) => void, reject: (error: Error) =>
}
}
-export function createBrowserRPCBridge({ authToken, onConnectionChange }: BrowserRPCBridgeOptions) {
+export function createBrowserRPCBridge({
+ authToken,
+ onConnectionChange,
+ appWaitTimeoutMs = APP_WAIT_TIMEOUT
+}: BrowserRPCBridgeOptions) {
const pending = new Map<string, PendingRequest>()
const clients = new Set<WebSocket>()
const connectionWaiters = new Set<PendingRequest>()
@@ -113,7 +119,7 @@ export function createBrowserRPCBridge({ authToken, onConnectionChange }: Browse
const timer = setTimeout(() => {
if (waiter) connectionWaiters.delete(waiter)
reject(new Error(APP_NOT_CONNECTED_MESSAGE))
- }, APP_WAIT_TIMEOUT)
+ }, appWaitTimeoutMs)
waiter = {
resolve: () => {
@@ -130,7 +136,7 @@ export function createBrowserRPCBridge({ authToken, onConnectionChange }: Browse
// race: if the browser registers between sendRPC's initial check and
// this point, notifyConnectionWaiters() will have already fired and
// cleared the set. Without this re-check, the waiter would stall for
- // APP_WAIT_TIMEOUT even though the browser is connected.
+ // appWaitTimeoutMs even though the browser is connected.
connectionWaiters.add(waiter)
if (browserWs && browserWs.readyState === browserWs.OPEN && browserRegistered) {
waiter.resolve(undefined)
diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts
index 246f32a1d..8d5ac6407 100644
--- a/packages/mcp/src/server.ts
+++ b/packages/mcp/src/server.ts
@@ -85,6 +85,12 @@ export interface ServerOptions {
* app opts in when it spawns the server.
*/
appAttachTimeoutMs?: number
+ /**
+ * How long a tool call waits for the app to register before it fails with
+ * APP_NOT_CONNECTED. Defaults to 10 s so a stdio bridge started slightly
+ * before the desktop app still succeeds; tests shorten it.
+ */
+ appWaitTimeoutMs?: number
}
export interface ServerHandle {
@@ -314,7 +320,8 @@ function buildServerContext(options: ServerOptions) {
})
const browserRPC = createBrowserRPCBridge({
authToken,
- onConnectionChange: mcpSessions.notifyToolsChanged
+ onConnectionChange: mcpSessions.notifyToolsChanged,
+ appWaitTimeoutMs: options.appWaitTimeoutMs
})
const sendToBrowser = browserRPC.sendRPC
const toolDescriptors = applyToolPolicy(createToolDescriptors(mcpRoot !== null), toolPolicy)
@@ -431,7 +438,8 @@ function buildHandle(
}
export async function startServer(options: ServerOptions = {}): Promise<ServerHandle> {
- validateAppAttachTimeout(options.appAttachTimeoutMs)
+ validateTimeoutOption('appAttachTimeoutMs', options.appAttachTimeoutMs)
+ validateTimeoutOption('appWaitTimeoutMs', options.appWaitTimeoutMs)
const ctx = buildServerContext(options)
// Wire shared connection handling BEFORE starting listeners so that
@@ -490,13 +498,13 @@ export async function startServer(options: ServerOptions = {}): Promise<ServerHa
const MAX_TIMER_MS = 2_147_483_647
-function validateAppAttachTimeout(timeoutMs: number | undefined): void {
+function validateTimeoutOption(name: string, timeoutMs: number | undefined): void {
if (timeoutMs === undefined) return
if (!Number.isSafeInteger(timeoutMs)) {
- throw new RangeError('appAttachTimeoutMs must be a safe integer')
+ throw new RangeError(`${name} must be a safe integer`)
}
if (timeoutMs < 0 || timeoutMs > MAX_TIMER_MS) {
- throw new RangeError(`appAttachTimeoutMs must be in the range 0–${MAX_TIMER_MS}`)
+ throw new RangeError(`${name} must be in the range 0–${MAX_TIMER_MS}`)
}
}
diff --git a/src/app/automation/mcp/spawn.ts b/src/app/automation/mcp/spawn.ts
index 009b2fadc..5f03dc7af 100644
--- a/src/app/automation/mcp/spawn.ts
+++ b/src/app/automation/mcp/spawn.ts
@@ -53,6 +53,15 @@ const MCP_EXECUTABLE = 'openpencil-mcp-http'
// port forever while still allowing brief renderer reloads (issue #488).
const MCP_APP_ATTACH_TIMEOUT_MS = 30_000
+/** Delays used while a spawned server comes up; tests shorten them. */
+export interface MCPStartupTiming {
+ /** How long to watch for the child exiting before polling its health. */
+ earlyExitMs: number
+ /** Delay before each of the health polls after spawning. */
+ healthPollMs: number
+}
+const DEFAULT_STARTUP_TIMING: MCPStartupTiming = { earlyExitMs: 250, healthPollMs: 1000 }
+
let runtimeAutomationAuthToken: string | null = DEV_AUTOMATION_AUTH_TOKEN
let runtimeAutomationStartupError: Error | null = null
@@ -365,7 +374,7 @@ async function configureDevMCP(): Promise<AutomationServerHandle> {
return { disconnect: noop, authToken, managed: true }
}
-async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {
+async function startMCPIfNeeded(timing: MCPStartupTiming): Promise<AutomationServerHandle | null> {
runtimeAutomationStartupError = null
if (import.meta.env.DEV) return configureDevMCP()
if (!isTauri()) return null
@@ -425,7 +434,10 @@ async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {
} catch (error) {
return rememberStartupError(error)
}
- const earlyExit = await Promise.race([childClosed, promiseTimeout(250).then(() => null)])
+ const earlyExit = await Promise.race([
+ childClosed,
+ promiseTimeout(timing.earlyExitMs).then(() => null)
+ ])
if (earlyExit) {
const details = startupStderr.trim()
return rememberStartupError(
@@ -434,7 +446,7 @@ async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {
)
)
}
- const health = await pollHealth(5, 1000, authToken)
+ const health = await pollHealth(5, timing.healthPollMs, authToken)
if (health) {
try {
@@ -476,9 +488,11 @@ async function startMCPIfNeeded(): Promise<AutomationServerHandle | null> {
)
}
-export async function spawnMCPIfNeeded(): Promise<AutomationServerHandle | null> {
+export async function spawnMCPIfNeeded(
+ timing: MCPStartupTiming = DEFAULT_STARTUP_TIMING
+): Promise<AutomationServerHandle | null> {
try {
- return await startMCPIfNeeded()
+ return await startMCPIfNeeded(timing)
} catch (error) {
return rememberStartupError(error)
}
diff --git a/tests/e2e/canvas/boolean-visual.spec.ts b/tests/e2e/canvas/boolean-visual.spec.ts
new file mode 100644
index 000000000..a6ae22ead
--- /dev/null
+++ b/tests/e2e/canvas/boolean-visual.spec.ts
@@ -0,0 +1,65 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function expectCanvas(name: string) {
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot(`${name}.png`)
+}
+
+test('boolean operations', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+ const operations = ['UNION', 'SUBTRACT', 'INTERSECT', 'EXCLUDE'] as const
+ const colors = [
+ { r: 0.23, g: 0.51, b: 0.96, a: 1 },
+ { r: 0.96, g: 0.35, b: 0.35, a: 1 },
+ { r: 0.08, g: 0.73, b: 0.73, a: 1 },
+ { r: 0.58, g: 0.27, b: 0.95, a: 1 }
+ ]
+
+ for (const [index, operation] of operations.entries()) {
+ const group = store.graph.createNode('BOOLEAN_OPERATION', pageId, {
+ name: `${operation} visual`,
+ x: 72 + index * 152,
+ y: 92,
+ width: 124,
+ height: 104,
+ booleanOperation: operation,
+ fills: [{ type: 'SOLID', color: colors[index], visible: true, opacity: 1 }],
+ strokes: [
+ {
+ color: { r: 0.08, g: 0.1, b: 0.18, a: 0.32 },
+ weight: 2,
+ visible: true,
+ opacity: 1,
+ align: 'CENTER'
+ }
+ ]
+ })
+ store.graph.createNode('RECTANGLE', group.id, {
+ name: `${operation} rectangle`,
+ x: 0,
+ y: 18,
+ width: 82,
+ height: 70,
+ cornerRadius: 14
+ })
+ store.graph.createNode('ELLIPSE', group.id, {
+ name: `${operation} ellipse`,
+ x: 42,
+ y: 0,
+ width: 82,
+ height: 104
+ })
+ }
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('boolean-operations')
+})
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/boolean-operations-openpencil-darwin.png b/tests/e2e/canvas/boolean-visual.spec.ts-snapshots/boolean-operations-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/boolean-operations-openpencil-darwin.png
rename to tests/e2e/canvas/boolean-visual.spec.ts-snapshots/boolean-operations-openpencil-darwin.png
diff --git a/tests/e2e/canvas/fill-modes-visual.spec.ts b/tests/e2e/canvas/fill-modes-visual.spec.ts
new file mode 100644
index 000000000..2491d98f9
--- /dev/null
+++ b/tests/e2e/canvas/fill-modes-visual.spec.ts
@@ -0,0 +1,207 @@
+import { readFile } from 'node:fs/promises'
+
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { readScenePixels } from '#tests/helpers/canvas/pixels'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function expectCanvas(name: string) {
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot(`${name}.png`)
+}
+
+test('FIT avatar preserves the full clipboard fixture image', async () => {
+ const bytes = await readFile('tests/fixtures/vectorize/pilot_avatar.png')
+ await editor.page.evaluate(
+ (data) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const hash = store.storeImage(new Uint8Array(data))
+ store.graph.createNode('RECTANGLE', store.state.currentPageId, {
+ name: 'Bitmap background',
+ x: 80,
+ y: 80,
+ width: 320,
+ height: 222,
+ cornerRadius: 16,
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 241 / 255, g: 245 / 255, b: 249 / 255, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ]
+ })
+ store.graph.createNode('RECTANGLE', store.state.currentPageId, {
+ name: 'Pilot avatar · image fill FIT',
+ x: 138,
+ y: 90,
+ width: 204,
+ height: 202,
+ fills: [
+ {
+ type: 'IMAGE',
+ imageHash: hash,
+ imageScaleMode: 'FIT',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ]
+ })
+ store.clearSelection()
+ store.requestRender()
+ },
+ [...bytes]
+ )
+ await editor.canvas.waitForRender()
+ await expectCanvas('fit-avatar-clipboard-fixture')
+})
+
+test('gradients and image fill modes', async () => {
+ await editor.page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+
+ const imageCanvas = document.createElement('canvas')
+ imageCanvas.width = 48
+ imageCanvas.height = 32
+ const ctx = imageCanvas.getContext('2d')
+ if (!ctx) throw new Error('Cannot create image fixture canvas')
+ ctx.fillStyle = '#ef4444'
+ ctx.fillRect(0, 0, 24, 16)
+ ctx.fillStyle = '#3b82f6'
+ ctx.fillRect(24, 0, 24, 16)
+ ctx.fillStyle = '#14b8a6'
+ ctx.fillRect(0, 16, 24, 16)
+ ctx.fillStyle = '#facc15'
+ ctx.fillRect(24, 16, 24, 16)
+ ctx.strokeStyle = '#111827'
+ ctx.lineWidth = 3
+ ctx.strokeRect(1.5, 1.5, 45, 29)
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ imageCanvas.toBlob((result) => {
+ if (result) {
+ resolve(result)
+ return
+ }
+ reject(new Error('Failed to encode image fixture'))
+ }, 'image/png')
+ })
+ const imageHash = store.storeImage(new Uint8Array(await blob.arrayBuffer()))
+
+ store.graph.createNode('FRAME', pageId, {
+ name: 'Gradient and Image Backdrop',
+ x: 56,
+ y: 52,
+ width: 700,
+ height: 250,
+ cornerRadius: 22,
+ fills: [
+ { type: 'SOLID', color: { r: 0.95, g: 0.95, b: 0.97, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+
+ const gradientStops = [
+ { color: { r: 0.23, g: 0.51, b: 0.96, a: 1 }, position: 0 },
+ { color: { r: 0.58, g: 0.27, b: 0.95, a: 1 }, position: 0.55 },
+ { color: { r: 0.08, g: 0.73, b: 0.73, a: 1 }, position: 1 }
+ ]
+ const gradientTypes = [
+ 'GRADIENT_LINEAR',
+ 'GRADIENT_RADIAL',
+ 'GRADIENT_ANGULAR',
+ 'GRADIENT_DIAMOND'
+ ] as const
+ for (const [index, type] of gradientTypes.entries()) {
+ store.graph.createNode('RECTANGLE', pageId, {
+ name: `${type} visual`,
+ x: 84 + index * 116,
+ y: 84,
+ width: 92,
+ height: 72,
+ cornerRadius: 16,
+ fills: [
+ {
+ type,
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ gradientStops,
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ }
+ ]
+ })
+ }
+
+ store.graph.createNode('RECTANGLE', pageId, {
+ name: 'FIT image with transparent margins',
+ x: 568,
+ y: 84,
+ width: 140,
+ height: 172,
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ imageHash,
+ imageScaleMode: 'FIT'
+ }
+ ]
+ })
+
+ const scaleModes = ['FILL', 'FIT', 'TILE', 'CROP'] as const
+ for (const [index, imageScaleMode] of scaleModes.entries()) {
+ store.graph.createNode('RECTANGLE', pageId, {
+ name: `${imageScaleMode} image visual`,
+ x: 84 + index * 116,
+ y: 184,
+ width: 92,
+ height: 72,
+ cornerRadius: 14,
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ imageHash,
+ imageScaleMode,
+ imageTransform:
+ imageScaleMode === 'CROP'
+ ? { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }
+ : undefined
+ }
+ ],
+ strokes: [
+ {
+ color: { r: 1, g: 1, b: 1, a: 0.9 },
+ weight: 2,
+ visible: true,
+ opacity: 1,
+ align: 'INSIDE'
+ }
+ ]
+ })
+ }
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ const gradientPixels = await readScenePixels(
+ editor.page,
+ [0, 1, 2, 3].map((index) => ({ x: 130 + index * 116, y: 120 }))
+ )
+ for (const [r, g, b, a] of gradientPixels) {
+ expect(a).toBe(255)
+ expect(Math.min(r, g, b)).toBeLessThan(200)
+ }
+ await editor.canvas.waitForRender()
+ await expectCanvas('gradients-and-image-fill-modes')
+})
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png b/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png
rename to tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/fit-avatar-clipboard-fixture-openpencil-darwin.png
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png b/tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png
rename to tests/e2e/canvas/fill-modes-visual.spec.ts-snapshots/gradients-and-image-fill-modes-openpencil-darwin.png
diff --git a/tests/e2e/canvas/pattern-mask-visual.spec.ts b/tests/e2e/canvas/pattern-mask-visual.spec.ts
new file mode 100644
index 000000000..152afbe89
--- /dev/null
+++ b/tests/e2e/canvas/pattern-mask-visual.spec.ts
@@ -0,0 +1,240 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function expectCanvas(name: string) {
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot(`${name}.png`)
+}
+
+test('pattern fills from source nodes', async () => {
+ await editor.page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+
+ const source = store.graph.createNode('ELLIPSE', pageId, {
+ name: 'Pattern source dot',
+ x: -1000,
+ y: -1000,
+ width: 18,
+ height: 18,
+ visible: false,
+ fills: [
+ { type: 'SOLID', color: { r: 0.96, g: 0.35, b: 0.12, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+
+ store.graph.createNode('RECTANGLE', pageId, {
+ name: 'Pattern fill visual',
+ x: 84,
+ y: 80,
+ width: 240,
+ height: 150,
+ cornerRadius: 18,
+ fills: [
+ {
+ type: 'PATTERN',
+ sourceNodeId: source.id,
+ patternTileType: 'HORIZONTAL_HEXAGONAL',
+ scale: 1.25,
+ patternSpacing: { x: 0.45, y: 0.35 },
+ horizontalAlignment: 'CENTER',
+ verticalAlignment: 'CENTER',
+ color: { r: 0.96, g: 0.35, b: 0.12, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ],
+ strokes: [
+ {
+ color: { r: 0.08, g: 0.1, b: 0.18, a: 0.18 },
+ weight: 2,
+ visible: true,
+ opacity: 1,
+ align: 'INSIDE'
+ }
+ ]
+ })
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('pattern-fills-from-source-nodes')
+})
+
+test('luminance masks and transformed tile fills', async () => {
+ await editor.page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+
+ const imageCanvas = document.createElement('canvas')
+ imageCanvas.width = 32
+ imageCanvas.height = 32
+ const ctx = imageCanvas.getContext('2d')
+ if (!ctx) throw new Error('Cannot create tile fixture canvas')
+ ctx.fillStyle = '#111827'
+ ctx.fillRect(0, 0, 32, 32)
+ ctx.fillStyle = '#f97316'
+ ctx.fillRect(0, 0, 16, 16)
+ ctx.fillStyle = '#38bdf8'
+ ctx.fillRect(16, 16, 16, 16)
+ ctx.fillStyle = '#facc15'
+ ctx.fillRect(20, 4, 8, 8)
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ imageCanvas.toBlob((result) => {
+ if (result) {
+ resolve(result)
+ return
+ }
+ reject(new Error('Failed to encode tile fixture'))
+ }, 'image/png')
+ })
+ const imageHash = store.storeImage(new Uint8Array(await blob.arrayBuffer()))
+
+ store.graph.createNode('RECTANGLE', pageId, {
+ name: 'Transformed tile fill visual',
+ x: 80,
+ y: 76,
+ width: 180,
+ height: 130,
+ cornerRadius: 18,
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ imageHash,
+ imageScaleMode: 'TILE',
+ imageTransform: { m00: 3, m01: 0, m02: 0, m10: 0, m11: 3, m12: 0 }
+ }
+ ],
+ strokes: [
+ {
+ color: { r: 1, g: 1, b: 1, a: 0.85 },
+ weight: 2,
+ visible: true,
+ opacity: 1,
+ align: 'INSIDE'
+ }
+ ]
+ })
+
+ const frame = store.graph.createNode('FRAME', pageId, {
+ name: 'Luminance mask stack visual',
+ x: 320,
+ y: 76,
+ width: 240,
+ height: 130,
+ cornerRadius: 18,
+ fills: [
+ { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ store.graph.createNode('RECTANGLE', frame.id, {
+ name: 'Luminance mask gradient',
+ x: 24,
+ y: 20,
+ width: 192,
+ height: 90,
+ isMask: true,
+ maskType: 'LUMINANCE',
+ fills: [
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ gradientStops: [
+ { color: { r: 0, g: 0, b: 0, a: 1 }, position: 0 },
+ { color: { r: 1, g: 1, b: 1, a: 1 }, position: 1 }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ }
+ ]
+ })
+ for (let index = 0; index < 5; index++) {
+ store.graph.createNode('RECTANGLE', frame.id, {
+ name: `Masked color stripe ${index + 1}`,
+ x: 24 + index * 38,
+ y: 20,
+ width: 34,
+ height: 90,
+ fills: [
+ {
+ type: 'SOLID',
+ color: [
+ { r: 0.96, g: 0.35, b: 0.35, a: 1 },
+ { r: 0.96, g: 0.64, b: 0.16, a: 1 },
+ { r: 0.08, g: 0.73, b: 0.73, a: 1 },
+ { r: 0.23, g: 0.51, b: 0.96, a: 1 },
+ { r: 0.58, g: 0.27, b: 0.95, a: 1 }
+ ][index],
+ visible: true,
+ opacity: 1
+ }
+ ]
+ })
+ }
+
+ const multiMaskFrame = store.graph.createNode('FRAME', pageId, {
+ name: 'Consecutive mask stack visual',
+ x: 620,
+ y: 76,
+ width: 220,
+ height: 130,
+ cornerRadius: 18,
+ fills: [
+ { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ store.graph.createNode('ELLIPSE', multiMaskFrame.id, {
+ name: 'First combined mask',
+ x: 18,
+ y: 16,
+ width: 112,
+ height: 98,
+ isMask: true,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
+ })
+ store.graph.createNode('ELLIPSE', multiMaskFrame.id, {
+ name: 'Second combined mask',
+ x: 90,
+ y: 16,
+ width: 112,
+ height: 98,
+ isMask: true,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
+ })
+ store.graph.createNode('RECTANGLE', multiMaskFrame.id, {
+ name: 'Consecutively masked content',
+ x: 18,
+ y: 16,
+ width: 184,
+ height: 98,
+ fills: [
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ gradientStops: [
+ { color: { r: 0.96, g: 0.35, b: 0.35, a: 1 }, position: 0 },
+ { color: { r: 0.08, g: 0.73, b: 0.73, a: 1 }, position: 0.5 },
+ { color: { r: 0.58, g: 0.27, b: 0.95, a: 1 }, position: 1 }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ }
+ ]
+ })
+
+ store.clearSelection()
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('luminance-masks-and-transformed-tile-fills')
+})
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/luminance-masks-and-transformed-tile-fills-openpencil-darwin.png b/tests/e2e/canvas/pattern-mask-visual.spec.ts-snapshots/luminance-masks-and-transformed-tile-fills-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/luminance-masks-and-transformed-tile-fills-openpencil-darwin.png
rename to tests/e2e/canvas/pattern-mask-visual.spec.ts-snapshots/luminance-masks-and-transformed-tile-fills-openpencil-darwin.png
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/pattern-fills-from-source-nodes-openpencil-darwin.png b/tests/e2e/canvas/pattern-mask-visual.spec.ts-snapshots/pattern-fills-from-source-nodes-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/pattern-fills-from-source-nodes-openpencil-darwin.png
rename to tests/e2e/canvas/pattern-mask-visual.spec.ts-snapshots/pattern-fills-from-source-nodes-openpencil-darwin.png
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts b/tests/e2e/canvas/renderer-visuals.spec.ts
deleted file mode 100644
index 3373bb6f0..000000000
--- a/tests/e2e/canvas/renderer-visuals.spec.ts
+++ /dev/null
@@ -1,652 +0,0 @@
-import { readFile } from 'node:fs/promises'
-
-import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
-import { readScenePixels } from '#tests/helpers/canvas/pixels'
-
-const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
-
-async function expectCanvas(name: string) {
- editor.canvas.assertNoErrors()
- const buffer = await editor.canvas.screenshotCanvasRegion()
- expect(buffer).toMatchSnapshot(`${name}.png`)
-}
-
-test('boolean operations', async () => {
- await editor.page.evaluate(() => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
- const operations = ['UNION', 'SUBTRACT', 'INTERSECT', 'EXCLUDE'] as const
- const colors = [
- { r: 0.23, g: 0.51, b: 0.96, a: 1 },
- { r: 0.96, g: 0.35, b: 0.35, a: 1 },
- { r: 0.08, g: 0.73, b: 0.73, a: 1 },
- { r: 0.58, g: 0.27, b: 0.95, a: 1 }
- ]
-
- for (const [index, operation] of operations.entries()) {
- const group = store.graph.createNode('BOOLEAN_OPERATION', pageId, {
- name: `${operation} visual`,
- x: 72 + index * 152,
- y: 92,
- width: 124,
- height: 104,
- booleanOperation: operation,
- fills: [{ type: 'SOLID', color: colors[index], visible: true, opacity: 1 }],
- strokes: [
- {
- color: { r: 0.08, g: 0.1, b: 0.18, a: 0.32 },
- weight: 2,
- visible: true,
- opacity: 1,
- align: 'CENTER'
- }
- ]
- })
- store.graph.createNode('RECTANGLE', group.id, {
- name: `${operation} rectangle`,
- x: 0,
- y: 18,
- width: 82,
- height: 70,
- cornerRadius: 14
- })
- store.graph.createNode('ELLIPSE', group.id, {
- name: `${operation} ellipse`,
- x: 42,
- y: 0,
- width: 82,
- height: 104
- })
- }
-
- store.clearSelection()
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- await expectCanvas('boolean-operations')
-})
-
-test('FIT avatar preserves the full clipboard fixture image', async () => {
- const bytes = await readFile('tests/fixtures/vectorize/pilot_avatar.png')
- await editor.page.evaluate(
- (data) => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const hash = store.storeImage(new Uint8Array(data))
- store.graph.createNode('RECTANGLE', store.state.currentPageId, {
- name: 'Bitmap background',
- x: 80,
- y: 80,
- width: 320,
- height: 222,
- cornerRadius: 16,
- fills: [
- {
- type: 'SOLID',
- color: { r: 241 / 255, g: 245 / 255, b: 249 / 255, a: 1 },
- visible: true,
- opacity: 1
- }
- ]
- })
- store.graph.createNode('RECTANGLE', store.state.currentPageId, {
- name: 'Pilot avatar · image fill FIT',
- x: 138,
- y: 90,
- width: 204,
- height: 202,
- fills: [
- {
- type: 'IMAGE',
- imageHash: hash,
- imageScaleMode: 'FIT',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1
- }
- ]
- })
- store.clearSelection()
- store.requestRender()
- },
- [...bytes]
- )
- await editor.canvas.waitForRender()
- await expectCanvas('fit-avatar-clipboard-fixture')
-})
-
-test('gradients and image fill modes', async () => {
- await editor.page.evaluate(async () => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
-
- const imageCanvas = document.createElement('canvas')
- imageCanvas.width = 48
- imageCanvas.height = 32
- const ctx = imageCanvas.getContext('2d')
- if (!ctx) throw new Error('Cannot create image fixture canvas')
- ctx.fillStyle = '#ef4444'
- ctx.fillRect(0, 0, 24, 16)
- ctx.fillStyle = '#3b82f6'
- ctx.fillRect(24, 0, 24, 16)
- ctx.fillStyle = '#14b8a6'
- ctx.fillRect(0, 16, 24, 16)
- ctx.fillStyle = '#facc15'
- ctx.fillRect(24, 16, 24, 16)
- ctx.strokeStyle = '#111827'
- ctx.lineWidth = 3
- ctx.strokeRect(1.5, 1.5, 45, 29)
- const blob = await new Promise<Blob>((resolve, reject) => {
- imageCanvas.toBlob((result) => {
- if (result) {
- resolve(result)
- return
- }
- reject(new Error('Failed to encode image fixture'))
- }, 'image/png')
- })
- const imageHash = store.storeImage(new Uint8Array(await blob.arrayBuffer()))
-
- store.graph.createNode('FRAME', pageId, {
- name: 'Gradient and Image Backdrop',
- x: 56,
- y: 52,
- width: 700,
- height: 250,
- cornerRadius: 22,
- fills: [
- { type: 'SOLID', color: { r: 0.95, g: 0.95, b: 0.97, a: 1 }, visible: true, opacity: 1 }
- ]
- })
-
- const gradientStops = [
- { color: { r: 0.23, g: 0.51, b: 0.96, a: 1 }, position: 0 },
- { color: { r: 0.58, g: 0.27, b: 0.95, a: 1 }, position: 0.55 },
- { color: { r: 0.08, g: 0.73, b: 0.73, a: 1 }, position: 1 }
- ]
- const gradientTypes = [
- 'GRADIENT_LINEAR',
- 'GRADIENT_RADIAL',
- 'GRADIENT_ANGULAR',
- 'GRADIENT_DIAMOND'
- ] as const
- for (const [index, type] of gradientTypes.entries()) {
- store.graph.createNode('RECTANGLE', pageId, {
- name: `${type} visual`,
- x: 84 + index * 116,
- y: 84,
- width: 92,
- height: 72,
- cornerRadius: 16,
- fills: [
- {
- type,
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- gradientStops,
- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- }
- ]
- })
- }
-
- store.graph.createNode('RECTANGLE', pageId, {
- name: 'FIT image with transparent margins',
- x: 568,
- y: 84,
- width: 140,
- height: 172,
- fills: [
- {
- type: 'IMAGE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- imageHash,
- imageScaleMode: 'FIT'
- }
- ]
- })
-
- const scaleModes = ['FILL', 'FIT', 'TILE', 'CROP'] as const
- for (const [index, imageScaleMode] of scaleModes.entries()) {
- store.graph.createNode('RECTANGLE', pageId, {
- name: `${imageScaleMode} image visual`,
- x: 84 + index * 116,
- y: 184,
- width: 92,
- height: 72,
- cornerRadius: 14,
- fills: [
- {
- type: 'IMAGE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- imageHash,
- imageScaleMode,
- imageTransform:
- imageScaleMode === 'CROP'
- ? { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }
- : undefined
- }
- ],
- strokes: [
- {
- color: { r: 1, g: 1, b: 1, a: 0.9 },
- weight: 2,
- visible: true,
- opacity: 1,
- align: 'INSIDE'
- }
- ]
- })
- }
-
- store.clearSelection()
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- const gradientPixels = await readScenePixels(
- editor.page,
- [0, 1, 2, 3].map((index) => ({ x: 130 + index * 116, y: 120 }))
- )
- for (const [r, g, b, a] of gradientPixels) {
- expect(a).toBe(255)
- expect(Math.min(r, g, b)).toBeLessThan(200)
- }
- await editor.canvas.waitForRender()
- await expectCanvas('gradients-and-image-fill-modes')
-})
-
-test('complex text fills preserve native paragraph layout', async () => {
- await editor.page.evaluate(async () => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
-
- store.graph.createNode('FRAME', pageId, {
- name: 'Complex text fill visual backdrop',
- x: 64,
- y: 56,
- width: 660,
- height: 220,
- cornerRadius: 22,
- fills: [
- { type: 'SOLID', color: { r: 0.96, g: 0.97, b: 0.99, a: 1 }, visible: true, opacity: 1 }
- ]
- })
-
- store.graph.createNode('TEXT', pageId, {
- name: 'Gradient outline text visual',
- x: 96,
- y: 88,
- width: 560,
- height: 96,
- text: 'OPEN',
- fontFamily: 'Inter',
- fontSize: 88,
- fontWeight: 700,
- textAutoResize: 'NONE',
- fills: [
- {
- type: 'GRADIENT_LINEAR',
- opacity: 1,
- visible: true,
- gradientStops: [
- { position: 0, color: { r: 0.23, g: 0.51, b: 0.96, a: 1 } },
- { position: 0.5, color: { r: 0.08, g: 0.73, b: 0.73, a: 1 } },
- { position: 1, color: { r: 0.58, g: 0.27, b: 0.95, a: 1 } }
- ],
- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- }
- ]
- })
-
- store.graph.createNode('TEXT', pageId, {
- name: 'Solid control text visual',
- x: 100,
- y: 188,
- width: 520,
- height: 34,
- text: 'solid text remains paragraph-rendered',
- fontFamily: 'Inter',
- fontSize: 24,
- fontWeight: 500,
- textAutoResize: 'HEIGHT',
- fills: [
- { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
- ]
- })
-
- store.clearSelection()
- await store.loadFontsForNodes(store.graph.getPages().flatMap((page) => page.childIds))
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- await expectCanvas('complex-text-fills-as-outlines')
-})
-
-test('text decoration styles and OpenType features', async () => {
- await editor.page.evaluate(async () => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
-
- store.graph.createNode('FRAME', pageId, {
- name: 'Text decoration visual backdrop',
- x: 64,
- y: 56,
- width: 660,
- height: 220,
- cornerRadius: 22,
- fills: [
- { type: 'SOLID', color: { r: 0.96, g: 0.97, b: 0.99, a: 1 }, visible: true, opacity: 1 }
- ]
- })
-
- const rows = [
- {
- text: 'Wavy underline in red',
- y: 92,
- textDecoration: 'UNDERLINE' as const,
- textDecorationStyle: 'WAVY' as const,
- textDecorationThickness: 2,
- textDecorationFills: [
- {
- type: 'SOLID' as const,
- color: { r: 0.96, g: 0.26, b: 0.21, a: 1 },
- visible: true,
- opacity: 1
- }
- ]
- },
- {
- text: 'Dotted underline in blue',
- y: 142,
- textDecoration: 'UNDERLINE' as const,
- textDecorationStyle: 'DOTTED' as const,
- textDecorationThickness: 2.5,
- textDecorationFills: [
- {
- type: 'SOLID' as const,
- color: { r: 0.23, g: 0.51, b: 0.96, a: 1 },
- visible: true,
- opacity: 1
- }
- ]
- },
- {
- text: 'OpenType tags: oldstyle 0123456789 + ss01',
- y: 192,
- fontFeatures: [
- { tag: 'ONUM', enabled: true },
- { tag: 'SS01', enabled: true },
- { tag: 'KERN', enabled: false }
- ]
- }
- ]
-
- for (const row of rows) {
- store.graph.createNode('TEXT', pageId, {
- name: row.text,
- x: 100,
- y: row.y,
- width: 520,
- height: 34,
- text: row.text,
- fontSize: 24,
- fontWeight: 600,
- textAutoResize: 'HEIGHT',
- textDecoration: row.textDecoration ?? 'NONE',
- textDecorationStyle: row.textDecorationStyle ?? 'SOLID',
- textDecorationThickness: row.textDecorationThickness ?? null,
- textDecorationFills: row.textDecorationFills ?? [],
- fontFeatures: row.fontFeatures ?? [],
- fills: [
- { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
- ]
- })
- }
-
- store.clearSelection()
- await store.loadFontsForNodes(store.graph.getPages().flatMap((page) => page.childIds))
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- await expectCanvas('text-decoration-styles-and-opentype-features')
-})
-
-test('pattern fills from source nodes', async () => {
- await editor.page.evaluate(() => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
-
- const source = store.graph.createNode('ELLIPSE', pageId, {
- name: 'Pattern source dot',
- x: -1000,
- y: -1000,
- width: 18,
- height: 18,
- visible: false,
- fills: [
- { type: 'SOLID', color: { r: 0.96, g: 0.35, b: 0.12, a: 1 }, visible: true, opacity: 1 }
- ]
- })
-
- store.graph.createNode('RECTANGLE', pageId, {
- name: 'Pattern fill visual',
- x: 84,
- y: 80,
- width: 240,
- height: 150,
- cornerRadius: 18,
- fills: [
- {
- type: 'PATTERN',
- sourceNodeId: source.id,
- patternTileType: 'HORIZONTAL_HEXAGONAL',
- scale: 1.25,
- patternSpacing: { x: 0.45, y: 0.35 },
- horizontalAlignment: 'CENTER',
- verticalAlignment: 'CENTER',
- color: { r: 0.96, g: 0.35, b: 0.12, a: 1 },
- visible: true,
- opacity: 1
- }
- ],
- strokes: [
- {
- color: { r: 0.08, g: 0.1, b: 0.18, a: 0.18 },
- weight: 2,
- visible: true,
- opacity: 1,
- align: 'INSIDE'
- }
- ]
- })
-
- store.clearSelection()
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- await expectCanvas('pattern-fills-from-source-nodes')
-})
-
-test('luminance masks and transformed tile fills', async () => {
- await editor.page.evaluate(async () => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pageId = store.state.currentPageId
-
- const imageCanvas = document.createElement('canvas')
- imageCanvas.width = 32
- imageCanvas.height = 32
- const ctx = imageCanvas.getContext('2d')
- if (!ctx) throw new Error('Cannot create tile fixture canvas')
- ctx.fillStyle = '#111827'
- ctx.fillRect(0, 0, 32, 32)
- ctx.fillStyle = '#f97316'
- ctx.fillRect(0, 0, 16, 16)
- ctx.fillStyle = '#38bdf8'
- ctx.fillRect(16, 16, 16, 16)
- ctx.fillStyle = '#facc15'
- ctx.fillRect(20, 4, 8, 8)
- const blob = await new Promise<Blob>((resolve, reject) => {
- imageCanvas.toBlob((result) => {
- if (result) {
- resolve(result)
- return
- }
- reject(new Error('Failed to encode tile fixture'))
- }, 'image/png')
- })
- const imageHash = store.storeImage(new Uint8Array(await blob.arrayBuffer()))
-
- store.graph.createNode('RECTANGLE', pageId, {
- name: 'Transformed tile fill visual',
- x: 80,
- y: 76,
- width: 180,
- height: 130,
- cornerRadius: 18,
- fills: [
- {
- type: 'IMAGE',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- imageHash,
- imageScaleMode: 'TILE',
- imageTransform: { m00: 3, m01: 0, m02: 0, m10: 0, m11: 3, m12: 0 }
- }
- ],
- strokes: [
- {
- color: { r: 1, g: 1, b: 1, a: 0.85 },
- weight: 2,
- visible: true,
- opacity: 1,
- align: 'INSIDE'
- }
- ]
- })
-
- const frame = store.graph.createNode('FRAME', pageId, {
- name: 'Luminance mask stack visual',
- x: 320,
- y: 76,
- width: 240,
- height: 130,
- cornerRadius: 18,
- fills: [
- { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
- ]
- })
- store.graph.createNode('RECTANGLE', frame.id, {
- name: 'Luminance mask gradient',
- x: 24,
- y: 20,
- width: 192,
- height: 90,
- isMask: true,
- maskType: 'LUMINANCE',
- fills: [
- {
- type: 'GRADIENT_LINEAR',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- gradientStops: [
- { color: { r: 0, g: 0, b: 0, a: 1 }, position: 0 },
- { color: { r: 1, g: 1, b: 1, a: 1 }, position: 1 }
- ],
- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- }
- ]
- })
- for (let index = 0; index < 5; index++) {
- store.graph.createNode('RECTANGLE', frame.id, {
- name: `Masked color stripe ${index + 1}`,
- x: 24 + index * 38,
- y: 20,
- width: 34,
- height: 90,
- fills: [
- {
- type: 'SOLID',
- color: [
- { r: 0.96, g: 0.35, b: 0.35, a: 1 },
- { r: 0.96, g: 0.64, b: 0.16, a: 1 },
- { r: 0.08, g: 0.73, b: 0.73, a: 1 },
- { r: 0.23, g: 0.51, b: 0.96, a: 1 },
- { r: 0.58, g: 0.27, b: 0.95, a: 1 }
- ][index],
- visible: true,
- opacity: 1
- }
- ]
- })
- }
-
- const multiMaskFrame = store.graph.createNode('FRAME', pageId, {
- name: 'Consecutive mask stack visual',
- x: 620,
- y: 76,
- width: 220,
- height: 130,
- cornerRadius: 18,
- fills: [
- { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
- ]
- })
- store.graph.createNode('ELLIPSE', multiMaskFrame.id, {
- name: 'First combined mask',
- x: 18,
- y: 16,
- width: 112,
- height: 98,
- isMask: true,
- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
- })
- store.graph.createNode('ELLIPSE', multiMaskFrame.id, {
- name: 'Second combined mask',
- x: 90,
- y: 16,
- width: 112,
- height: 98,
- isMask: true,
- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, visible: true, opacity: 1 }]
- })
- store.graph.createNode('RECTANGLE', multiMaskFrame.id, {
- name: 'Consecutively masked content',
- x: 18,
- y: 16,
- width: 184,
- height: 98,
- fills: [
- {
- type: 'GRADIENT_LINEAR',
- color: { r: 0, g: 0, b: 0, a: 1 },
- visible: true,
- opacity: 1,
- gradientStops: [
- { color: { r: 0.96, g: 0.35, b: 0.35, a: 1 }, position: 0 },
- { color: { r: 0.08, g: 0.73, b: 0.73, a: 1 }, position: 0.5 },
- { color: { r: 0.58, g: 0.27, b: 0.95, a: 1 }, position: 1 }
- ],
- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
- }
- ]
- })
-
- store.clearSelection()
- store.requestRender()
- })
- await editor.canvas.waitForRender()
- await expectCanvas('luminance-masks-and-transformed-tile-fills')
-})
diff --git a/tests/e2e/canvas/text-path-visual.spec.ts b/tests/e2e/canvas/text/path-visual.spec.ts
similarity index 100%
rename from tests/e2e/canvas/text-path-visual.spec.ts
rename to tests/e2e/canvas/text/path-visual.spec.ts
diff --git a/tests/e2e/canvas/text-path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png b/tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/text-path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png
rename to tests/e2e/canvas/text/path-visual.spec.ts-snapshots/text-path-rendering-and-selection-openpencil-darwin.png
diff --git a/tests/e2e/canvas/text-raster-history.spec.ts b/tests/e2e/canvas/text/raster-history.spec.ts
similarity index 100%
rename from tests/e2e/canvas/text-raster-history.spec.ts
rename to tests/e2e/canvas/text/raster-history.spec.ts
diff --git a/tests/e2e/canvas/text/visual.spec.ts b/tests/e2e/canvas/text/visual.spec.ts
new file mode 100644
index 000000000..e00b4b5aa
--- /dev/null
+++ b/tests/e2e/canvas/text/visual.spec.ts
@@ -0,0 +1,167 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+
+const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')
+
+async function expectCanvas(name: string) {
+ editor.canvas.assertNoErrors()
+ const buffer = await editor.canvas.screenshotCanvasRegion()
+ expect(buffer).toMatchSnapshot(`${name}.png`)
+}
+
+test('complex text fills preserve native paragraph layout', async () => {
+ await editor.page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+
+ store.graph.createNode('FRAME', pageId, {
+ name: 'Complex text fill visual backdrop',
+ x: 64,
+ y: 56,
+ width: 660,
+ height: 220,
+ cornerRadius: 22,
+ fills: [
+ { type: 'SOLID', color: { r: 0.96, g: 0.97, b: 0.99, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+
+ store.graph.createNode('TEXT', pageId, {
+ name: 'Gradient outline text visual',
+ x: 96,
+ y: 88,
+ width: 560,
+ height: 96,
+ text: 'OPEN',
+ fontFamily: 'Inter',
+ fontSize: 88,
+ fontWeight: 700,
+ textAutoResize: 'NONE',
+ fills: [
+ {
+ type: 'GRADIENT_LINEAR',
+ opacity: 1,
+ visible: true,
+ gradientStops: [
+ { position: 0, color: { r: 0.23, g: 0.51, b: 0.96, a: 1 } },
+ { position: 0.5, color: { r: 0.08, g: 0.73, b: 0.73, a: 1 } },
+ { position: 1, color: { r: 0.58, g: 0.27, b: 0.95, a: 1 } }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ }
+ ]
+ })
+
+ store.graph.createNode('TEXT', pageId, {
+ name: 'Solid control text visual',
+ x: 100,
+ y: 188,
+ width: 520,
+ height: 34,
+ text: 'solid text remains paragraph-rendered',
+ fontFamily: 'Inter',
+ fontSize: 24,
+ fontWeight: 500,
+ textAutoResize: 'HEIGHT',
+ fills: [
+ { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+
+ store.clearSelection()
+ await store.loadFontsForNodes(store.graph.getPages().flatMap((page) => page.childIds))
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('complex-text-fills-as-outlines')
+})
+
+test('text decoration styles and OpenType features', async () => {
+ await editor.page.evaluate(async () => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+
+ store.graph.createNode('FRAME', pageId, {
+ name: 'Text decoration visual backdrop',
+ x: 64,
+ y: 56,
+ width: 660,
+ height: 220,
+ cornerRadius: 22,
+ fills: [
+ { type: 'SOLID', color: { r: 0.96, g: 0.97, b: 0.99, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+
+ const rows = [
+ {
+ text: 'Wavy underline in red',
+ y: 92,
+ textDecoration: 'UNDERLINE' as const,
+ textDecorationStyle: 'WAVY' as const,
+ textDecorationThickness: 2,
+ textDecorationFills: [
+ {
+ type: 'SOLID' as const,
+ color: { r: 0.96, g: 0.26, b: 0.21, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ]
+ },
+ {
+ text: 'Dotted underline in blue',
+ y: 142,
+ textDecoration: 'UNDERLINE' as const,
+ textDecorationStyle: 'DOTTED' as const,
+ textDecorationThickness: 2.5,
+ textDecorationFills: [
+ {
+ type: 'SOLID' as const,
+ color: { r: 0.23, g: 0.51, b: 0.96, a: 1 },
+ visible: true,
+ opacity: 1
+ }
+ ]
+ },
+ {
+ text: 'OpenType tags: oldstyle 0123456789 + ss01',
+ y: 192,
+ fontFeatures: [
+ { tag: 'ONUM', enabled: true },
+ { tag: 'SS01', enabled: true },
+ { tag: 'KERN', enabled: false }
+ ]
+ }
+ ]
+
+ for (const row of rows) {
+ store.graph.createNode('TEXT', pageId, {
+ name: row.text,
+ x: 100,
+ y: row.y,
+ width: 520,
+ height: 34,
+ text: row.text,
+ fontSize: 24,
+ fontWeight: 600,
+ textAutoResize: 'HEIGHT',
+ textDecoration: row.textDecoration ?? 'NONE',
+ textDecorationStyle: row.textDecorationStyle ?? 'SOLID',
+ textDecorationThickness: row.textDecorationThickness ?? null,
+ textDecorationFills: row.textDecorationFills ?? [],
+ fontFeatures: row.fontFeatures ?? [],
+ fills: [
+ { type: 'SOLID', color: { r: 0.08, g: 0.1, b: 0.18, a: 1 }, visible: true, opacity: 1 }
+ ]
+ })
+ }
+
+ store.clearSelection()
+ await store.loadFontsForNodes(store.graph.getPages().flatMap((page) => page.childIds))
+ store.requestRender()
+ })
+ await editor.canvas.waitForRender()
+ await expectCanvas('text-decoration-styles-and-opentype-features')
+})
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png b/tests/e2e/canvas/text/visual.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png
rename to tests/e2e/canvas/text/visual.spec.ts-snapshots/complex-text-fills-as-outlines-openpencil-darwin.png
diff --git a/tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png b/tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png
similarity index 100%
rename from tests/e2e/canvas/renderer-visuals.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png
rename to tests/e2e/canvas/text/visual.spec.ts-snapshots/text-decoration-styles-and-opentype-features-openpencil-darwin.png
diff --git a/tests/engine/app/document/recovery/store.test.ts b/tests/engine/app/document/recovery/store.test.ts
index 00d336cb0..e4ac0ef14 100644
--- a/tests/engine/app/document/recovery/store.test.ts
+++ b/tests/engine/app/document/recovery/store.test.ts
@@ -1,5 +1,7 @@
import 'fake-indexeddb/auto'
-import { beforeEach, describe, expect, test } from 'bun:test'
+import { afterAll, beforeEach, describe, expect, test } from 'bun:test'
+
+import { IDBFactory } from 'fake-indexeddb'
import { createIdbRecoveryStore } from '@/app/document/recovery/idb'
import { createMemoryRecoveryStore } from '@/app/document/recovery/memory'
@@ -7,13 +9,19 @@ import { createMemoryRecoveryStore } from '@/app/document/recovery/memory'
const bytes = new Uint8Array([1, 2, 3, 4])
describe('document recovery store', () => {
- beforeEach(async () => {
- await new Promise<void>((resolve) => {
- const request = indexedDB.deleteDatabase('open-pencil-recovery')
- request.onsuccess = () => resolve()
- request.onerror = () => resolve()
- request.onblocked = () => resolve()
- })
+ // Every file in a shard shares this process and its `indexedDB` global.
+ // Another suite may leave the production recovery store's connection open
+ // (createEditorStore() opens it), which would block a deleteDatabase() here
+ // and queue our open() behind it until the test times out. A fresh factory
+ // per test isolates this suite from that and from its own previous test.
+ const sharedFactory = indexedDB
+
+ beforeEach(() => {
+ globalThis.indexedDB = new IDBFactory()
+ })
+
+ afterAll(() => {
+ globalThis.indexedDB = sharedFactory
})
test('stores metadata and FIG bytes atomically in IndexedDB', async () => {
diff --git a/tests/engine/cli/eval.test.ts b/tests/engine/cli/eval.test.ts
index e26104d9a..fe336d808 100644
--- a/tests/engine/cli/eval.test.ts
+++ b/tests/engine/cli/eval.test.ts
@@ -17,7 +17,7 @@ async function run(
args: string[],
stdin?: string
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
- const proc = Bun.spawn(['bun', CLI, ...args], {
+ const proc = Bun.spawn([process.execPath, CLI, ...args], {
stdout: 'pipe',
stderr: 'pipe',
stdin: stdin ? Buffer.from(stdin) : undefined
@@ -139,7 +139,7 @@ heavy('eval CLI', () => {
})
test('stdin reads code from pipe', async () => {
- const proc = Bun.spawn(['bun', CLI, 'eval', FIXTURE, '--stdin'], {
+ const proc = Bun.spawn([process.execPath, CLI, 'eval', FIXTURE, '--stdin'], {
stdout: 'pipe',
stderr: 'pipe',
stdin: 'pipe'
diff --git a/tests/engine/cli/overlaps.test.ts b/tests/engine/cli/overlaps.test.ts
index 171d16a6e..e6949f9e5 100644
--- a/tests/engine/cli/overlaps.test.ts
+++ b/tests/engine/cli/overlaps.test.ts
@@ -34,7 +34,7 @@ async function makeTwoPageFixture(): Promise<string> {
}
async function run(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
- const proc = Bun.spawn(['bun', CLI, ...args], {
+ const proc = Bun.spawn([process.execPath, CLI, ...args], {
stdout: 'pipe',
stderr: 'pipe'
})
diff --git a/tests/engine/clipboard/figma/images.test.ts b/tests/engine/clipboard/figma/images.test.ts
index 7b4f2ffa3..72585fc11 100644
--- a/tests/engine/clipboard/figma/images.test.ts
+++ b/tests/engine/clipboard/figma/images.test.ts
@@ -2,6 +2,7 @@ import { expect, test } from 'bun:test'
import { buildFigmaClipboardHTML, FigmaAPI } from '@open-pencil/core'
import { parseFigmaClipboard } from '@open-pencil/fig/clipboard'
+import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
// Valid PNG: Figma validates the embedded bytes against the SHA-1 image reference.
@@ -10,6 +11,7 @@ const bytes = new Uint8Array(
)
test('Figma clipboard embeds shared image bytes once with SHA-1 references', async () => {
+ await initCodec()
const graph = new SceneGraph()
const page = graph.getPages()[0]
const { hash } = new FigmaAPI(graph).createImage(bytes)
diff --git a/tests/engine/io/fig/import/basic.test.ts b/tests/engine/io/fig/import/basic.test.ts
index 39603ba5d..92785cb6a 100644
--- a/tests/engine/io/fig/import/basic.test.ts
+++ b/tests/engine/io/fig/import/basic.test.ts
@@ -2,7 +2,7 @@ import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/core'
-import { parseGoldPreviewFixture, VALID_NODE_TYPES } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture, VALID_NODE_TYPES } from '#tests/helpers/fig-fixtures'
setDefaultTimeout(60_000)
@@ -10,7 +10,7 @@ let parsed: SceneGraph
let allNodes: SceneNode[]
beforeAll(async () => {
- const fixture = await parseGoldPreviewFixture()
+ const fixture = await sharedGoldPreviewFixture()
parsed = fixture.graph
allNodes = fixture.allNodes
})
diff --git a/tests/engine/io/fig/import/edge-cases.test.ts b/tests/engine/io/fig/import/edge-cases.test.ts
index e4eaa4aaa..a737c0fd2 100644
--- a/tests/engine/io/fig/import/edge-cases.test.ts
+++ b/tests/engine/io/fig/import/edge-cases.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, setDefaultTimeout, test } from 'bun:test'
import { importNodeChanges, parseFigFile } from '@open-pencil/core'
import { expectDefined } from '#tests/helpers/assert'
-import { parseFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
setDefaultTimeout(60_000)
@@ -494,7 +494,7 @@ describe('edge cases', () => {
})
test('DSD propagates through intermediate clones that are also DSD-targeted', async () => {
- const graph = await parseFixture('gold-preview.fig')
+ const { graph } = await sharedGoldPreviewFixture()
const thumb = [...graph.getAllNodes()].find((n) => n.name === 'Preview Thumbnail')
expect(thumb).toBeDefined()
diff --git a/tests/engine/io/fig/import/property-integrity.test.ts b/tests/engine/io/fig/import/property-integrity.test.ts
index d0068a71a..72fb0211d 100644
--- a/tests/engine/io/fig/import/property-integrity.test.ts
+++ b/tests/engine/io/fig/import/property-integrity.test.ts
@@ -2,14 +2,14 @@ import { beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test'
import { type Fill, type SceneNode } from '@open-pencil/core'
-import { parseGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
setDefaultTimeout(60_000)
let allNodes: SceneNode[]
beforeAll(async () => {
- const fixture = await parseGoldPreviewFixture()
+ const fixture = await sharedGoldPreviewFixture()
allNodes = fixture.allNodes
})
diff --git a/tests/engine/io/subgraph.test.ts b/tests/engine/io/subgraph.test.ts
index ffc1decca..c6ec88126 100644
--- a/tests/engine/io/subgraph.test.ts
+++ b/tests/engine/io/subgraph.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test'
-import { readFileSync } from 'node:fs'
import { exportFigFile, extractExportGraph, parseFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
@@ -7,6 +6,8 @@ import { parseFigBuffer } from '@open-pencil/fig'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
+
describe('export subgraph extraction', () => {
test('page extraction keeps the source root and page descendants', () => {
const graph = new SceneGraph()
@@ -93,13 +94,8 @@ describe('export subgraph extraction', () => {
test('fig export preserves imported instance symbol overrides and guids', async () => {
await initCodec()
- const fixture = new Uint8Array(readFileSync('tests/fixtures/gold-preview.fig'))
- const graph = await parseFigFile(
- fixture.buffer.slice(
- fixture.byteOffset,
- fixture.byteOffset + fixture.byteLength
- ) as ArrayBuffer
- )
+ // exportFigFile clones its source, so the shared read-only parse is safe.
+ const { graph } = await sharedGoldPreviewFixture()
const exported = await exportFigFile(graph)
const parsed = parseFigBuffer(exported.buffer as ArrayBuffer)
const input = parsed.nodeChanges.find(
diff --git a/tests/engine/mcp/browser-rpc.test.ts b/tests/engine/mcp/browser-rpc.test.ts
index f9366deac..7299e24d8 100644
--- a/tests/engine/mcp/browser-rpc.test.ts
+++ b/tests/engine/mcp/browser-rpc.test.ts
@@ -285,12 +285,13 @@ describe('BrowserRpcBridge reconnection', () => {
test('sendRPC rejects after timeout when browser never connects', async () => {
const bridge = createBrowserRPCBridge({
authToken: AUTH_TOKEN,
- onConnectionChange: () => undefined
+ onConnectionChange: () => undefined,
+ appWaitTimeoutMs: 50
})
// No browser registered — sendRPC rejects with APP_NOT_CONNECTED.
await expect(bridge.sendRPC(RPC_BODY)).rejects.toThrow('OpenPencil app is not connected')
- }, 12_000)
+ })
test('response from non-browser WebSocket is ignored (ws guard)', async () => {
// Set up two independent WS pairs: one for the browser, one for a
diff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.ts
index e89ade2ae..0b7c70877 100644
--- a/tests/engine/mcp/server/index.test.ts
+++ b/tests/engine/mcp/server/index.test.ts
@@ -131,6 +131,15 @@ test('MCP exposure exclusions apply to both descriptors and registered tools', a
}
})
+describe('startServer option validation', () => {
+ test('rejects an app wait timeout that is not a safe non-negative integer', async () => {
+ await expect(startServer({ appWaitTimeoutMs: -1 })).rejects.toThrow(RangeError)
+ await expect(startServer({ appWaitTimeoutMs: 1.5 })).rejects.toThrow(
+ 'appWaitTimeoutMs must be a safe integer'
+ )
+ })
+})
+
describe('MCP server', () => {
let client: Client
let graph: SceneGraph
diff --git a/tests/engine/mcp/server/transport.test.ts b/tests/engine/mcp/server/transport.test.ts
index 0399e4114..9d1d42649 100644
--- a/tests/engine/mcp/server/transport.test.ts
+++ b/tests/engine/mcp/server/transport.test.ts
@@ -272,7 +272,8 @@ describe('MCP WebSocket stdio bridge routing', () => {
socketPath: testSocketPath(),
authToken: 'bridge-test-token',
enableEval: false,
- mcpRoot: null
+ mcpRoot: null,
+ appWaitTimeoutMs: 50
})
let clientWs: WebSocket | undefined
diff --git a/tests/engine/mcp/stdio/index.test.ts b/tests/engine/mcp/stdio/index.test.ts
index c7c6d1582..83f0d94aa 100644
--- a/tests/engine/mcp/stdio/index.test.ts
+++ b/tests/engine/mcp/stdio/index.test.ts
@@ -46,7 +46,7 @@ async function createStdioClient(socketPath: string, authToken: string | null) {
env.OPENPENCIL_MCP_AUTH_TOKEN = authToken
}
const transport = new StdioClientTransport({
- command: 'bun',
+ command: process.execPath,
args: ['packages/mcp/src/stdio.ts'],
env,
stderr: 'pipe'
@@ -324,7 +324,9 @@ describe('MCP stdio readiness without an open document', () => {
socketPath: isUnix ? join(SOCKET_DIR, 'mcp-no-document.sock') : null,
authToken: NO_DOCUMENT_AUTH_TOKEN,
enableEval: false,
- mcpRoot: null
+ mcpRoot: null,
+ // No app ever registers; the default 10 s wait only slows the assertion.
+ appWaitTimeoutMs: 50
})
let client: Client | undefined
diff --git a/tests/engine/render/canvas/chunks/gold-preview.test.ts b/tests/engine/render/canvas/chunks/gold-preview.test.ts
index 1338c27a0..e7a8aca77 100644
--- a/tests/engine/render/canvas/chunks/gold-preview.test.ts
+++ b/tests/engine/render/canvas/chunks/gold-preview.test.ts
@@ -1,22 +1,19 @@
import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
-import { readFileSync } from 'node:fs'
-import { initCodec, parseFigFile } from '@open-pencil/core'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { RenderChunkIndex } from '#core/canvas/renderer/chunks'
import { expectDefined } from '#tests/helpers/assert'
-import { repoPath } from '#tests/helpers/paths'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
setDefaultTimeout(HEAVY_TEST_TIMEOUT_MS)
-let graph: Awaited<ReturnType<typeof parseFigFile>>
+let graph: SceneGraph
beforeAll(async () => {
- await initCodec()
- const bytes = readFileSync(repoPath('tests/fixtures/gold-preview.fig'))
- graph = await parseFigFile(bytes.buffer as ArrayBuffer, { populate: 'all' })
+ graph = (await sharedGoldPreviewFixture()).graph
}, 60_000)
test('gold-preview render chunks stay bounded and spatial queries stay selective', () => {
diff --git a/tests/engine/render/canvas/tiles/gold-preview.test.ts b/tests/engine/render/canvas/tiles/gold-preview.test.ts
index a1662344f..8ab2edea4 100644
--- a/tests/engine/render/canvas/tiles/gold-preview.test.ts
+++ b/tests/engine/render/canvas/tiles/gold-preview.test.ts
@@ -1,7 +1,6 @@
import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'
-import { readFileSync } from 'node:fs'
-import { initCodec, parseFigFile } from '@open-pencil/core'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { initCanvasKit } from '#cli/headless'
import { SkiaRenderer } from '#core/canvas'
@@ -15,19 +14,17 @@ import {
} from '#core/canvas/renderer/tiles'
import { expectDefined } from '#tests/helpers/assert'
-import { repoPath } from '#tests/helpers/paths'
+import { sharedGoldPreviewFixture } from '#tests/helpers/fig-fixtures'
import { HEAVY_TEST_TIMEOUT_MS } from '#tests/helpers/test-utils'
setDefaultTimeout(HEAVY_TEST_TIMEOUT_MS)
-let graph: Awaited<ReturnType<typeof parseFigFile>>
+let graph: SceneGraph
let ck: Awaited<ReturnType<typeof initCanvasKit>>
beforeAll(async () => {
ck = await initCanvasKit()
- await initCodec()
- const bytes = readFileSync(repoPath('tests/fixtures/gold-preview.fig'))
- graph = await parseFigFile(bytes.buffer as ArrayBuffer, { populate: 'all' })
+ graph = (await sharedGoldPreviewFixture()).graph
}, 60_000)
test('renders one gold-preview tile from a selective chunk query', () => {
diff --git a/tests/engine/render/canvas/visual/boolean.test.ts b/tests/engine/render/canvas/visual/boolean.test.ts
index 58037c7e7..d95e92fad 100644
--- a/tests/engine/render/canvas/visual/boolean.test.ts
+++ b/tests/engine/render/canvas/visual/boolean.test.ts
@@ -35,7 +35,7 @@ function countCellColoredPixels(
describe('boolean visual matrix', () => {
test('generates a non-empty visual fixture for supported shape cases', async () => {
const proc = Bun.spawnSync({
- cmd: ['bun', 'tests/engine/render/canvas/visual/boolean-matrix.ts'],
+ cmd: [process.execPath, 'tests/engine/render/canvas/visual/boolean-matrix.ts'],
stdout: 'pipe',
stderr: 'pipe'
})
diff --git a/tests/engine/scene-graph/plugin-data.test.ts b/tests/engine/scene-graph/plugin-data.test.ts
index adbfa4448..3bf93cbd1 100644
--- a/tests/engine/scene-graph/plugin-data.test.ts
+++ b/tests/engine/scene-graph/plugin-data.test.ts
@@ -13,6 +13,7 @@ import {
import { deduplicateNodeChangePluginData } from '#core/kiwi'
import { expectDefined } from '#tests/helpers/assert'
+import { parseFixture } from '#tests/helpers/fig-fixtures'
function doc(): NodeChange {
return {
@@ -119,11 +120,9 @@ describe('plugin data', () => {
})
test('preserves plugin relaunch data from imported fig files', async () => {
- await initCodec()
- const bytes = new Uint8Array(await Bun.file('./tests/fixtures/material3.fig').arrayBuffer())
- const graph = await parseFigFile(
- bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
- )
+ // Relaunch data lives on the imported node changes themselves, so the
+ // small fixture without instance population is enough to cover it.
+ const graph = await parseFixture('gold-preview.fig', { populate: 'none' })
const nodeWithRelaunch = [...graph.getAllNodes()].find(
(node) => node.pluginRelaunchData.length > 0
)
diff --git a/tests/engine/tauri/document-io.test.ts b/tests/engine/tauri/document-io.test.ts
index f58e3f503..92c6be56f 100644
--- a/tests/engine/tauri/document-io.test.ts
+++ b/tests/engine/tauri/document-io.test.ts
@@ -13,7 +13,7 @@ afterEach(async () => {
describe('Tauri document IO helpers', () => {
test('reads reload source bytes through plugin-fs', async () => {
- const fixture = await Bun.file('tests/fixtures/gold-preview.fig').arrayBuffer()
+ const fixture = await Bun.file('tests/fixtures/circle-text.fig').arrayBuffer()
await mockTauriIPC((cmd, args) => {
expect(cmd).toBe('plugin:fs|read_file')
expect(args).toEqual({ path: '/tmp/document.fig', options: undefined })
diff --git a/tests/engine/tauri/fig-export.test.ts b/tests/engine/tauri/fig-export.test.ts
index fa8d866ed..e1011506c 100644
--- a/tests/engine/tauri/fig-export.test.ts
+++ b/tests/engine/tauri/fig-export.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
describe('Tauri fig export', () => {
test('delegates fig archive construction to the Tauri Rust command', async () => {
- const proc = Bun.spawn(['bun', 'tests/helpers/tauri/fig-export-fixture.ts'], {
+ const proc = Bun.spawn([process.execPath, 'tests/helpers/tauri/fig-export-fixture.ts'], {
stdout: 'pipe',
stderr: 'pipe'
})
diff --git a/tests/engine/tauri/mcp-spawn.test.ts b/tests/engine/tauri/mcp-spawn.test.ts
index 8ef1f98ce..57dfe349f 100644
--- a/tests/engine/tauri/mcp-spawn.test.ts
+++ b/tests/engine/tauri/mcp-spawn.test.ts
@@ -161,7 +161,7 @@ describe('Tauri MCP spawning', () => {
return null
})
- const handle = await spawnMCPIfNeeded()
+ const handle = await spawnMCPIfNeeded({ earlyExitMs: 5, healthPollMs: 5 })
await expect(getAutomationAuthToken()).resolves.toBe('discovery-token')
onEvent?.({ event: 'Stderr', payload: [119, 97, 114, 110] })
handle?.disconnect()
diff --git a/tests/engine/tools/cli.test.ts b/tests/engine/tools/cli.test.ts
index cb9c96295..cddc5e4d1 100644
--- a/tests/engine/tools/cli.test.ts
+++ b/tests/engine/tools/cli.test.ts
@@ -11,7 +11,7 @@ const FIXTURE = repoPath('tests/fixtures/gold-preview.fig')
async function evalCode(
code: string
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
- const proc = Bun.spawn(['bun', CLI, 'eval', FIXTURE, '--code', code, '--json'], {
+ const proc = Bun.spawn([process.execPath, CLI, 'eval', FIXTURE, '--code', code, '--json'], {
stdout: 'pipe',
stderr: 'pipe'
})
diff --git a/tests/engine/tools/read.test.ts b/tests/engine/tools/read.test.ts
index 5b54824ed..c7dfc8729 100644
--- a/tests/engine/tools/read.test.ts
+++ b/tests/engine/tools/read.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { FigmaAPI } from '@open-pencil/core'
+import { DEFAULT_FONT_FAMILY, FigmaAPI, fontManager } from '@open-pencil/core'
import { getTool, setupToolTest, type ALL_TOOLS, type ToolResult } from '#tests/helpers/tools'
@@ -130,12 +130,18 @@ describe('get_font_status', () => {
}>
}
+ // The tool reads the process-wide font manager. A missing family is
+ // 'unresolved' in a pristine process and 'substituted' by the default font
+ // once any earlier suite in the shard has loaded it; both are issues.
+ const defaultLoaded = fontManager.loadedFontSource(DEFAULT_FONT_FAMILY, 'Regular') !== null
+
expect(result.faithful).toBe(false)
expect(result.issues).toEqual([
expect.objectContaining({
family: 'Unavailable Sans',
style: 'Regular',
- status: 'unresolved',
+ status: defaultLoaded ? 'substituted' : 'unresolved',
+ substituteFamily: defaultLoaded ? DEFAULT_FONT_FAMILY : null,
nodeIds: [text.id]
})
])
diff --git a/tests/helpers/cli.ts b/tests/helpers/cli.ts
index e7b4ff4ec..3028c749c 100644
--- a/tests/helpers/cli.ts
+++ b/tests/helpers/cli.ts
@@ -9,7 +9,9 @@ export interface CLICommandResult {
}
export async function runOpenPencilCLI(args: string[]): Promise<CLICommandResult> {
- const proc = Bun.spawn(['bun', CLI, ...args], {
+ // Run the CLI with the Bun that runs the tests, not whatever `bun` PATH
+ // resolves to in the child's cwd (version shims can differ or fail there).
+ const proc = Bun.spawn([process.execPath, CLI, ...args], {
stdout: 'pipe',
stderr: 'pipe'
})
diff --git a/tests/helpers/fig-fixtures.ts b/tests/helpers/fig-fixtures.ts
index bf0b3e1fe..92320a0e8 100644
--- a/tests/helpers/fig-fixtures.ts
+++ b/tests/helpers/fig-fixtures.ts
@@ -67,6 +67,22 @@ export async function parseGoldPreviewFixture(): Promise<{
return { graph, allNodes: collectAllNodes(graph) }
}
+let sharedGoldPreview: ReturnType<typeof parseGoldPreviewFixture> | null = null
+
+/**
+ * The fully populated `gold-preview.fig` graph, parsed once per process.
+ *
+ * Populating its ~38k instance children costs about 3 s and 700 MB, and a
+ * shard runs every file in one Bun process, so read-only suites share the
+ * result instead of paying that per file. Treat the graph as immutable: a
+ * test that creates, updates, deletes or lays out nodes must call
+ * `parseGoldPreviewFixture()` for its own copy.
+ */
+export function sharedGoldPreviewFixture(): ReturnType<typeof parseGoldPreviewFixture> {
+ sharedGoldPreview ??= parseGoldPreviewFixture()
+ return sharedGoldPreview
+}
+
const LFS_POINTER_PREFIX = 'version https://git-lfs'
/**
diff --git a/tools/unit-tests/src/list.ts b/tools/unit-tests/src/list.ts
deleted file mode 100644
index 34801ad5f..000000000
--- a/tools/unit-tests/src/list.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/usr/bin/env bun
-
-import { listHeavyUnitTests, listUnitTests, type UnitTestGroup, unitTestGroupNames } from './shards'
-
-const args = new Set(process.argv.slice(2))
-const groupArg = process.argv.slice(2).find((arg) => !arg.startsWith('--')) ?? 'all'
-const groupNames = unitTestGroupNames()
-
-if (!groupNames.includes(groupArg as UnitTestGroup)) {
- throw new Error(`Unknown unit test group: ${groupArg}. Expected one of: ${groupNames.join(', ')}`)
-}
-
-const group = groupArg as UnitTestGroup
-const files = args.has('--heavy-only')
- ? await listHeavyUnitTests(group)
- : await listUnitTests(group, { includeHeavy: args.has('--include-heavy') })
-
-process.stdout.write(files.join('\n'))
-if (files.length > 0) process.stdout.write('\n')
diff --git a/tools/unit-tests/src/run.ts b/tools/unit-tests/src/run.ts
new file mode 100644
index 000000000..62298f9e4
--- /dev/null
+++ b/tools/unit-tests/src/run.ts
@@ -0,0 +1,41 @@
+#!/usr/bin/env bun
+
+import { listHeavyUnitTests, listUnitTests, type UnitTestGroup, unitTestGroupNames } from './shards'
+
+/**
+ * Runs `bun test` over one shard group.
+ *
+ * bun tools/unit-tests/src/run.ts [group] [--include-heavy | --heavy-only] [-- <bun test args>]
+ *
+ * Quick runs (the default) skip heavy fixture files and heavy-marked blocks;
+ * `--include-heavy` runs everything and `--heavy-only` runs only the heavy
+ * fixture files. Arguments after `--` go to `bun test` unchanged.
+ */
+const separator = process.argv.indexOf('--')
+const ownArgs = separator === -1 ? process.argv.slice(2) : process.argv.slice(2, separator)
+const bunTestArgs = separator === -1 ? [] : process.argv.slice(separator + 1)
+const flags = new Set(ownArgs.filter((arg) => arg.startsWith('--')))
+const group = (ownArgs.find((arg) => !arg.startsWith('--')) ?? 'all') as UnitTestGroup
+
+if (!unitTestGroupNames().includes(group)) {
+ throw new Error(
+ `Unknown unit test group: ${group}. Expected one of: ${unitTestGroupNames().join(', ')}`
+ )
+}
+
+const heavyOnly = flags.has('--heavy-only')
+const includeHeavy = heavyOnly || flags.has('--include-heavy')
+const files = heavyOnly
+ ? await listHeavyUnitTests(group)
+ : await listUnitTests(group, { includeHeavy })
+
+if (files.length === 0) {
+ console.log(`No unit tests found for shard ${group}`)
+ process.exit(0)
+}
+
+const child = Bun.spawn([process.execPath, 'test', ...bunTestArgs, ...files], {
+ stdio: ['inherit', 'inherit', 'inherit'],
+ env: { ...process.env, BUN_HEAVY_TESTS: includeHeavy ? 'true' : 'false' }
+})
+process.exit(await child.exited)
diff --git a/tools/unit-tests/src/shards.ts b/tools/unit-tests/src/shards.ts
index f68323c68..3e0d681f1 100644
--- a/tools/unit-tests/src/shards.ts
+++ b/tools/unit-tests/src/shards.ts
@@ -1,42 +1,66 @@
+import { existsSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
+/**
+ * Unit test shards, keyed by owning package or application area.
+ *
+ * Each group lists the owner's canonical test home from
+ * `packages/docs/development/testing.md` (`packages/<owner>/tests`,
+ * `tests/app`, `tests/integration`) together with the `tests/engine/**`
+ * directories it still owns, so a file is discovered from either place and a
+ * move needs no shard change. A path that does not exist yet contributes no
+ * files. `render` is Core-owned but
+ * sharded separately because canvas suites parse large fixtures.
+ */
export const UNIT_TEST_GROUPS = {
app: [
+ 'tests/app',
+ 'tests/integration',
'tests/engine/acp',
'tests/engine/app',
- 'tests/engine/cli',
'tests/engine/collab',
'tests/engine/tauri'
],
- dom: ['tests/engine/dom-css', 'tests/engine/color', 'tests/engine/icons', 'tests/engine/pen'],
- editor: [
+ cli: ['packages/cli/tests', 'tests/engine/cli'],
+ core: [
+ 'packages/core/tests',
'tests/engine/clipboard',
+ 'tests/engine/color',
'tests/engine/core',
'tests/engine/editor',
- 'tests/engine/hit-test',
- 'tests/engine/snap'
- ],
- fig: ['tests/engine/figma', 'tests/engine/io', 'tests/engine/kiwi'],
- render: ['tests/engine/geometry', 'tests/engine/layout', 'tests/engine/render'],
- scene: [
- 'tests/engine/bytes',
+ 'tests/engine/icons',
+ 'tests/engine/layout',
'tests/engine/library',
'tests/engine/lint',
+ 'tests/engine/profiler',
+ 'tests/engine/text',
+ 'tests/engine/tools',
+ 'tests/engine/vector'
+ ],
+ dom: ['packages/dom-css/tests', 'packages/pen/tests', 'tests/engine/dom-css', 'tests/engine/pen'],
+ fig: [
+ 'packages/fig/tests',
+ 'packages/kiwi/tests',
+ 'tests/engine/bytes',
+ 'tests/engine/figma',
+ 'tests/engine/io',
+ 'tests/engine/kiwi'
+ ],
+ mcp: ['packages/mcp/tests', 'tests/engine/mcp'],
+ render: ['tests/engine/render'],
+ 'scene-graph': [
+ 'packages/scene-graph/tests',
+ 'tests/engine/geometry',
+ 'tests/engine/hit-test',
'tests/engine/random',
'tests/engine/scene-graph',
- 'tests/engine/text'
+ 'tests/engine/snap'
],
- vue: [
- 'tests/engine/mcp',
- 'tests/engine/profiler',
- 'tests/engine/tools',
- 'tests/engine/vector',
- 'tests/engine/vue'
- ]
+ vue: ['packages/vue/tests', 'tests/engine/vue']
} as const
export type UnitTestGroup = keyof typeof UNIT_TEST_GROUPS | 'all'
@@ -90,6 +114,7 @@ async function listTestFiles(paths: string[]): Promise<string[]> {
async function listTestFilesInPath(path: string): Promise<string[]> {
const absolutePath = resolve(REPO_ROOT, path)
+ if (!existsSync(absolutePath)) return []
const entries = await readdir(absolutePath, { withFileTypes: true })
const files = await Promise.all(
entries.map(async (entry) => {
diff --git a/tools/unit-tests/tests/shards.test.ts b/tools/unit-tests/tests/shards.test.ts
index 5b0e953f5..b9cf791c9 100644
--- a/tools/unit-tests/tests/shards.test.ts
+++ b/tools/unit-tests/tests/shards.test.ts
@@ -9,12 +9,17 @@ import {
unitTestGroupNames
} from '../src/shards'
-test('every engine test belongs to exactly one shard', async () => {
- const discovered = await Array.fromAsync(
- new Bun.Glob('tests/engine/**/*.test.ts').scan({
- cwd: fileURLToPath(new URL('../../..', import.meta.url))
- })
- )
+const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
+
+async function discover(pattern: string): Promise<string[]> {
+ return Array.fromAsync(new Bun.Glob(pattern).scan({ cwd: REPO_ROOT }))
+}
+
+test('every engine and package-local test belongs to exactly one shard', async () => {
+ const discovered = [
+ ...(await discover('tests/engine/**/*.test.ts')),
+ ...(await discover('packages/*/tests/**/*.test.ts'))
+ ].filter((file) => !file.startsWith('packages/harness/'))
const paths = pathsForUnitTestGroup('all')
const invalidAssignments = discovered.flatMap((file) => {
const owners = paths.filter((path) => file.startsWith(`${path}/`))
@@ -26,6 +31,26 @@ test('every engine test belongs to exactly one shard', async () => {
expect((await listUnitTests('all', { includeHeavy: true })).sort()).toEqual(discovered.sort())
})
+test('canonical destinations are registered before they hold files', async () => {
+ const paths = pathsForUnitTestGroup('all')
+ expect(paths).toContain('tests/app')
+ expect(paths).toContain('tests/integration')
+ for (const owner of [
+ 'core',
+ 'scene-graph',
+ 'vue',
+ 'fig',
+ 'kiwi',
+ 'dom-css',
+ 'pen',
+ 'cli',
+ 'mcp'
+ ]) {
+ expect(paths).toContain(`packages/${owner}/tests`)
+ }
+ await expect(listUnitTests('all')).resolves.toBeArray()
+})
+
test('quick and explicit heavy tests partition the full engine suite', async () => {
const quick = await listUnitTests('all')
const heavy = await listHeavyUnitTests()
@@ -38,6 +63,7 @@ test('quick and explicit heavy tests partition the full engine suite', async ()
test('unit test groups cover all declared shards', () => {
expect(unitTestGroupNames()).toContain('all')
expect(pathsForUnitTestGroup('dom')).toContain('tests/engine/dom-css')
+ expect(pathsForUnitTestGroup('fig')).toContain('packages/fig/tests')
expect(pathsForUnitTestGroup('all')).toContain('tests/engine/io')
})