diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn index fba4cac7bc..1b91e14d7a 100644 --- a/.clj-kondo/config.edn +++ b/.clj-kondo/config.edn @@ -88,6 +88,9 @@ :dynamic-var-not-earmuffed {:level :off} + :type-mismatch + {:level :off} + :used-underscored-binding {:level :warning} diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000..b8c352b7cd --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +# Penpot API configuration for error-reports CLI tool +PENPOT_API_URI=http://localhost:3450 +PENPOT_ACCESS_TOKEN=your-access-token-here diff --git a/.github/workflows/build-bundle.yml b/.github/workflows/build-bundle.yml index 441587eea3..e785f2c84e 100644 --- a/.github/workflows/build-bundle.yml +++ b/.github/workflows/build-bundle.yml @@ -9,16 +9,6 @@ on: type: string required: true default: 'develop' - build_wasm: - description: 'BUILD_WASM. Valid values: yes, no' - type: string - required: false - default: 'yes' - build_storybook: - description: 'BUILD_STORYBOOK. Valid values: yes, no' - type: string - required: false - default: 'yes' workflow_call: inputs: gh_ref: @@ -26,29 +16,21 @@ on: type: string required: true default: 'develop' - build_wasm: - description: 'BUILD_WASM. Valid values: yes, no' - type: string - required: false - default: 'yes' - build_storybook: - description: 'BUILD_STORYBOOK. Valid values: yes, no' - type: string - required: false - default: 'yes' concurrency: group: ${{ github.workflow }}-${{ inputs.gh_ref }} cancel-in-progress: true jobs: - build-bundle: - name: Build and Upload Penpot Bundle + # ── 1. Decide whether there is anything to build ─────────────────────── + check: + name: Check current bundle runs-on: penpot-runner-01 - env: - AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + timeout-minutes: 10 + outputs: + gh_ref: ${{ steps.vars.outputs.gh_ref }} + bundle_version: ${{ steps.vars.outputs.bundle_version }} + exists: ${{ steps.check.outputs.exists }} steps: - name: Checkout repository @@ -63,10 +45,52 @@ jobs: echo "gh_ref=${{ inputs.gh_ref || github.ref_name }}" >> $GITHUB_OUTPUT echo "bundle_version=$(git describe --tags --always)" >> $GITHUB_OUTPUT + # The uploaded zip carries its version as S3 metadata. If the + # existing object was already built from this same commit, the + # whole build job is skipped. + - name: Check if this bundle is already built + id: check + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + run: | + EXISTING_VERSION=$(aws s3api head-object \ + --bucket ${{ secrets.S3_BUCKET }} \ + --key "penpot-${{ steps.vars.outputs.gh_ref }}.zip" \ + --query 'Metadata."bundle-version"' \ + --output text 2>/dev/null || echo "none") + + if [ "$EXISTING_VERSION" = "${{ steps.vars.outputs.bundle_version }}" ]; then + echo "exists=true" >> $GITHUB_OUTPUT + { + echo "### ⏭️ Bundle build skipped" + echo "" + echo "The bundle in S3 was already built from \`${{ steps.vars.outputs.bundle_version }}\`." + } >> "$GITHUB_STEP_SUMMARY" + else + echo "exists=false" >> $GITHUB_OUTPUT + fi + + # ── 2. Build and upload, only when needed ────────────────────────────── + build: + name: Build and Upload Penpot Bundle + runs-on: penpot-runner-01 + timeout-minutes: 90 + needs: check + if: needs.check.outputs.exists == 'false' + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + ref: ${{ inputs.gh_ref }} + - name: Build bundle env: - BUILD_WASM: ${{ inputs.build_wasm }} - BUILD_STORYBOOK: ${{ inputs.build_storybook }} + BUILD_WASM: 'yes' + BUILD_STORYBOOK: 'yes' run: ./manage.sh build-bundle - name: Prepare directories for zipping @@ -80,18 +104,32 @@ jobs: zip -r zips/penpot.zip penpot - name: Upload Penpot bundle to S3 + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} run: | - aws s3 cp zips/penpot.zip s3://${{ secrets.S3_BUCKET }}/penpot-${{ steps.vars.outputs.gh_ref }}.zip --metadata bundle-version=${{ steps.vars.outputs.bundle_version }} + aws s3 cp zips/penpot.zip \ + s3://${{ secrets.S3_BUCKET }}/penpot-${{ needs.check.outputs.gh_ref }}.zip \ + --metadata bundle-version=${{ needs.check.outputs.bundle_version }} + # ── 3. Single failure notification for the whole workflow ───────────── + notify: + name: Notify failure + runs-on: penpot-runner-01 + timeout-minutes: 5 + needs: [check, build] + if: failure() + + steps: - name: Notify Mattermost - if: failure() uses: mattermost/action-mattermost-notify@ae31bb6f9e26a54336e79696f108a2c91cf55b4e # v2.1.0 with: MATTERMOST_WEBHOOK_URL: ${{ secrets.MATTERMOST_WEBHOOK }} MATTERMOST_CHANNEL: bot-alerts-cicd TEXT: | ❌ 📦 *[PENPOT] Error building penpot bundles.* - 📄 Triggered from ref: `${{ steps.vars.outputs.gh_ref }}` - Bundle version: `${{ steps.vars.outputs.bundle_version }}` + 📄 Triggered from ref: `${{ needs.check.outputs.gh_ref || inputs.gh_ref }}` + Bundle version: `${{ needs.check.outputs.bundle_version || 'n/a' }}` 🔗 Run: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} @infra diff --git a/.github/workflows/build-develop.yml b/.github/workflows/build-develop.yml index 8125c81e12..b0edcb63cb 100644 --- a/.github/workflows/build-develop.yml +++ b/.github/workflows/build-develop.yml @@ -11,8 +11,6 @@ jobs: secrets: inherit with: gh_ref: "develop" - build_wasm: "yes" - build_storybook: "yes" build-docker: needs: build-bundle @@ -20,3 +18,9 @@ jobs: secrets: inherit with: gh_ref: "develop" + + build-docker-admin-console: + uses: ./.github/workflows/build-docker-admin-console.yml + secrets: inherit + with: + gh_ref: "develop" diff --git a/.github/workflows/build-docker-admin-console.yml b/.github/workflows/build-docker-admin-console.yml new file mode 100644 index 0000000000..b3f8384636 --- /dev/null +++ b/.github/workflows/build-docker-admin-console.yml @@ -0,0 +1,91 @@ +name: Admin Console Docker Builder + +on: + workflow_dispatch: + inputs: + gh_ref: + description: 'Name of the branch or ref to build in penpot-nitrate' + type: string + required: true + default: 'develop' + dispatch_ref: + description: 'Branch of penpot-nitrate from which the workflow definition is read' + type: string + required: false + default: 'develop' + workflow_call: + inputs: + gh_ref: + description: 'Name of the branch or ref to build in penpot-nitrate' + type: string + required: true + dispatch_ref: + description: 'Branch of penpot-nitrate from which the workflow definition is read' + type: string + required: false + default: 'develop' + secrets: + ORG_WORKFLOW_TOKEN: + description: 'Token with Actions write access on penpot-nitrate' + required: true + +jobs: + build-nitrate-docker: + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ secrets.ORG_WORKFLOW_TOKEN }} + REPO: penpot/penpot-nitrate + WORKFLOW: build-docker-admin-console.yml + GH_REF: ${{ inputs.gh_ref }} + DISPATCH_REF: ${{ inputs.dispatch_ref }} + steps: + - name: Trigger nitrate docker build + id: dispatch + run: | + DISTINCT_ID="${{ github.run_id }}-${{ github.run_attempt }}" + CALLER_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" + + gh workflow run "$WORKFLOW" --repo "$REPO" --ref "$DISPATCH_REF" \ + -f gh_ref="$GH_REF" \ + -f caller_run_id="$DISTINCT_ID" \ + -f caller_run_url="$CALLER_URL" + + # Locate the dispatched run using the correlation id embedded in its run-name + RUN_ID="" + for i in $(seq 1 24); do + sleep 5 + RUN_ID=$(gh run list --repo "$REPO" --workflow "$WORKFLOW" \ + --limit 10 --json databaseId,displayTitle \ + --jq ".[] | select(.displayTitle | contains(\"$DISTINCT_ID\")) | .databaseId" \ + | head -n1) + [ -n "$RUN_ID" ] && break + done + + if [ -z "$RUN_ID" ]; then + echo "::error::Could not locate the dispatched run in $REPO" + exit 1 + fi + + RUN_URL="https://github.com/$REPO/actions/runs/$RUN_ID" + echo "run_id=$RUN_ID" >> "$GITHUB_OUTPUT" + echo "run_url=$RUN_URL" >> "$GITHUB_OUTPUT" + echo "::notice title=Nitrate docker build::$RUN_URL" + + - name: Wait for nitrate docker build + run: | + gh run watch "${{ steps.dispatch.outputs.run_id }}" \ + --repo "$REPO" \ + --interval 30 \ + --exit-status + + - name: Report result + if: always() && steps.dispatch.outputs.run_id != '' + run: | + CONCLUSION=$(gh run view "${{ steps.dispatch.outputs.run_id }}" \ + --repo "$REPO" --json conclusion --jq '.conclusion') + { + echo "### 🐳 Nitrate docker build" + echo "" + echo "- Result: \`${CONCLUSION:-in_progress}\`" + echo "- Run: ${{ steps.dispatch.outputs.run_url }}" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/build-docker-devenv.yml b/.github/workflows/build-docker-devenv.yml index 5faafba350..b0340d329b 100644 --- a/.github/workflows/build-docker-devenv.yml +++ b/.github/workflows/build-docker-devenv.yml @@ -20,12 +20,19 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 - - name: Login to Docker Registry + - name: Login to Docker Registry (push destination) uses: docker/login-action@v4 with: username: ${{ secrets.PUB_DOCKER_USERNAME }} password: ${{ secrets.PUB_DOCKER_PASSWORD }} + - name: Login to Docker Hardened Images registry (base image pull) + uses: docker/login-action@v4 + with: + registry: dhi.io + username: ${{ secrets.PUB_DOCKER_USERNAME }} + password: ${{ secrets.PUB_DOCKER_PASSWORD }} + - name: Build and push DevEnv Docker image uses: docker/build-push-action@v7 env: @@ -35,6 +42,8 @@ jobs: file: ./docker/devenv/Dockerfile platforms: linux/amd64,linux/arm64 push: true + provenance: mode=max + sbom: true tags: ${{ env.DOCKER_IMAGE }}:latest cache-from: type=registry,ref=${{ env.DOCKER_IMAGE }}:buildcache cache-to: type=registry,ref=${{ env.DOCKER_IMAGE }}:buildcache,mode=max diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml index e2497f3093..0d03490194 100644 --- a/.github/workflows/build-docker.yml +++ b/.github/workflows/build-docker.yml @@ -20,55 +20,117 @@ concurrency: group: ${{ github.workflow }}-${{ inputs.gh_ref }} cancel-in-progress: true +env: + ALL_IMAGES: backend frontend exporter storybook mcp + # All runner instances live on the same server, so the bundle is + # downloaded from S3 once and shared between build jobs through this + # host-local directory. Each build job falls back to S3 if the file is + # missing (e.g. if runners ever move to separate machines). + BUNDLE_CACHE: /var/tmp/penpot-bundle-cache + jobs: - build-and-push: - name: Build and Push Penpot Docker Images + # ── 1. Resolve the build key and check the whole set at once ─────────── + prepare: + name: Prepare runs-on: penpot-runner-02 + timeout-minutes: 15 + outputs: + gh_ref: ${{ steps.vars.outputs.gh_ref }} + bundle_version: ${{ steps.vars.outputs.bundle_version }} + build_key: ${{ steps.vars.outputs.build_key }} + exists: ${{ steps.check.outputs.exists }} + + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ inputs.gh_ref }} + + - name: Extract some useful variables + id: vars + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + run: | + GH_REF="${{ inputs.gh_ref || github.ref_name }}" + echo "gh_ref=$GH_REF" >> $GITHUB_OUTPUT + + BUNDLE_VERSION=$(aws s3api head-object \ + --bucket ${{ secrets.S3_BUCKET }} \ + --key "penpot-$GH_REF.zip" \ + --query 'Metadata."bundle-version"' \ + --output text) + echo "bundle_version=$BUNDLE_VERSION" >> $GITHUB_OUTPUT + + # Image content = bundle + docker build context, so the build key + # combines both. + CTX_HASH=$(git rev-parse "HEAD:docker/images" | cut -c1-12) + echo "build_key=${BUNDLE_VERSION}-${CTX_HASH}" >> $GITHUB_OUTPUT + + # The image set is a single block, so a single set-level check is + # enough: `promote` drops a marker object in S3 only after every + # image was built AND every branch tag was moved. Marker present + # means there is nothing at all to do for this build key. + - name: Check if this image set is already built + id: check + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + run: | + if aws s3api head-object \ + --bucket ${{ secrets.S3_BUCKET }} \ + --key "markers/images-${{ steps.vars.outputs.build_key }}" \ + > /dev/null 2>&1; then + echo "exists=true" >> $GITHUB_OUTPUT + { + echo "### ⏭️ Image set build skipped" + echo "" + echo "The whole set was already built and promoted for \`${{ steps.vars.outputs.build_key }}\`." + } >> "$GITHUB_STEP_SUMMARY" + else + echo "exists=false" >> $GITHUB_OUTPUT + + # Stage the bundle in the host-local cache, once, for all the + # build jobs. Download to a temp name and mv for atomicity; + # prune stale bundles while at it. + mkdir -p "$BUNDLE_CACHE" + find "$BUNDLE_CACHE" -type f -mtime +1 -delete || true + ZIP="$BUNDLE_CACHE/penpot-${{ steps.vars.outputs.build_key }}.zip" + if [ ! -f "$ZIP" ]; then + aws s3 cp "s3://${{ secrets.S3_BUCKET }}/penpot-${{ steps.vars.outputs.gh_ref }}.zip" "$ZIP.$$.tmp" + mv "$ZIP.$$.tmp" "$ZIP" + fi + fi + + # ── 2. One build per image, in parallel, only when needed ────────────── + build: + name: Build ${{ matrix.image }} + runs-on: penpot-runner-02 + timeout-minutes: 60 + needs: prepare + if: needs.prepare.outputs.exists == 'false' + strategy: + fail-fast: true + # 4 runner slots are available for build jobs on this server; cap the + # matrix at 3 so short jobs (prepare and other workflows' checks) + # never queue behind long builds. + max-parallel: 3 + matrix: + image: [backend, frontend, exporter, storybook, mcp] steps: - name: Set common environment variables run: | # Each job execution will use its own docker configuration. - echo "DOCKER_CONFIG=${{ runner.temp }}/.docker-${{ github.run_id }}-${{ github.job }}" >> $GITHUB_ENV + echo "DOCKER_CONFIG=${{ runner.temp }}/.docker-${{ github.run_id }}-${{ github.job }}-${{ matrix.image }}" >> $GITHUB_ENV - name: Checkout code uses: actions/checkout@v6 with: - fetch-depth: 0 ref: ${{ inputs.gh_ref }} - - name: Extract some useful variables - id: vars - run: | - echo "gh_ref=${{ inputs.gh_ref || github.ref_name }}" >> $GITHUB_OUTPUT - - - name: Download Penpot Bundles - id: bundles - env: - FILE_NAME: penpot-${{ steps.vars.outputs.gh_ref }}.zip - AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} - AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} - AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} - run: | - tmp=$(aws s3api head-object \ - --bucket ${{ secrets.S3_BUCKET }} \ - --key "$FILE_NAME" \ - --query 'Metadata."bundle-version"' \ - --output text) - echo "bundle_version=$tmp" >> $GITHUB_OUTPUT - pushd docker/images - aws s3 cp s3://${{ secrets.S3_BUCKET }}/$FILE_NAME . - unzip $FILE_NAME > /dev/null - mv penpot/backend bundle-backend - mv penpot/frontend bundle-frontend - mv penpot/exporter bundle-exporter - mv penpot/storybook bundle-storybook - mv penpot/mcp bundle-mcp - popd - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 - - name: Login to Docker Registry uses: docker/login-action@v4 with: @@ -85,103 +147,140 @@ jobs: username: ${{ secrets.PUB_DOCKER_USERNAME }} password: ${{ secrets.PUB_DOCKER_PASSWORD }} + # Images now build FROM Docker Hardened Images (dhi.io). DHI + # is free (Apache 2.0, no subscription), but pulling from it + # still requires an authenticated login -- a separate `docker + # login` against a different registry host, even though it + # reuses the same PUB_DOCKER_* credentials as the DockerHub + # login above. + - name: Login to Docker Hardened Images registry (base image pull) + uses: docker/login-action@v4 + with: + registry: dhi.io + username: ${{ secrets.PUB_DOCKER_USERNAME }} + password: ${{ secrets.PUB_DOCKER_PASSWORD }} + + # Bundle staged once by `prepare` on this host; the S3 fallback only + # triggers if the cache is unavailable (runners on another machine, + # cache pruned mid-run, ...). + - name: Prepare Penpot bundle + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + run: | + ZIP="$BUNDLE_CACHE/penpot-${{ needs.prepare.outputs.build_key }}.zip" + if [ ! -f "$ZIP" ]; then + echo "Bundle not found in host cache; falling back to S3." + mkdir -p "$BUNDLE_CACHE" + aws s3 cp "s3://${{ secrets.S3_BUCKET }}/penpot-${{ needs.prepare.outputs.gh_ref }}.zip" "$ZIP.$$.tmp" + mv "$ZIP.$$.tmp" "$ZIP" + fi + # Extract only the bundle this job needs. + pushd docker/images + unzip -q "$ZIP" "penpot/${{ matrix.image }}/*" + mv "penpot/${{ matrix.image }}" "bundle-${{ matrix.image }}" + popd + + - name: Set up QEMU (stable) + uses: docker/setup-qemu-action@v4 + with: + platforms: linux/amd64,linux/arm64 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + - name: Extract metadata (tags, labels) id: meta uses: docker/metadata-action@v6 with: - images: - frontend - backend - exporter - storybook - mcp + images: ${{ matrix.image }} labels: | - bundle_version=${{ steps.bundles.outputs.bundle_version }} + bundle_version=${{ needs.prepare.outputs.bundle_version }} - - name: Build and push Backend Docker image + - name: Build and push Docker image uses: docker/build-push-action@v7 - env: - DOCKER_IMAGE: 'backend' - BUNDLE_PATH: './bundle-backend' with: context: ./docker/images/ - file: ./docker/images/Dockerfile.backend + file: ./docker/images/Dockerfile.${{ matrix.image }} platforms: linux/amd64,linux/arm64 push: true - tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.vars.outputs.gh_ref }} + provenance: mode=max + sbom: true + # Immutable tag only; branch tags are moved atomically for the + # whole image set by the `promote` job. + tags: ${{ secrets.DOCKER_REGISTRY }}/${{ matrix.image }}:build-${{ needs.prepare.outputs.build_key }} labels: ${{ steps.meta.outputs.labels }} - cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache - cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache,mode=max + cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ matrix.image }}:buildcache + cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ matrix.image }}:buildcache,mode=max - - name: Build and push Frontend Docker image - uses: docker/build-push-action@v7 - env: - DOCKER_IMAGE: 'frontend' - BUNDLE_PATH: './bundle-frontend' + # ── 3. Move the branch tags of ALL images together ───────────────────── + # Runs only when every build succeeded (default `needs` semantics); if + # the set was already complete, `build` is skipped and so is this job — + # the S3 marker guarantees the branch tags were already moved. + promote: + name: Promote image set + runs-on: penpot-runner-02 + timeout-minutes: 10 + needs: [prepare, build] + + steps: + - name: Set common environment variables + run: | + echo "DOCKER_CONFIG=${{ runner.temp }}/.docker-${{ github.run_id }}-${{ github.job }}" >> $GITHUB_ENV + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Login to Docker Registry + uses: docker/login-action@v4 with: - context: ./docker/images/ - file: ./docker/images/Dockerfile.frontend - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.vars.outputs.gh_ref }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache - cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache,mode=max + registry: ${{ secrets.DOCKER_REGISTRY }} + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} - - name: Build and push Exporter Docker image - uses: docker/build-push-action@v7 + - name: Point branch tags to the new build key + run: | + set -e + for image in $ALL_IMAGES; do + docker buildx imagetools create \ + -t "${{ secrets.DOCKER_REGISTRY }}/$image:${{ needs.prepare.outputs.gh_ref }}" \ + "${{ secrets.DOCKER_REGISTRY }}/$image:build-${{ needs.prepare.outputs.build_key }}" + done + + # The marker is written LAST: its presence certifies that all five + # images exist and all branch tags point to this build key. + - name: Write set-completed marker env: - DOCKER_IMAGE: 'exporter' - BUNDLE_PATH: './bundle-exporter' - with: - context: ./docker/images/ - file: ./docker/images/Dockerfile.exporter - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.vars.outputs.gh_ref }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache - cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache,mode=max + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: ${{ secrets.AWS_REGION }} + run: | + echo "${{ github.run_id }}" | aws s3 cp - \ + "s3://${{ secrets.S3_BUCKET }}/markers/images-${{ needs.prepare.outputs.build_key }}" + { + echo "### ✅ Image set promoted" + echo "" + echo "All \`:${{ needs.prepare.outputs.gh_ref }}\` tags now point to \`build-${{ needs.prepare.outputs.build_key }}\`." + } >> "$GITHUB_STEP_SUMMARY" - - name: Build and push Storybook Docker image - uses: docker/build-push-action@v7 - env: - DOCKER_IMAGE: 'storybook' - BUNDLE_PATH: './bundle-storybook' - with: - context: ./docker/images/ - file: ./docker/images/Dockerfile.storybook - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.vars.outputs.gh_ref }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache - cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache,mode=max - - - name: Build and push MCP Docker image - uses: docker/build-push-action@v7 - env: - DOCKER_IMAGE: 'mcp' - BUNDLE_PATH: './bundle-mcp' - with: - context: ./docker/images/ - file: ./docker/images/Dockerfile.mcp - platforms: linux/amd64,linux/arm64 - push: true - tags: ${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:${{ steps.vars.outputs.gh_ref }} - labels: ${{ steps.meta.outputs.labels }} - cache-from: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache - cache-to: type=registry,ref=${{ secrets.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}:buildcache,mode=max + # ── 4. Single failure notification for the whole workflow ───────────── + notify: + name: Notify failure + runs-on: penpot-runner-02 + timeout-minutes: 5 + needs: [prepare, build, promote] + if: failure() + steps: - name: Notify Mattermost - if: failure() uses: mattermost/action-mattermost-notify@ae31bb6f9e26a54336e79696f108a2c91cf55b4e # v2.1.0 with: MATTERMOST_WEBHOOK_URL: ${{ secrets.MATTERMOST_WEBHOOK }} MATTERMOST_CHANNEL: bot-alerts-cicd TEXT: | - ❌ 🐳 *[PENPOT] Error building penpot docker images.* - 📄 Triggered from ref: `${{ steps.vars.outputs.gh_ref }}` - 📦 Bundle: `${{ steps.bundles.outputs.bundle_version }}` + ❌ 🐳 *[PENPOT] Error building/promoting the penpot docker image set.* + 📄 Triggered from ref: `${{ needs.prepare.outputs.gh_ref || inputs.gh_ref }}` + 📦 Bundle: `${{ needs.prepare.outputs.bundle_version || 'n/a' }}` 🔗 Run: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} @infra diff --git a/.github/workflows/build-staging.yml b/.github/workflows/build-staging.yml index 572d8c2a95..ec3003a4b2 100644 --- a/.github/workflows/build-staging.yml +++ b/.github/workflows/build-staging.yml @@ -11,8 +11,6 @@ jobs: secrets: inherit with: gh_ref: "staging" - build_wasm: "yes" - build_storybook: "yes" build-docker: needs: build-bundle @@ -20,3 +18,9 @@ jobs: secrets: inherit with: gh_ref: "staging" + + build-docker-admin-console: + uses: ./.github/workflows/build-docker-admin-console.yml + secrets: inherit + with: + gh_ref: "staging" diff --git a/.github/workflows/build-tag.yml b/.github/workflows/build-tag.yml index c47d19570c..18f81d10f1 100644 --- a/.github/workflows/build-tag.yml +++ b/.github/workflows/build-tag.yml @@ -12,8 +12,6 @@ jobs: secrets: inherit with: gh_ref: ${{ github.ref_name }} - build_wasm: "yes" - build_storybook: "yes" build-docker: needs: build-bundle @@ -22,11 +20,18 @@ jobs: with: gh_ref: ${{ github.ref_name }} + build-docker-admin-console: + uses: ./.github/workflows/build-docker-admin-console.yml + secrets: inherit + with: + gh_ref: ${{ github.ref_name }} + notify: name: Notifications runs-on: ubuntu-24.04 - needs: build-docker - + needs: + - build-docker + - build-docker-admin-console steps: - name: Notify Mattermost uses: mattermost/action-mattermost-notify@ae31bb6f9e26a54336e79696f108a2c91cf55b4e # v2.1.0 @@ -40,7 +45,9 @@ jobs: publish-final-tag: if: ${{ !contains(github.ref_name, '-RC') && !contains(github.ref_name, '-alpha') && !contains(github.ref_name, '-beta') && contains(github.ref_name, '.') }} - needs: build-docker + needs: + - build-docker + - build-docker-admin-console uses: ./.github/workflows/release.yml secrets: inherit with: diff --git a/.github/workflows/tests-composable-suite.yml b/.github/workflows/tests-composable-suite.yml new file mode 100644 index 0000000000..1ad48c0edf --- /dev/null +++ b/.github/workflows/tests-composable-suite.yml @@ -0,0 +1,69 @@ +name: "CI: Composable Test Suite" + +# Runs the composable component test suite (it exercises component semantics +# through the real Plugin API against the full frontend, so it needs the +# frontend bundle + the plugin runtime, but no backend): the driver serves the +# prebuilt frontend bundle and intercepts every backend RPC with Playwright +# fixtures. See plugins/apps/composable-test-suite/README.md ("Running in CI"). + +defaults: + run: + shell: bash + +on: + pull_request: + paths: + - 'plugins/**' + - 'frontend/**' + - 'common/**' + types: + - opened + - synchronize + - ready_for_review + + push: + branches: + - develop + - staging + paths: + - 'plugins/**' + - 'frontend/**' + - 'common/**' + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + composable-test-suite: + if: ${{ !github.event.pull_request.draft }} + name: "Run composable test suite (mocked backend)" + runs-on: penpot-runner-02 + container: + image: penpotapp/devenv:latest + volumes: + - /var/cache/github-runner/m2:/root/.m2 + - /var/cache/github-runner/gitlib:/root/.gitlibs + + steps: + - uses: actions/checkout@v6 + + # The driver serves the prebuilt bundle from frontend/resources/public. + - name: Build frontend bundle + working-directory: ./frontend + run: ./scripts/build + + - name: Install deps + working-directory: ./plugins + run: | + corepack enable; + corepack install; + pnpm install; + + - name: Install Playwright Chromium + working-directory: ./plugins + run: pnpm --filter composable-test-suite exec playwright install --with-deps chromium + + - name: Run composable test suite (mocked) + working-directory: ./plugins + run: pnpm --filter composable-test-suite run test:ci diff --git a/.gitignore b/.gitignore index 2fbd8f5971..81e6733053 100644 --- a/.gitignore +++ b/.gitignore @@ -59,6 +59,8 @@ opencode.json /docker/images/bundle* /exporter/target /exporter/.shadow-cljs +/exporter/resources/wasm/ +/exporter/src/app/wasm/shared.js /frontend/.storybook/preview-body.html /frontend/.storybook/preview-head.html /frontend/playwright-report/ @@ -89,6 +91,7 @@ opencode.json /blob-report/ /playwright/.cache/ /render-wasm/target/ +/media-processor/dist/ /**/node_modules /**/.yarn/* /.pnpm-store @@ -102,6 +105,7 @@ opencode.json /.opencode/plans /.opencode/reports /.opencode/prompts +/.ci-logs /.codex/ /tools/__pycache__ /performance/results/ \ No newline at end of file diff --git a/.nvmrc b/.nvmrc index 5bcf9c6e6a..87d8620cc6 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24.18.0 +v24.18.1 diff --git a/.opencode/agents/commiter.md b/.opencode/agents/commiter.md deleted file mode 100644 index a5e128e4d1..0000000000 --- a/.opencode/agents/commiter.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -name: commiter -description: Git commit assistant -mode: subagent -permission: - read: allow - glob: allow - grep: allow - edit: deny - webfetch: deny - websearch: deny - task: deny - skill: deny - lsp: deny - todowrite: deny - question: deny - external_directory: deny - bash: allow ---- - -## Role - -You are the Penpot commit assistant. You produce git commits that follow the -repository's commit conventions. You do not implement features, review code, or -push branches — you commit. - -## Required Reading - -Before drafting any commit, **read `.serena/memories/workflow/creating-commits.md` -end-to-end**. It is the authoritative source for the commit message format, the -emoji menu, subject/body limits, and the `AI-assisted-by` trailer. Follow it -exactly — do not improvise the format and do not restate its contents here. - -## Pre-commit Workflow - -1. **Stage the files** specified by the calling agent. Do not ask for - confirmation — the calling agent knows exactly which files to commit. -2. Run `git diff --staged` to review the content. If you see secrets (API - keys, tokens, passwords, private keys, `.env` values), debug prints, or - anything that does not match the stated intent, STOP and tell the user - before committing. -3. Following the format in the doc, draft the message and run - `git commit -m "" -m ""` (or `git commit -F -` if the body has - unusual characters). The `AI-assisted-by` trailer value is provided by the - calling agent — use it verbatim. - -## Constraints - -- Do not push. Pushing is a separate workflow handled by the user. -- Do not run `git reset`, `git checkout`, `git restore`, `git clean`, or `rm` — these are destructive operations. -- Do not pass `--author`. Author identity comes from the local git config. -- Do not amend a commit you did not create in this session, unless the user explicitly asks. -- Do not bypass pre-commit hooks (`--no-verify`) unless the user explicitly asks. -- Do not add untracked files that were not created in this session. -- Do not ask questions. The calling agent provides all necessary information. If something is unclear, proceed with what you know and note any assumptions in your response. diff --git a/.opencode/commands/implement-plan.md b/.opencode/commands/implement-plan.md index f6cb42f6b8..20eedb3fe5 100644 --- a/.opencode/commands/implement-plan.md +++ b/.opencode/commands/implement-plan.md @@ -1,5 +1,5 @@ --- -description: Execute a ready plan end-to-end — create a GitHub issue, branch issue-NNNN, implement the plan, then commit via the commiter subagent +description: Execute a ready plan end-to-end — create a GitHub issue, branch issue-NNNN, implement the plan, then commit via the create-commit skill agent: build --- @@ -32,12 +32,11 @@ Implement the prepared plan from the session context. Work methodically, keeping changes focused on what the issue requires. Do not commit — the commit happens in step 4. -## 4. Commit with the commiter subagent +## 4. Commit with the create-commit skill -After the implementation is complete, delegate the commit to the **`commiter`** -subagent. Give it a brief summary of what was implemented and why, the issue -reference (`issue-NNNN`), and the model name you are running as so it sets the -`AI-assisted-by` trailer correctly. The subagent owns the commit format and -conventions. +After the implementation is complete, load the **`create-commit`** skill and +follow its workflow to commit the changes. Provide a brief summary of what was +implemented and why, the issue reference (`issue-NNNN`), and the model name you +are running as so the `AI-assisted-by` trailer is set correctly. Do not push. Pushing is handled separately by the user. diff --git a/.opencode/commands/review.md b/.opencode/commands/review.md index 7736620e89..3e6f59cee5 100644 --- a/.opencode/commands/review.md +++ b/.opencode/commands/review.md @@ -1,21 +1,79 @@ ---- -description: Review a commit (defaults to the last commit) with the code-review-and-quality skill across all five axes -agent: plan -subtask: true ---- +Act as a senior software engineer and perform a thorough code review. -You are performing a code review of a git commit. You MUST conduct it using the **`code-review-and-quality`** skill (the five-axis review: correctness, readability, architecture, security, performance). +## Instructions -The user may specify a commit or revision range as an argument ($ARGUMENTS). If no argument is given, default to reviewing the **last commit** (`HEAD`, i.e. the changes introduced by `HEAD` vs its parent). +1. Load the **`code-review-and-quality`** skill — it defines the five axes, core principles (DRY, KISS, YAGNI), severity taxonomy, and output format. +2. Determine the diff or code to review from the provided context. +3. **Skip generated files, lockfile-only changes, and unrelated modifications** unless they introduce security risks. +4. Read the diff and the surrounding context for each changed file. +5. Review across all five axes: correctness, readability, architecture, security, performance. +6. Produce the review using this structure: + - **Summary**: One-paragraph overview of the change and its impact + - **Critical/High Findings**: Blockers that must be fixed (with file:line, severity, description, and proposed fix) + - **Other Findings**: Medium/Low issues and suggestions + - **Testing Recommendations**: Missing test coverage or test quality issues + - **Positive Observations**: What was done well (brief, specific) + - **Verdict**: Approve / Request Changes / Needs Discussion +7. For each finding: + - State the severity (Critical / High / Medium / Low / Suggestion) + - Identify the file and line + - Describe failure circumstances + - **For Critical/High**: Provide a concrete fix with a code snippet showing the corrected code + - **For Medium/Low**: Describe the fix clearly; code snippet optional + - If multiple approaches exist, briefly note trade-offs +8. **Perform a second review pass if the change is complex:** + - **Complex indicators**: Critical/High findings, multiple files (>5), architectural changes, security-sensitive code, >300 lines changed + - **Skip for simple changes**: Typo fixes, formatting, small bug fixes (<50 lines), single-file changes with no findings + - Second pass checks: + - Validate severity assignments: Are Critical/High findings truly blockers? + - Catch missed issues: Edge cases, error paths, test gaps overlooked in first pass + - Remove false positives: Discard findings that aren't real issues + - Verify fixes: Are the proposed solutions actually correct and complete? -Workflow: +## Strong Rules -1. Determine the target to review: - - If the user provided a revision/range in $ARGUMENTS, use it. - - Otherwise, default to the last commit: review `HEAD` (the diff of `HEAD` against `HEAD~1`). -2. Inspect the change with `git show ` / `git diff ~1 ` and `git log -1 --stat ` to understand the intent and the files touched. -3. Invoke the **`code-review-and-quality`** skill and review the commit across all five axes. Categorize every finding as Critical / Required / Optional / Nit / FYI, and lead with correctness and security. -4. For each finding, state the axis it belongs to, the severity, and a concrete suggested fix (propose the structural remedy, not just the problem). -5. Conclude with a clear verdict: **Approve** (ready to merge) or **Request changes** (issues that must be addressed), and summarize the highest-leverage items. +1. Do not invent problems. Every finding must be real and actionable. +2. Do not modify any code and do not create a commit — this command only reviews. +3. Be specific and constructive. "This could be better" is not helpful — explain why and how. +4. Prioritize by impact. One structural issue outweighs ten nits. +5. If tests are missing for new functionality, flag it as High severity. -Do not modify any code and do not create a commit — this command only reviews. +## Context + +$ARGUMENTS + +## Expected Format + +``` +## Review Summary +[1-2 sentences on what the change does and overall assessment] + +## Critical/High Findings +### [Severity] file.ts:123 +**Issue**: [Description of the problem] +**Impact**: [What could go wrong] +**Fix**: +```[language] +// Current code +[problematic code] + +// Fixed code +[corrected code] +``` +[Optional: note trade-offs if multiple approaches exist] + +## Other Findings +### [Severity] file.ts:456 +**Issue**: [Description] +**Fix**: [Clear description; code snippet optional] + +## Testing Recommendations +[List specific test cases that should be added] + +## Positive Observations +[2-3 specific things done well] + +## Verdict +[Approve / Request Changes / Needs Discussion] +[If Request Changes: list the must-fix items] +``` diff --git a/.opencode/skills/code-review-and-quality/SKILL.md b/.opencode/skills/code-review-and-quality/SKILL.md index 21b0b71771..a0f75e7f99 100644 --- a/.opencode/skills/code-review-and-quality/SKILL.md +++ b/.opencode/skills/code-review-and-quality/SKILL.md @@ -19,9 +19,18 @@ Multi-dimensional code review with quality gates. Every change gets reviewed bef - When refactoring existing code - After any bug fix (review both the fix and the regression test) +## Core Principles + +These principles underpin every axis. When in doubt, default to them. + +- **DRY (Don't Repeat Yourself):** Every piece of knowledge has one authoritative representation. If the same logic appears in two places, extract it into a shared helper, model, or type. Reviewers: flag duplicated logic as a required change — it's not "just similar," it's drift that will diverge. +- **KISS (Keep It Simple, Stupid):** The simplest solution that works is the best solution. Complexity must earn its place. Reviewers: if you need more than one sentence to explain what a piece of code does, it's too complex — push for simplification before merge. +- **YAGNI (You Aren't Gonna Need It):** Don't add abstractions, hooks, or generalizations for hypothetical future use cases. Generalize on the third occurrence, not the first. Reviewers: delete speculative generality. +- **Don't invent problems:** Do not manufacture issues to produce more feedback. Every finding must be a real risk, a real readability barrier, or a real architectural concern — not a hypothetical or a stylistic preference disguised as a problem. + ## The Five-Axis Review -Every review evaluates code across these dimensions: +Every review evaluates code across these dimensions. ### 1. Correctness @@ -39,14 +48,13 @@ Can another engineer (or agent) understand this code without the author explaini - Are names descriptive and consistent with project conventions? (No `temp`, `data`, `result` without context) - Is the control flow straightforward (avoid nested ternaries, deep callbacks)? -- Is the code organized logically (related code grouped, clear module boundaries)? - Are there any "clever" tricks that should be simplified? -- **Could this be done in fewer lines?** (1000 lines where 100 suffice is a failure) -- **Are abstractions earning their complexity?** (Don't generalize until the third use case) -- Would comments help clarify non-obvious intent? (But don't comment obvious code.) -- Are there dead code artifacts: no-op variables (`_unused`), backwards-compat shims, or `// removed` comments? -- **Is a new conditional bolted onto an unrelated flow?** That's a design smell, not a nit — push the logic into its own helper, state, or policy instead of tangling an existing path. -- **Do repeated conditionals on the same shape appear?** They signal a missing model or dispatcher. A "temporary" branch is usually permanent debt. +- **KISS check:** Is this the simplest approach that solves the problem? A 20-line straightforward function beats a 5-line clever one that requires a comment to explain. +- Could this be done in fewer lines? (1000 lines where 100 suffice is a failure) +- Are abstractions earning their complexity? (Don't generalize until the third use case) +- Is a new conditional bolted onto an unrelated flow? Push the logic into its own helper, state, or policy. +- Do repeated conditionals on the same shape appear? They signal a missing model or dispatcher. +- Are there dead code artifacts: no-op variables, backwards-compat shims, or `// removed` comments? ### 3. Architecture @@ -54,16 +62,17 @@ Does the change fit the system's design? - Does it follow existing patterns or introduce a new one? If new, is it justified? - Does it maintain clean module boundaries? -- Is there code duplication that should be shared? +- **DRY check:** Is there existing code that does the same thing? Reuse the canonical helper instead of writing a near-duplicate. If two branches do nearly the same thing, collapse them. - Are dependencies flowing in the right direction (no circular dependencies)? - Is the abstraction level appropriate (not over-engineered, not too coupled)? -- **Does this refactor reduce complexity or just relocate it?** Count the concepts a reader must hold to follow the change. If a "cleaner" version leaves that count unchanged, it isn't cleaner — prefer the restructuring that makes whole branches, modes, or layers disappear over one that re-centralizes the same logic. Prefer deleting an abstraction to polishing it. -- **Is feature-specific logic leaking into a shared or general-purpose module?** Keep logic in its owning layer, reuse the existing canonical helper instead of a near-duplicate, and don't normalize architectural drift. -- **Are type boundaries explicit?** Question gratuitous `any`/`unknown`/optional/casts and silent fallbacks that paper over an unclear invariant — making the boundary explicit often makes the surrounding control flow simpler. +- Does this refactor reduce complexity or just relocate it? Count the concepts a reader must hold. Prefer the restructuring that makes whole branches disappear over one that re-centralizes the same logic. Prefer deleting an abstraction to polishing it. +- Is feature-specific logic leaking into a shared or general-purpose module? +- Are type boundaries explicit? Question gratuitous `any`/`unknown`/optional/casts and silent fallbacks. +- **Structural remedies:** When you flag a problem, propose the move — not just the problem. Replace conditionals with dispatchers, collapse duplicate branches, separate orchestration from business logic, extract helpers, split large files. Prefer the remedy that removes moving pieces over one that spreads the same complexity around. ### 4. Security -For detailed security guidance, see `security-and-hardening`. Does the change introduce vulnerabilities? +For detailed security guidance, see `security-and-hardening`. - Is user input validated and sanitized? - Are secrets kept out of code, logs, and version control? @@ -72,12 +81,9 @@ For detailed security guidance, see `security-and-hardening`. Does the change in - Are outputs encoded to prevent XSS? - Are dependencies from trusted sources with no known vulnerabilities? - Is data from external sources (APIs, logs, user content, config files) treated as untrusted? -- Are external data flows validated at system boundaries before use in logic or rendering? ### 5. Performance -Does the change introduce performance problems? - - Any N+1 query patterns? - Any unbounded loops or unconstrained data fetching? - Any synchronous operations that should be async? @@ -85,24 +91,66 @@ Does the change introduce performance problems? - Any missing pagination on list endpoints? - Any large objects created in hot paths? -## Structural Remedies +## Review Process -When you flag a structural problem, propose the move — not just the problem. A review that only says "this is complex" leaves the author guessing. Reach for a named restructuring: +1. **Understand the intent** — What is this change trying to accomplish? What spec or task does it implement? +2. **Review tests first** — Tests reveal intent and coverage. Do they test behavior, not implementation details? Are edge cases covered? +3. **Review the implementation** — Walk through each file with the five axes in mind. +4. **Categorize findings** — Label every comment with its severity: -- **Replace a chain of conditionals** with a typed model or an explicit dispatcher. -- **Collapse duplicate branches** into a single clearer flow. -- **Separate orchestration from business logic** so each reads on its own. -- **Move feature-specific logic** out of a shared module into the package that owns the concept. -- **Reuse the canonical helper** instead of a bespoke near-duplicate. -- **Make a type boundary explicit** so downstream branching disappears. -- **Delete a pass-through wrapper** that adds indirection without clarifying the API. -- **Extract a helper, or split a large file** into focused modules. +| Prefix | Meaning | Author Action | +|--------|---------|---------------| +| **Critical:** | Blocks merge | Security vulnerability, data loss, broken functionality | +| **High:** | Required change | Must address before merge | +| **Medium:** | Should fix | Strongly recommended, not a blocker | +| **Low:** | Minor, optional | Author may ignore — formatting, style preferences | +| **Suggestion:** | Worth considering | Not required, but improves the code | -Prefer the remedy that removes moving pieces over one that spreads the same complexity around. +For each finding, describe the circumstances under which it could fail: specific inputs, load conditions, timing, or user actions that trigger the problem. "This crashes when input is null" is actionable; "this might crash" is not. + +Lead with what matters: correctness and security first, then structural issues, then everything else. A few high-conviction comments beat a long list. + +5. **Verify the verification** — What tests were run? Did the build pass? Was the change tested manually? Screenshots for UI changes? + +## Review Output + +Structure every review using this format: + +### Summary + +Briefly explain what the code does and give an overall assessment. + +### Critical and High-Priority Issues + +List problems that could cause security incidents, data loss, crashes, incorrect behavior, or major performance degradation. For each: state the severity, identify the file/function/code section, explain why it's a problem, describe failure circumstances, and provide a concrete improvement with corrected code when useful. + +### Other Findings + +List medium- and low-priority issues, including maintainability and design concerns. + +### Suggested Refactoring + +Provide focused code changes or revised snippets. Preserve existing behavior unless a behavior change is explicitly justified. + +### Testing Recommendations + +Identify missing tests and describe specific test cases, including edge cases and failure scenarios. + +### Positive Observations + +Mention implementation choices that are clear, safe, efficient, or well designed. This is not fluff — it reinforces good patterns and tells the author what to keep doing. + +### Final Verdict + +Choose one: + +- **Approve** — Ready to merge +- **Approve with minor changes** — Good to merge after addressing low/medium issues +- **Request changes** — Critical or high issues must be resolved before merge ## Change Sizing -Small, focused changes are easier to review, faster to merge, and safer to deploy. Target these sizes: +Small, focused changes are easier to review, faster to merge, and safer to deploy. ``` ~100 lines changed → Good. Reviewable in one sitting. @@ -110,11 +158,9 @@ Small, focused changes are easier to review, faster to merge, and safer to deplo ~1000 lines changed → Too large. Split it. ``` -**Watch file size, not just diff size.** A small diff can still push a file past a healthy boundary — around 1000 *total* lines in a single file (distinct from the ~1000 *changed*-lines threshold above) is a common inspection signal, not a hard cap. When a change materially grows an already-large file, ask whether to extract helpers, subcomponents, or modules *first*, before piling more on. Decompose, then add. +**Watch file size, not just diff size.** Around 1000 *total* lines in a single file is a common inspection signal. When a change materially grows an already-large file, decompose first. -**What counts as "one change":** A single self-contained modification that addresses one thing, includes related tests, and keeps the system functional after submission. One part of a feature — not the whole feature. - -**Splitting strategies when a change is too large:** +**Splitting strategies:** | Strategy | How | When | |----------|-----|------| @@ -123,164 +169,17 @@ Small, focused changes are easier to review, faster to merge, and safer to deplo | **Horizontal** | Create shared code/stubs first, then consumers | Layered architecture | | **Vertical** | Break into smaller full-stack slices of the feature | Feature work | -**When large changes are acceptable:** Complete file deletions and automated refactoring where the reviewer only needs to verify intent, not every line. - -**Separate refactoring from feature work.** A change that refactors existing code and adds new behavior is two changes — submit them separately. Small cleanups (variable renaming) can be included at reviewer discretion. +**Separate refactoring from feature work.** A change that refactors and adds new behavior is two changes — submit them separately. ## Change Descriptions -Every change needs a description that stands alone in version control history. +- **First line:** Short, imperative, standalone. "Delete the FizzBuzz RPC" not "Deleting the FizzBuzz RPC." +- **Body:** What is changing and why. Include context and reasoning not visible in the code itself. +- **Anti-patterns:** "Fix bug," "Fix build," "Add patch," "Phase 1." -**First line:** Short, imperative, standalone. "Delete the FizzBuzz RPC" not "Deleting the FizzBuzz RPC." Must be informative enough that someone searching history can understand the change without reading the diff. +## Dependencies -**Body:** What is changing and why. Include context, decisions, and reasoning not visible in the code itself. Link to bug numbers, benchmark results, or design docs where relevant. Acknowledge approach shortcomings when they exist. - -**Anti-patterns:** "Fix bug," "Fix build," "Add patch," "Moving code from A to B," "Phase 1," "Add convenience functions." - -## Review Process - -### Step 1: Understand the Context - -Before looking at code, understand the intent: - -``` -- What is this change trying to accomplish? -- What spec or task does it implement? -- What is the expected behavior change? -``` - -### Step 2: Review the Tests First - -Tests reveal intent and coverage: - -``` -- Do tests exist for the change? -- Do they test behavior (not implementation details)? -- Are edge cases covered? -- Do tests have descriptive names? -- Would the tests catch a regression if the code changed? -``` - -### Step 3: Review the Implementation - -Walk through the code with the five axes in mind: - -``` -For each file changed: -1. Correctness: Does this code do what the test says it should? -2. Readability: Can I understand this without help? -3. Architecture: Does this fit the system? -4. Security: Any vulnerabilities? -5. Performance: Any bottlenecks? -``` - -### Step 4: Categorize Findings - -Label every comment with its severity so the author knows what's required vs optional: - -| Prefix | Meaning | Author Action | -|--------|---------|---------------| -| *(no prefix)* | Required change | Must address before merge | -| **Critical:** | Blocks merge | Security vulnerability, data loss, broken functionality | -| **Nit:** | Minor, optional | Author may ignore — formatting, style preferences | -| **Optional:** / **Consider:** | Suggestion | Worth considering but not required | -| **FYI** | Informational only | No action needed — context for future reference | - -This prevents authors from treating all feedback as mandatory and wasting time on optional suggestions. - -**Lead with what matters.** Order findings by leverage: correctness and security first, then structural regressions and missed simplifications, then everything else. Don't bury a real issue under cosmetic nits — a few high-conviction comments beat a long list. If you have one structural problem and ten nits, the structural problem *is* the review. - -### Step 5: Verify the Verification - -Check the author's verification story: - -``` -- What tests were run? -- Did the build pass? -- Was the change tested manually? -- Are there screenshots for UI changes? -- Is there a before/after comparison? -``` - -## Multi-Model Review Pattern - -Use different models for different review perspectives: - -``` -Model A writes the code - │ - ▼ -Model B reviews for correctness and architecture - │ - ▼ -Model A addresses the feedback - │ - ▼ -Human makes the final call -``` - -This catches issues that a single model might miss — different models have different blind spots. - -**Example prompt for a review agent:** -``` -Review this code change for correctness, security, and adherence to -our project conventions. The spec says [X]. The change should [Y]. -Flag any issues as Critical, Required, Optional, or Nit. -``` - -## Dead Code Hygiene - -After any refactoring or implementation change, check for orphaned code: - -1. Identify code that is now unreachable or unused -2. List it explicitly -3. **Ask before deleting:** "Should I remove these now-unused elements: [list]?" - -Don't leave dead code lying around — it confuses future readers and agents. But don't silently delete things you're not sure about. When in doubt, ask. - -``` -DEAD CODE IDENTIFIED: -- formatLegacyDate() in src/utils/date.ts — replaced by formatDate() -- OldTaskCard component in src/components/ — replaced by TaskCard -- LEGACY_API_URL constant in src/config.ts — no remaining references -→ Safe to remove these? -``` - -## Review Speed - -Slow reviews block entire teams. The cost of context-switching to review is less than the waiting cost imposed on others. - -- **Respond within one business day** — this is the maximum, not the target -- **Ideal cadence:** Respond shortly after a review request arrives, unless deep in focused coding. A typical change should complete multiple review rounds in a single day -- **Prioritize fast individual responses** over quick final approval. Quick feedback reduces frustration even if multiple rounds are needed -- **Large changes:** Ask the author to split them rather than reviewing one massive changeset - -## Handling Disagreements - -When resolving review disputes, apply this hierarchy: - -1. **Technical facts and data** override opinions and preferences -2. **Style guides** are the absolute authority on style matters -3. **Software design** must be evaluated on engineering principles, not personal preference -4. **Codebase consistency** is acceptable if it doesn't degrade overall health - -**Don't accept "I'll clean it up later."** Experience shows deferred cleanup rarely happens. Require cleanup before submission unless it's a genuine emergency. If surrounding issues can't be addressed in this change, require filing a bug with self-assignment. - -## Honesty in Review - -When reviewing code — whether written by you, another agent, or a human: - -- **Don't rubber-stamp.** "LGTM" without evidence of review helps no one. -- **Don't soften real issues.** "This might be a minor concern" when it's a bug that will hit production is dishonest. -- **Quantify problems when possible.** "This N+1 query will add ~50ms per item in the list" is better than "this could be slow." -- **Push back on approaches with clear problems.** Sycophancy is a failure mode in reviews. If the implementation has issues, say so directly and propose alternatives. -- **Accept override gracefully.** If the author has full context and disagrees, defer to their judgment. Comment on code, not people — reframe personal critiques to focus on the code itself. - -## Dependency Discipline - -Part of code review is dependency review: - -**Before adding any dependency:** +Before adding any dependency: 1. Does the existing stack solve this? (Often it does.) 2. How large is the dependency? (Check bundle impact.) @@ -290,67 +189,14 @@ Part of code review is dependency review: **Rule:** Prefer standard library and existing utilities over new dependencies. Every dependency is a liability. -**Upgrading an existing dependency** is a code change like any other, and the riskiest upgrades are the ones merged in bulk with a message like "bump deps." Review them with the same discipline: +**Upgrading dependencies:** -1. **Read the changelog, not just the version number.** Semver is a promise the maintainer may not have kept — a "patch" can carry a behavioral change. For a major bump, read the migration notes and find what breaks. -2. **One dependency per change.** Upgrade and merge them individually (or in small related groups). When a bulk bump breaks the build, you've lost which package did it; a single-package change makes the cause obvious and the revert clean. -3. **Let the tests decide.** The upgrade is verified by a green suite before *and* after, not by "it installed." If coverage around the dependency's behavior is thin, that gap is the real finding — add a test first. -4. **Mind the transitive graph.** Most installed packages are ones nobody chose directly. Review the lockfile diff, not just `package.json`; a single direct bump can pull in dozens of indirect changes. -5. **Keep the lockfile honest.** Commit it, review its diff, and never hand-edit it. The lockfile is the thing that actually pins what ships. +- Read the changelog, not just the version number. Semver is a promise the maintainer may not have kept. +- One dependency per change. When a bulk bump breaks the build, you've lost which package did it. +- Let the tests decide — a green suite before *and* after, not just "it installed." +- Review the lockfile diff, not just `package.json`. Commit it and never hand-edit it. -For triaging `npm audit` findings and supply-chain risk (typosquatting, compromised maintainers), follow the `security-and-hardening` skill — this section covers the upgrade *workflow*, that one covers the security verdict. - -## The Review Checklist - -```markdown -## Review: [PR/Change title] - -### Context -- [ ] I understand what this change does and why - -### Correctness -- [ ] Change matches spec/task requirements -- [ ] Edge cases handled -- [ ] Error paths handled -- [ ] Tests cover the change adequately - -### Readability -- [ ] Names are clear and consistent -- [ ] Logic is straightforward -- [ ] No unnecessary complexity - -### Architecture -- [ ] Follows existing patterns -- [ ] No unnecessary coupling or dependencies -- [ ] Appropriate abstraction level -- [ ] Refactors reduce complexity rather than relocate it -- [ ] No feature logic in shared modules; file stays within a healthy size - -### Security -- [ ] No secrets in code -- [ ] Input validated at boundaries -- [ ] No injection vulnerabilities -- [ ] Auth checks in place -- [ ] External data sources treated as untrusted - -### Performance -- [ ] No N+1 patterns -- [ ] No unbounded operations -- [ ] Pagination on list endpoints - -### Verification -- [ ] Tests pass -- [ ] Build succeeds -- [ ] Manual verification done (if applicable) - -### Verdict -- [ ] **Approve** — Ready to merge -- [ ] **Request changes** — Issues must be addressed -``` - -## See Also - -- For detailed security review guidance, see `security-and-hardening` +For supply-chain risk triage, follow the `security-and-hardening` skill. ## Common Rationalizations @@ -358,13 +204,16 @@ For triaging `npm audit` findings and supply-chain risk (typosquatting, compromi |---|---| | "It works, that's good enough" | Working code that's unreadable, insecure, or architecturally wrong creates debt that compounds. | | "I wrote it, so I know it's correct" | Authors are blind to their own assumptions. Every change benefits from another set of eyes. | -| "We'll clean it up later" | Later never comes. The review is the quality gate — use it. Require cleanup before merge, not after. | +| "We'll clean it up later" | Later never comes. The review is the quality gate — use it. | | "AI-generated code is probably fine" | AI code needs more scrutiny, not less. It's confident and plausible, even when wrong. | -| "The tests pass, so it's good" | Tests are necessary but not sufficient. They don't catch architecture problems, security issues, or readability concerns. | -| "The refactor makes it cleaner" | Relocating complexity isn't reducing it. If the reader still holds the same number of concepts, the structure didn't improve — look for the version where branches disappear. | -| "It's only a small addition to this file" | Small diffs still push files past a healthy size and bolt branches onto unrelated flows. Judge the resulting structure, not the diff size. | -| "It's just a version bump" | A bump is a behavior change you didn't write. Read the changelog; semver doesn't guarantee no breakage. | -| "I'll upgrade everything in one PR to save time" | A bulk bump that breaks the build hides which package did it. One dependency per change keeps the cause and the revert clean. | +| "The tests pass, so it's good" | Tests are necessary but not sufficient. They don't catch architecture, security, or readability problems. | +| "The refactor makes it cleaner" | Relocating complexity isn't reducing it. If the reader still holds the same number of concepts, the structure didn't improve. | +| "It's only a small addition to this file" | Small diffs still push files past healthy size and bolt branches onto unrelated flows. | +| "It's just a version bump" | A bump is a behavior change you didn't write. Read the changelog. | +| "I'll upgrade everything in one PR" | A bulk bump hides which package broke the build. One per change. | +| "It's duplicated but it's only two places" | Two becomes three becomes five. Extract now, before the copies diverge. | +| "The abstraction is future-proof" | YAGNI. Delete speculative generality — generalize on the third occurrence, not the first. | +| "It's clever but efficient" | Cleverness is a readability tax. If it needs a comment to understand, simplify it. | ## Red Flags @@ -374,14 +223,11 @@ For triaging `npm audit` findings and supply-chain risk (typosquatting, compromi - Security-sensitive changes without security-focused review - Large PRs that are "too big to review properly" (split them) - No regression tests with bug fix PRs -- Review comments without severity labels — makes it unclear what's required vs optional - Accepting "I'll fix it later" — it never happens - A refactor that moves code around without reducing the number of concepts a reader must hold -- A change that grows an already-large file instead of decomposing it - New conditionals scattered into unrelated code paths (a missing abstraction) -- A bespoke helper that duplicates an existing canonical one, or feature logic placed in a shared module -- A bulk "bump dependencies" PR with no changelog review and no per-package isolation -- A lockfile change that's hand-edited, uncommitted, or merged without reviewing its diff +- A bespoke helper that duplicates an existing canonical one +- A bulk "bump dependencies" PR with no changelog review ## Verification @@ -392,6 +238,18 @@ After review is complete: - [ ] Tests pass - [ ] Build succeeds - [ ] The verification story is documented (what changed, how it was verified) -- [ ] Dependency upgrades were reviewed against their changelog, isolated per package, and verified by a green suite with the lockfile diff reviewed +- [ ] Dependency upgrades reviewed against changelog, isolated per package, verified by green suite -**Presumptive blockers:** surface and propose the simpler design for each of these; escalate to Required only when the change actively makes structure worse: a refactor that relocates complexity instead of reducing it; a change that pushes a file past the size boundary with no decomposition; feature logic added to a shared module; a near-duplicate of an existing canonical helper; a silent fallback that hides an unclear invariant. +## Multi-Model Review Pattern + +Use different models for different review perspectives: + +``` +Model A writes the code → Model B reviews → Model A addresses feedback → Human makes the final call +``` + +Different models have different blind spots. + +## See Also + +- For detailed security review guidance, see `security-and-hardening` diff --git a/.opencode/skills/create-commit/SKILL.md b/.opencode/skills/create-commit/SKILL.md new file mode 100644 index 0000000000..790ba1b585 --- /dev/null +++ b/.opencode/skills/create-commit/SKILL.md @@ -0,0 +1,47 @@ +--- +name: create-commit +description: Stage, review, and commit files following Penpot commit conventions. +--- + +# Skill: create-commit + +Produce a git commit that follows Penpot's commit message conventions. This +skill owns the commit format, staging review, and safety checks — it does not +implement features or push. + +## When to Use + +- After code changes are complete and files need to be committed +- When delegated by a workflow step (e.g. implement-plan) to handle the commit + +## Required Reading + +Before drafting any commit, read `mem:workflow/creating-commits` end-to-end. It +is the authoritative source for the commit message format, the emoji menu, +subject/body limits, and the `AI-assisted-by` trailer. Follow it exactly. + +## Workflow + +1. **Stage the files** specified by the calling context. Do not ask for + confirmation. +2. Run `git diff --staged` to review the content. If you see secrets (API keys, + tokens, passwords, private keys, `.env` values), debug prints, or anything + that does not match the stated intent, **STOP** and tell the user before + committing. +3. Draft the message following the format in the memory doc, wrapping the body + at 72 characters per line, and run: + ```bash + git commit -m "" -m "" + ``` + (or `git commit -F -` if the body has unusual characters). +4. The `AI-assisted-by` trailer value is provided by the calling context — use + it verbatim. + +## Constraints + +- Do not push. Pushing is a separate workflow handled by the user. +- Do not run `git reset`, `git checkout`, `git restore`, `git clean`, or `rm`. +- Do not pass `--author`. Author identity comes from the local git config. +- Do not amend a commit you did not create in this session, unless explicitly asked. +- Do not bypass pre-commit hooks (`--no-verify`) unless explicitly asked. +- Do not add untracked files that were not created in this session. diff --git a/.opencode/skills/testing/SKILL.md b/.opencode/skills/testing/SKILL.md new file mode 100644 index 0000000000..5ad5d04e6e --- /dev/null +++ b/.opencode/skills/testing/SKILL.md @@ -0,0 +1,57 @@ +--- +name: testing +description: Enforce TDD workflow and testing best practices for Penpot. Use when implementing features, fixing bugs, or modifying behavior. Reads testing memory for full guidance. +--- + +# Testing Skill + +Enforces test-driven development and Penpot testing conventions. + +## When to Use + +- Implementing new logic or behavior +- Fixing any bug (reproduction test required) +- Modifying existing functionality +- Adding edge case handling + +**Skip:** Pure configuration changes, documentation updates, or static content with no behavioral impact. + +## Workflow + +Follow TDD (Red → Green → Refactor) whenever practical: + +1. **RED** — Write a failing test first +2. **GREEN** — Write minimal code to pass +3. **REFACTOR** — Clean up while tests stay green + +For bug fixes, use the Prove-It Pattern: write a test that reproduces the bug, confirm it fails, implement the fix, confirm it passes. + +## Required Reading + +Before writing any test, read: + +1. `.serena/memories/testing.md` — cross-cutting testing principles, TDD workflow, anti-patterns, execution discipline +2. Module-specific testing memory for the affected module: + - `mem:common/testing` — CLJC unit tests + - `mem:frontend/testing` — CLJS unit tests, Playwright E2E + - `mem:backend/core` — JVM clojure.test conventions + +## Key Rules + +- Every behavior change needs a test +- Test state, not interactions +- DAMP over DRY — tests are specifications; duplication is OK if each test is self-contained and readable +- Prefer Real > Fake > Stub > Mock +- Arrange-Act-Assert structure +- One assertion per concept +- Never pipe test output to filters — redirect to file first +- Register new test files in the module's runner/entrypoint + +## Verification + +After completing implementation: + +- [ ] Every new behavior has a test +- [ ] All tests pass for touched modules +- [ ] Bug fixes include a reproduction test +- [ ] Lint/formatter passes diff --git a/.serena/memories/backend/core.md b/.serena/memories/backend/core.md index 6530f74308..708d30fc5d 100644 --- a/.serena/memories/backend/core.md +++ b/.serena/memories/backend/core.md @@ -92,8 +92,8 @@ Fixtures can populate local data for manual testing/perf work. From the backend IMPORTANT: all CLI commands must be executed from the `backend/` subdirectory. -* **Linting:** `clj-kondo --lint ../common/src/ src/`. -* **Formatting:** `cljfmt check src/ test/` to check, `cljfmt fix src/ test/` to fix. Avoid unrelated whitespace diffs. +* **Linting:** `pnpm run lint:clj`. +* **Formatting:** `pnpm run check-fmt:clj` to check, `pnpm run fmt:clj` to fix. After running `fmt:clj`, `check-fmt:clj` is redundant. Avoid unrelated whitespace diffs. **Before linting:** if delimiter errors are suspected (after LLM edits), run `scripts/paren-repair` on the affected files first. Delimiter errors produce diff --git a/.serena/memories/common/component-data-model.md b/.serena/memories/common/component-data-model.md index 4ed1a47f9a..ef3343797c 100644 --- a/.serena/memories/common/component-data-model.md +++ b/.serena/memories/common/component-data-model.md @@ -24,6 +24,12 @@ Variant masters are main instances and component roots. Their descendants may th Masters are not normally touched through `set-shape-attr`, but touched flags can appear on master shapes through cloning/duplication paths. `add-touched-from-ref-chain` in `app.common.logic.variants` unions touched flags from ancestors into the copy being processed, so upstream/master touched state can affect downstream switch behavior. +## Swap slots and positional matching + +- A swap slot (stored via `ctk/set-swap-slot`, a `:touched` group `swap-slot-`) marks a copy sub-head that was SWAPPED to another component; `compare-children` then pairs it to the main child by slot instead of by `shape-ref`. +- Copy sub-heads without a slot are paired to main children by `shape-ref` (seek, not index). `find-near-match` (positional) is only a validator/repair heuristic; validity requires membership of the ref among the near-main parent's children, not index equality (`mem:common/file-change-validation-migration-subtleties`). +- Copy child ORDER converges to the main's via the async sync (`moved` branch of `compare-children`); local code must never reorder copy children directly (guards in `:mov-objects`/`:reorder-children`). + ## Cloning paths `make-component-instance` in `app.common.types.container` produces a clean component copy through `update-new-shape`, dissociating attrs such as `:touched`, `:variant-id`, and `:variant-name` on cloned shapes. diff --git a/.serena/memories/common/core.md b/.serena/memories/common/core.md index 6ae8f084e8..816d131e14 100644 --- a/.serena/memories/common/core.md +++ b/.serena/memories/common/core.md @@ -5,7 +5,7 @@ ## Stable namespace map - `app.common.data` and `app.common.data.macros`: generic data helpers and performance macros that do not depend on Penpot domain entities. -- `app.common.types.*`: shared shape/file/page/component/token data types, schemas, predicates, and entity-local operations. `app.common.types.nitrate-permissions` contains shared fail-closed Nitrate organization/team permission rules. +- `app.common.types.*`: shared shape/file/page/component/token data types, schemas, predicates, and entity-local operations. `app.common.types.organization` contains organization schemas, `apply-organization`, and fail-closed organization/team permission rules (`allowed?`, `can-send-invitations?`). - `app.common.files.*`: file-level operations, shape tree helpers, change application, migrations, validation, and undo/redo-related logic. - `app.common.logic.*`: higher-level workflows/algorithms over files, shapes, components, variants, libraries, tokens, etc. - `app.common.geom.*`: geometry helpers and transformations. diff --git a/.serena/memories/common/file-change-validation-migration-subtleties.md b/.serena/memories/common/file-change-validation-migration-subtleties.md index 7ff830a38d..014a458a30 100644 --- a/.serena/memories/common/file-change-validation-migration-subtleties.md +++ b/.serena/memories/common/file-change-validation-migration-subtleties.md @@ -7,6 +7,8 @@ - `set-shape-attr` treats `:position-data` as derived and never touched. Geometry/content-path changes use approximate equality; geometry differences under about 1px can be ignored for touched purposes. - Width/height are excluded from the `is-geometry?` branch in `set-shape-attr`; do not assume all geometry-group attrs follow identical ignore-geometry behavior. - `process-touched-change` marks the owning component modified when a touched shape belongs to a main instance; component-data changes can come from shape ops through this second pass. +- Copy structure is guarded at change application: `:mov-objects` (`is-valid-move?`) and `:reorder-children` both refuse to alter children of shapes inside component copies unless the change carries `allow-altering-copies` (sync/swap flows set it). New structural change types must follow the same rule. +- `cls/generate-delete-shapes` propagates deletions from INSIDE a component main to the copy shapes referencing them (transitively, all pages of the file) so no dangling `shape-ref`s remain; skipped when the main root itself is deleted (copies then resolve into the deleted component) and for `allow-altering-copies` flows (swap replaces the shape; sync reconciles). ## Shape tree edits @@ -19,6 +21,7 @@ - Full referential/semantic validation currently runs only when file features contain `"components/v2"`. - Validation starts at root plus orphan shapes, then validates component records. `validate-file!` raises `:validation :referential-integrity` with collected details. - `repair-file` does not mutate data directly; it reduces validation errors into redo changes using `changes-builder`. Callers must apply or persist those changes. +- `:missing-slot` fires only for a REAL swap: a copy sub-head whose `shape-ref` is no longer a child of the near main parent. A pure positional mismatch (ref still a sibling elsewhere) is a reorder — valid, realigned by the async component sync; do not "repair" it by assigning swap slots (a slot freezes the child out of normal sync). `fix-missing-swap-slots` (migration 0019) follows the same membership rule. ## Migrations diff --git a/.serena/memories/common/layout-grid-subtleties.md b/.serena/memories/common/layout-grid-subtleties.md index a3070efefb..2a48b9d149 100644 --- a/.serena/memories/common/layout-grid-subtleties.md +++ b/.serena/memories/common/layout-grid-subtleties.md @@ -8,6 +8,9 @@ ## Grid assignment - Grid `assign-cells` ensures at least one column and row, skips absolute-position children, creates non-tracked rows/cols when children exceed tracked cells, and asserts that assigned cells do not overlap. +- `position-absolute?` counts HIDDEN shapes as absolute: hiding a grid child frees its cell on the next `assign-cells`. +- `reorder-grid-children` rewrites the parent's `:shapes` to the REVERSE of the sorted cell order, but children with no cell (hidden/absolute) keep their original index — do not "fix" this into moving them to an end; that broke copy/main positional slot alignment (referential-integrity crash). +- The `:reorder-children` change it emits is refused on parents inside component copies unless `allow-altering-copies` (same rule as `:mov-objects`); `pcb/reorder-grid-children` also skips copy grids producer-side. Copy child order is owned by the component sync engine. - Grid deassignment removes cells for shapes that are no longer direct children or have become absolute-positioned. - Auto-positioning is not just sorting: some auto cells are converted to manual when empty/manual/span state would break the auto sequence, then auto single-span items can be compacted. - `fix-overlaps` is marked dev-only and removes one overlapping cell, preferring empty cells first. Avoid depending on it as normal production repair. \ No newline at end of file diff --git a/.serena/memories/critical-info.md b/.serena/memories/critical-info.md index fcc2394424..117e8ff464 100644 --- a/.serena/memories/critical-info.md +++ b/.serena/memories/critical-info.md @@ -39,6 +39,7 @@ This is a monorepo. Principles that apply to one module do *not* generally apply - `plugins/`: TypeScript plugin runtime/examples and Plugin API types; core conventions: `mem:plugins/core`. - `library/`: design library workflows; core conventions: `mem:library/core`. - `docs/`: documentation site; core workflow and conventions: `mem:docs/core`. +- `media-processor/`: TypeScript/Node.js HTTP service for image (sharp) and font (FontForge) processing; core conventions: `mem:media-processor/core`. The memory is structured in a way that you can get the critical information about the module. You can read it from `mem:/core` @@ -52,7 +53,7 @@ module. You can read it from `mem:/core` - `experiments/` contains standalone experimental HTML/JS/scripts; treat it as non-core unless the user explicitly asks about it. - `sample_media/` contains sample image/icon media and config used as fixtures/demo material; do not infer app behavior from it. -# Dev tools +# Dev Scripts (scripts/) - `scripts/nrepl-eval.mjs` — Evaluate Clojure/ClojureScript code via nREPL. Supports `--backend` (port 6064) and `--frontend` (port 3447) aliases. diff --git a/.serena/memories/devenv/core.md b/.serena/memories/devenv/core.md index 82e4e704f3..0651f872fe 100644 --- a/.serena/memories/devenv/core.md +++ b/.serena/memories/devenv/core.md @@ -25,7 +25,9 @@ Compose-based dev environment under `docker/devenv/`, driven by `manage.sh`. Par ## Worker policy -Backend workers run only on ws0. `_env` gates `enable-backend-worker` on `PENPOT_BACKEND_WORKER`; ws1+ inject it as false. ws0 must be running whenever any ws1+ is running, and is the last instance to stop — `run-devenv --agentic --ws N` (N≥1) auto-starts ws0 first; `stop-devenv` refuses to stop ws0 while any ws1+ is up. Workers are pure fire-and-forget: `wrk/submit!` inserts a row into the shared Postgres `task` table and returns; RPC handlers never wait on completion and workers never publish to msgbus. The reason for "ws0 only" is avoiding multi-instance worker races (cron dedup is best-effort across instances, `wrk/submit!` `dedupe` is racy across submitters); details in `mem:prod-infra/core`. +Backend workers run only on ws0. `_env` gates `enable-backend-worker` on `PENPOT_BACKEND_WORKER`; ws1+ inject it as false. Workers are pure fire-and-forget: `wrk/submit!` inserts a row into the shared Postgres `task` table and returns; RPC handlers never wait on completion and workers never publish to msgbus. The reason for "ws0 only" is avoiding multi-instance worker races (cron dedup is best-effort across instances, `wrk/submit!` `dedupe` is racy across submitters); details in `mem:prod-infra/core`. + +Each workspace is independent and can be started/stopped in any order. Shared infra (postgres, minio, etc.) is shut down only when no instances remain running. ## Port layout @@ -63,8 +65,8 @@ No `--delete` on the working-tree pass: gitignored caches in the workspace survi ## CLI surface -- `run-devenv --agentic [--ws main|0|wsN|N] [--sync] [--serena-context CTX]`: bring one instance up. Agentic only — MCP and Serena windows are always created. Default target main. Errors out if the target is already running. `--sync` is rejected on main; on ws1+ it's optional (forced only when the workspace dir does not exist yet). Auto-starts ws0 first when the target is ws1+ and ws0 is not yet up. -- `stop-devenv [--ws main|0|wsN|N] [--all]`: stop instances. Flags mutually exclusive. `--ws N` (N≥1) stops just that workspace. `--ws 0` or no flag stops ws0 + shared infra, refused while any ws1+ is running. `--all` stops every ws highest-first then ws0, then infra. +- `run-devenv --agentic [--ws main|0|wsN|N] [--sync] [--serena-context CTX]`: bring one instance up. Agentic only — MCP and Serena windows are always created. Default target main. Errors out if the target is already running. `--sync` is rejected on main; on ws1+ it's optional (forced only when the workspace dir does not exist yet). +- `stop-devenv [--ws main|0|wsN|N] [--all]`: stop instances. Flags mutually exclusive. `--ws N` stops just that workspace. `--ws 0` or no flag stops ws0; shared infra shuts down only if no other instances remain. `--all` stops every ws highest-first then ws0, then infra. - `run-devenv`: legacy alias, ws0 non-agentic attached. - `attach-devenv [--ws main|0|wsN|N]`: pure attach. Fails fast if instance/session missing. - `run-devenv-shell [--instance 0|wsN|N] [cmd...]`: bash in target instance. (`--instance` flag not yet renamed to `--ws`.) diff --git a/.serena/memories/frontend/composable-component-tests.md b/.serena/memories/frontend/composable-component-tests.md index 28c0605569..865a381133 100644 --- a/.serena/memories/frontend/composable-component-tests.md +++ b/.serena/memories/frontend/composable-component-tests.md @@ -1,316 +1,151 @@ # Composable component tests -A framework for systematically testing Penpot's component subsystem (synchronisation/propagation, -swaps, variant switches, nesting), plus the suite of cases built on it. Lives entirely in the -**frontend** test tree as `.cljs`; it is test-only code with a single consumer (the frontend test -suite, which runs the real app). There is nothing "common" about it — it is not under `app/common`. +A framework concept for systematically testing Penpot's component subsystem +(synchronisation/propagation, swaps, variant switches, nesting, overrides), implemented in TWO test +suites that share the principles below: -## Core idea -A test is a **composition of operations** over a **situation**, plus assertions. You describe a -test as data (a setup + a sequence of operations) rather than writing bespoke imperative code, and -coverage grows by COMPOSITION: a new variation is one combinator wrapped around existing pieces, -not a copied test. One written case stands for a whole matrix of concrete cases. +1. **ClojureScript suite** — in the frontend test tree (`frontend/test/frontend_tests/ + composable_tests/`), driving a minimally-assembled real app headlessly. The original. +2. **TypeScript suite** — a Penpot plugin (`plugins/apps/composable-test-suite/`), driving the FULL + production app end-to-end through the Plugin API, with a slightly more elaborate set of + abstractions. Runs interactively (panel), remotely (Playwright), and headlessly in CI. Its + README is the authoritative operational reference. -- **Situation** — the in-memory Penpot file value, plus named **roles** (meaningful shapes, e.g. - `:main-instance`/`:copy-instance`), a `:vars` map (named non-shape values), and an ordered - **applied-log** of what ran. -- **Operation** — a step, reified as a DATA record implementing `IOperation` (single method - `apply-to`; `apply` collides with core). Operations are printable, navigable, and enumerable. - Most transform the situation; some do not — hence the genus is "operation", not "transformation" - (`Test` asserts and returns the situation unchanged; `Skip` is a no-op). -- **Assertions** — inline `Test` operations placed in the sequence (assert at intermediate points) - and/or a trailing asserter (a `situation -> any` lambda calling `t/is`). The runner makes NO - judgment; it applies operations and returns the situation. Only *retrieval* helpers live outside - the test (role accessors, `has-property-of`, `applied?`). +## Shared core idea +A test is a **composition of operations** over a starting configuration, plus assertions. You +describe a test as data (a setup + a sequence of operations) rather than writing bespoke imperative +code, and coverage grows by COMPOSITION: a new variation is one combinator wrapped around existing +pieces, not a copied test. Choice points (one-of alternatives, optional steps) EXPAND the +composition into a full sweep of variants — one written case stands for a whole matrix of concrete +tests. -## Principles -- **Operations are data with identity.** Each node gets a unique id at construction (`assign-id`), - records what it did under that id (`record-application`), and is interrogated by identity - (`applied?`, `get-choice`). No flat keyword-tagged log. -- **Drive the real production pipeline.** Every operation routes through the actual production - change functions (`generate-update-shapes`, `generate-component-swap`, `generate-reset-component`, - `generate-sync-file-changes`, …) — never raw field writes, or propagation would have nothing to - react to. The test exercises genuine Penpot logic, not a reimplementation. -- **The frontend runs the real app.** Synchronous file-ops apply directly to the store; event-ops - dispatch the REAL workspace events and await settlement, so the production watcher's AUTOMATIC - propagation is what's under test. Observed semantics are genuine. -- **Roles resolve to ids at setup time.** The global label→id map (`thi`) is shared and - time-varying, so a role is captured as an id when the situation is built; resolving late (across - enumerated variants) would be unsound. Absence throws a diagnostic (never silent nil). -- **Targets resolve at apply-time and may be rebound.** A target is a `(situation -> id)` FUNCTION, - else a currently-bound ROLE, else a LABEL (`target-shape-id`). So one operation targeting a role - follows that role as state-building ops re-point it — which is what lets a single operation be - swept across depth. -- **Enumeration is authored, not exhaustive.** You compose only VALID cases (every `one-of` branch - must be valid against the setup), so outcomes are just pass / fail / error — no not-applicable - cells. Adding a variation across a matrix is a one-expression edit. +## Shared principles +- **Every producing object is the accessor interface to what it produces downstream.** An + operation — and related objects such as content-creation strategies — is not merely an action: + the SAME object instance the case holds is the typed interface through which everything it + created or changed is later retrieved, checked, and asserted, parameterized by the situation. A + foundation operation exposes accessors for the participants it built; an edit operation exposes + its dual check (`assertHasChangedProperty` / `has-property-of`); a choice is recovered by asking + the one-of object (`getChoice`/`get-choice`); "did this step run" is asked of the step + (`wasApplied`/`applied?`). NEVER reach into a situation (or the document) for something an + upstream object produced — ask the producer. This is what keeps sweeps sound (object identity + ties the question to the exact node that ran) and what keeps retrieval logic in exactly one + place. Particularly explicit in the TS OOP implementation, where these accessors are methods on + the operation/strategy classes; repeatedly violating it (reading the document directly, + duplicating retrieval) was the most common review correction while building the suites. +- **Operations are data with identity.** Each operation node has a unique id at construction and + records what it did under that id; interrogation is by identity. Bind an operation to a value + ONCE and reuse it in the composition and in every query about it. +- **Drive the real production pipeline.** Operations route through genuine Penpot logic — real + change functions / real workspace events / the real Plugin API, never raw field writes — so the + production watcher's AUTOMATIC propagation is what's under test. +- **Roles, not internals.** A starting configuration names its participants (roles). Role→id + capture happens when the configuration is built; operation TARGETS resolve at apply-time and may + be re-bound, so an operation targeting a role follows it as state-building ops re-point it — + which lets a single operation be swept across depth. +- **Enumeration is authored, not exhaustive.** Compose only VALID cases, so outcomes are just + pass / fail / error — no not-applicable cells. - **Naming discipline.** Penpot domain nouns ("component", "variant") must not name framework - abstractions (they collide with real domain concepts). Framework vocabulary is testing concepts - only; an operation may name the domain *action* it performs (`swap`, `propagate`). + abstractions; an operation may name the domain ACTION it performs. +- **Operator algebra** (same in both suites): sequence (cartesian product of the steps' variants), + one-of (union, choice recorded), optional(X) = one-of([X, skip]), inline assertion ops, trailing + asserters. +- **Case authoring:** a case carries a CamelCase identifier and a plain-terms description in three + parts — situation setup, actions/variations, asserted requirement. -## Composition operators -- `in-sequence` — ordered application, threads the situation; enumerates to the CARTESIAN PRODUCT - of its steps' variants. Operations do not commute, so order is explicit. The workhorse. -- `one-of` — exactly one branch; applying it throws (must be enumerated); enumerates to the UNION - of branches, each wrapped in a `RecordedChoice` so `get-choice` recovers which ran. -- `optional(X)` = `one-of([X, skip])` — sweeps "with and without X" (two variants). `skip` is the - identity operation. The workhorse for adding a state-building step as an axis over a case. -- `test-that [assert-fn]` — an inline `Test`: asserts at this point in the sequence, situation - unchanged. Lets checkpoints sit at intermediate steps. Engine stays clojure.test-free (it just - calls the supplied fn). -- `applied? [situation operation]` — whether that exact node ran (identity-based). Composes with - `optional`/`one-of` for free. REQUIREMENT: bind an operation to a value ONCE and reuse it (in the - composition AND any `Test` querying it), so the id you ask about is the id that ran. +--- -## Structure (frontend/test/frontend_tests/composable_tests/) -Two boundaries: the domain-agnostic **engine** and the **comp** subject library (about components; -naming the domain is correct there). +# ClojureScript suite (frontend test tree) -- `core.cljs` (ns `frontend-tests.composable-tests.core`) — the engine, one file: - - situation: `make-situation`, `file`/`with-file`, `with-aux-files`/`aux-files` (carry extra - files, e.g. a library for case H), the applied-log. - - identity & transcript: `assign-id`, `node-id`, `record-application` (also stores a `::kind` - from the record type), `node-data`, `describe-applied` (readable ordered transcript, attached - to every failure so a failing variant in a sweep is identifiable). - - roles & lookup: `role-shape` (strict, by stored id), `has-role?`, `rebind-role`/`rebind-role-id` - (re-point a role — used by state-building ops), `target-shape-id` (fn | role | label), - `shape-by-id` (read a shape whose id is held in a `:vars` object), `resolve-shape`/`-id`. - - protocols: `IOperation`(`apply-to`); `IEnumerable`(`-enumerate`) + `enumerate`. - - operators: `Sequence`/`in-sequence`; `OneOf`/`one-of`/`RecordedChoice`/`get-choice`; - `Skip`/`skip`; `optional`; `Test`/`test-that`; `applied?`; vars `set-var`/`get-var`. - - runners (clojure.test-free): `run-variant`, `run-all` (enumerate → vector, `thi/reset-idmap!` - per variant). - - per-op-interpreter helpers: `sequence-ops` (flatten a concrete variant — flattens `Sequence`, - keeps `RecordedChoice` as a unit), `recorded-choice?`, `choice-of`, `choice-one-of-id`. -- `comp/setups.cljs` — setup fns returning a situation, + role accessors (`main-instance`/ - `copy-instance`/`main-root`/`copy-root`, `copy-child` 1-based): `simple-component-with-copy`, - `simple-component-with-labeled-copy`, `component-with-many-children` (E, F), - `nested-component-with-copy`, `cross-file-component-with-copy` (H: main in a linked library, copy - in the consuming file; primary `:file` = consuming, aux = library), and `empty-situation` (empty - file, no roles — the `:setup` for the sweep cases, whose first operation is `create-component`). -- `comp/nodes.cljs` — the component OPERATIONS. General edit/structure ops: - `change-property [target property value]` (`:fills`/`:opacity`) with its dual `has-property-of` - (`IPropertyCheck`); `change-attr`/`has-attr?` are aliases. `add-child`/`remove-child`/`move-child` - (with `IStructuralCheck`). `sync-from-library` (H: `generate-sync-file-changes`, libraries = - primary + aux). `undo` (I; frontend `dwu/undo`). Plus the scenario building blocks below. -- `interpreter.cljs` (ns `frontend-tests.composable-tests.interpreter`) — runs a case against the - real frontend (see "Interpreter"). -- `comp/sync_test.cljs` (ns `frontend-tests.composable-tests.comp.sync-test`) — the cases; - registered in `frontend_tests/runner.cljs`. +Test-only `.cljs` code in the frontend test tree (nothing "common" about it). A **situation** = +the in-memory file value + named roles + `:vars` + an ordered applied-log. Operations are records +implementing `IOperation`/`apply-to` (`apply` collides with core). Assertions = inline `Test` ops +and/or a trailing asserter; the runner makes no judgment. Failures carry `describe-applied` (the +transcript), which is what makes a failing variant in a sweep identifiable. -## Scenario object model (behind the sweep cases) -Scenario ops track one or more named component LINEAGES as OBJECTS under `:vars :components` (keyed -by name, e.g. "main"). Grouping a lineage's fields into one object lets several lineages coexist -(a swap targets a DIFFERENT component) and makes each op "read object `name`, update, write back". +Layout: `core.cljs` (the domain-agnostic engine: situation, identity/transcript, roles/targets, +operators, runners), `comp/setups.cljs` (setups + role accessors), `comp/nodes.cljs` (the component +operations and their check duals), `interpreter.cljs` (runs cases against the real frontend), +`comp/sync_test.cljs` (the cases; registered in `frontend_tests/runner.cljs`). Case letters B..N; +the sweeps (K: depth × edit-precedence; L: swaps; M: variant switches; N: rotated-instance +geometry, on the #10109 fix branch until merged) are the flagship pattern — read them before +writing a new sweep. -A lineage object has: -- `:main-component-id` — the component the next instantiate/nest uses (advances to the new OUTER - component per `make-nested-component`). -- `:remote-head`/`:remote-rect` — the FIXED deepest origin (the original component everything is - derived from). For a plain lineage this is never re-pointed; a variant nesting DOES re-point it - (see below). -- `:main-head`/`:main-rect` — the current outer main (advances per nesting). -- `:nesting-count`; `:copies`, `:copy-head`/`:copy-rect` (from `instantiate-copy`). -- `:nesting-data` — vector, one entry per level i: `{:main-head, :nested-head, :nested-rect, - :nested-head-parent}`. - - `:nested-head` is the DEEPEST instance at level i — the descendant of the level's copy head - that corresponds to `:remote-head`, found by descending the `:shape-ref` chain (at level 0 the - inner copy itself; deeper, the corresponding shape nested within the outer wrapper). This is THE - SWAP / SWITCH TARGET; it carries a `:component-id`. - - `:nested-head-parent` is the SWAP-STABLE anchor: a swap/switch replaces the head in place but - keeps its parent, so assertions re-resolve parent → current head → rect. +**Scenario lineage model** (behind the sweeps): scenario ops track named component lineages as +objects under `:vars`, each holding the FIXED deepest origin (`:remote-*`), the ADVANCING outer +main (`:main-*`), and per-nesting-level data whose `:nested-head` (the deepest instance at that +level, found by descending the `:shape-ref` chain — matching chain MEMBERSHIP, not terminus) is +the swap/switch target, anchored by its swap-stable parent. Nesting seeks the FIXED origin, not +the advancing main — that is what makes each level's `:nested-head` land on the deepest instance. +A variant nesting re-points the lineage's remote to the chosen member. Construction lesson: +cross-level propagation requires progressively NESTED levels (one variant + plain wraps); sibling +nestings do not propagate between each other. -Accessors / targets (in nodes): `lineage-component-id`, `lineage-rect`, `lineage-copy-rect`, -`lineage-nesting`, `level-rect`/`level-rect-of` (level i's CURRENT rect via the parent anchor); -target-fns `remote-rect-of`/`main-rect-of`/`copy-rect-of` and `nested-head-of` (return a -`(situation -> id)` for use as an operation target). "Corresponds to" across layers follows the -`:shape-ref` CHAIN, matching on chain MEMBERSHIP not terminus (a copy rect refs its near-main, -which carries a further `:shape-ref`, so the terminus over-walks). Single-file setups, so the chain -resolves in the local page objects. +**Interpreter:** installs the situation's files into the global `st/state` (aux files tagged +`:library-of`), starts the real `watch-component-changes` (+ harness `watch-undo-stack`), maps +event-ops to REAL workspace events (`dwsh/update-shapes`, `dwl/component-swap`, +`dwv/variants-switch`, `dwt/increase-rotation` — which runs the `check-delta` placement +classification — `dwt/update-dimensions`, `dwu/undo`, `dwl/sync-file`, …) and runs sync-ops' +`apply-to` against the live store file; awaits settlement (idle-gap heuristic + per-op grace) and +re-reads `:file` each step so the shared accessors keep working. +STORE-SWAP IMMUNITY: other test namespaces `set!` `st/state`/`st/stream` and never restore, while +the `app.main.refs` lenses stay bound to the ORIGINAL atoms — propagation then dies silently. The +interpreter captures the atoms at namespace-load time and re-`set!`s them per variant. -Scenario operations (each takes a lineage `name`): -- `create-component [name color]` — a component (frame + rect child of `color`); remote == main, - count 0. -- `make-nested-component [name]` — wrap `name`'s component in a NEW OUTER component whose main - contains a COPY of it inside a board (add-frame → instantiate inside → make-component); the OUTER - becomes `:main-component-id`; advance `:main-*`; append a `:nesting-data` entry; bump count. - ITERABLE: `×N` = board-within-board nesting with one rect at the bottom. Each level's - `:nested-head` is the deepest instance there, so swapping/switching it propagates (via the - watcher) outward to copies of it in OUTER levels. -- `instantiate-copy [name]` — instantiate `name`'s current component; track `:copy-head` and the - rect corresponding to its main rect as `:copy-rect`. -- `reset-copy-instance [name]` — reset overrides on `:copy-head` (production - `generate-reset-component`, `:validate? false` — a file-op on the frontend too: the real reset - event reads browser globals and cannot run headless). -- `swap-component [name level target & {:keys [keep-touched?]}]` — swap level `level`'s - `:nested-head` for lineage `target`'s component, via production `generate-component-swap`. - Frontend = the REAL `dwl/component-swap` event, so the watcher AUTOMATICALLY propagates the swap - to copies (incl. deeper levels). A swap replaces the head in place: Penpot keeps the head id, - rewrites it to the new component, stamps a `:swap-slot-` touched group. `keep-touched?` - default false (discards overrides); true is the variant-switch flavour. -- Shared nesting helper `nest-in-new-outer-component [situation name op seek-rect-id seek-head-id - instantiate-inner-fn]` — the contain-outward mechanism behind BOTH nesting ops. Adds the outer - frame, calls `instantiate-inner-fn` to place the inner instance, makes the outer a component, - then computes this level's `:nested-rect`/`:nested-head` as the IMAGES (inside the new inner copy) - of `seek-rect-id`/`seek-head-id` — the FIXED deepest origin — and does the bookkeeping. A flavour - supplies only the two origin ids + the instantiate fn. Seeking the FIXED origin (not the advancing - `:main-*`) is what makes `:nested-head` land on the deepest instance at every level. - `self-or-descendant-corresponding-to` is the chain-descent that also matches the head itself - (needed at level 0, where the inner copy head IS the origin's image). +Running: `cd frontend && pnpm run build:test`, then +`node target/tests/test.js --focus frontend-tests.composable-tests.comp.sync-test` +(var-level focus for one case). -## Variant operations -A variant switch IS a keep-touched swap whose target is resolved by a property VALUE (the -production `variants-switch`/`variant-switch` reduces to `component-swap … keep-touched? true`), so -it routes through the SAME `generate-component-swap` and the watcher auto-propagates it across -nesting levels exactly like a swap. -- `make-variant-container [name members]` (sync-op) — build a variant SET synchronously, mirroring - the test-helpers' `add-variant` idiom: a container frame (`:is-variant-container`), each `members` - entry `[value color]` becoming a member component whose ROOT is a child of the container carrying - the shared `:variant-id`/`:variant-name`, then `update-component` stamps `:variant-id` + - `:variant-properties [{:name "Property 1" :value value}]` on the component. Read the container id - via `(thi/id container-label)` only AFTER adding the container frame (`thi/id` returns nil before - the shape exists). Records the set in `:vars` (`variant-set`/`variant-member`/ - `variant-member-component-id` read it back). -- `make-nested-component-with-variant [name set-name value]` (sync-op) — nest a chosen member via - the shared nesting helper, AND re-point the lineage's `:remote-head`/`:remote-rect` to that - member's root/rect: nesting a variant makes the member the new deepest origin, so subsequent plain - `make-nested-component` descends to the variant's image (its `:nested-head`) at every level. -- `switch-variant [target value]` (frontend event) — switch the variant copy head bound to `target` - to the sibling member with property value `value`, via the REAL `dwv/variants-switch` event (which - DISCOVERS the sibling in the container via `find-variant-components`). `target` uses the standard - resolution (role | label | fn), so the op knows nothing about nesting; cases supply - `nested-head-of name i`. +**Fidelity warning:** the harness drives a MINIMALLY-ASSEMBLED app — only some +`initialize-workspace` subscriptions are wired. Risk = SILENT UNDER-WIRING (e.g. undo needs the +harness `watch-undo-stack`). When a case needs app behaviour beyond a raw edit, check for an +unwired subscription and verify by PROBING store state, not by trusting a green assertion. -## Interpreter (interpreter.cljs) -Drives the real app: -- `op->events [op situation]` maps each event-dispatching operation to its real workspace event(s): - `ChangeProperty`→`dwsh/update-shapes` (the SHARED `set-property`, target via `target-shape-id`); - `MoveChild`→`dwsh/relocate-shapes`; `RemoveChild`→`dwsh/delete-shapes`; `AddChild`→`dwsh/add-shape`; - `SyncFromLibrary`→`dwl/sync-file`; `Undo`→`dwu/undo`; `SwapComponent`→`dwl/component-swap`; - `SwitchVariant`→`dwv/variants-switch {:shapes [head] :pos 0 :val value}`. All real events, so the - watcher auto-propagates. -- `sync-op?` ops (`MakeNestedComponent`, `CreateComponent`, `InstantiateCopy`, `ResetCopyInstance`, - `MakeVariantContainer`, `MakeNestedComponentWithVariant`, `Skip`, `Test`) are NOT dispatched as - events: `run-sync-op` runs the shared `apply-to` against a situation whose `:file` is the live - store file, then writes back synchronously. The property under test is still exercised by the - subsequent real-event ops + the watcher. -- It installs the situation's files into the global `st/state` store (primary as current; aux files - tagged `:library-of` the current file so the library-sync machinery treats them as linked), starts - the real `watch-component-changes` and the harness `watch-undo-stack`, then folds the operations: - dispatch events → await settlement → re-read the current file into `:file` → record. Re-reading - `:file` each step is why the shared role accessors keep working. -- `watch-undo-stack` mirrors the production undo-append subscription from `initialize-workspace` - (which the harness does not run); without it `dwu/undo` has an empty stack. -- Settlement (`await-settle`): subscribe to the commit stream, resolve on the first 60ms idle gap - after a commit (captures the edit commit and the watcher's follow-up sync commit), 2000ms timeout. - Debounce-based, not a deterministic per-op stopper. After settling, `op-grace-ms` adds a per-op - grace wait (currently only `SyncFromLibrary`, ~3.2s — see the Running note). -- Thumbnail rendering is stubbed for this suite (`install-thumbnail-noop!` no-ops - `dwth/update-thumbnail`): the propagation watcher schedules thumbnail renders that reach `window`, - absent headless. -- `check [done case-map asserter]` enumerates, runs each variant via the async fold, wraps the - asserter in `describe-applied`, and calls `done`. Per-variant isolation = id-map reset + global - state re-install (the global `st/state` is a shared `defonce`). -- STORE-SWAP IMMUNITY (`original-store`/`restore-global-store!`): many plugins-suite namespaces - `set!` `st/state`/`st/stream` to isolated stores and never restore them. The `app.main.refs` - lenses (through which the watcher observes commits) are okulary lenses bound to the ORIGINAL - atom instance at load time — after such a swap, events commit to a store the watcher cannot see - and ALL propagation dies silently (assertions see base/unsynced state; no error). The interpreter - therefore captures `st/state`/`st/stream` at namespace-LOAD time (before any test runs) and - re-`set!`s them at the start of every variant, making the harness immune to run order. Diagnosed - by bisecting the runner's deterministic execution order (it is NOT the `test-namespaces` vector - order: `t/test-vars-block` groups vars by namespace, and the group-by hash order decides — same - order locally and in CI). +**Caveats:** inline `Test` exceptions are UNCAUGHT on the frontend (crash the runner — assert in +the trailing asserter). `(optional (in-sequence …))` is not flattened for the interpreter — use +independent optionals. The Serena/clj-kondo cache for `nodes.cljs` goes stale (phantom symbols) — +trust the build. Cross-namespace global-state leaks land in this suite first; suspect them before +the framework on inexplicable full-run-only failures. Case H's `sync-file` schedules a delayed RPC +that fails headless (benign; absorbed by per-op grace). -## Cases -Asserters are inline; no `doseq`, no count assertions. -- **B** — an override on the copy survives a later main change (override present + `:touched` - contains the fill group + `:shape-ref` present). -- **C** — attribute sweep via `one-of {fills, opacity}`: assert `(has-attr? (get-choice …) copy)` - per enumerated variant. -- **D** — `add-child` to the main gives the copy a ref-integral child (`is-main-of?` + - `parent-of?` + untouched). -- **E** — `remove-child` of the MIDDLE of three: survivors keep order `[child1, child3]`, - `:shape-ref` intact, untouched (middle removal is where index maintenance is tested). -- **F** — `move-child` of child1 to index 2: copy mirrors `[child2, child1, child3]`, identity - preserved. -- **H** — locality (cross-file): main in a linked library, copy in the consuming (current) file, - library main diverged. The in-file watcher does not cross a library boundary; the cross-file - mechanism is the library-update action (`sync-from-library` → `sync-file file-id library-id`). - Setup order matters: instantiate the copy first (captures the old value), diverge the library main - after. -- **I** — undo: an edit then `undo`; copy and main return to baseline, copy untouched. A single - `dwu/undo` reverses the whole logical action — the edit AND its auto-propagation — because the two - commits share an undo-group. -- **K** — SYNC-SCENARIO SWEEP (the flagship). On `empty-situation`: `create-component` → two - `(optional make-nested-component)` (depths 0/1/2) → `instantiate-copy` → three `(optional change-*)` - over remote/main/copy → INLINE checkpoints: (1) override-precedence at the copy (copy wins, else - main, else remote — branch via `applied?`), (2) force a copy override and confirm it wins, (3) - after `reset-copy-instance`, copy reverts to main's value if main changed, else remote's. No - explicit propagate (the watcher auto-propagates at all depths, incl. chained remote→deep-copy). -- **L** — SWAP SWEEP. On `empty-situation`: `create-component` (base) + one swap-target lineage per - level → three `make-nested-component` → three `(optional (swap-component "main" i target_i))` → - one `Test` asserting each level's colour. A swap at level i auto-propagates to level i and every - OUTER level until a higher swap overrides; colour at level i = applied swap at highest j<=i, else - base. -- **M** — VARIANT-SWITCH SWEEP (case L with a variant switch instead of the plain swap, driving the - REAL variant-switch machinery). On `empty-situation`: `create-component` (base lineage "main") + - `make-variant-container` (4 peer members `v0..v3`) → ONE `make-nested-component-with-variant - "main" "vset" "v0"` (introduce the variant innermost) + two plain `make-nested-component` - (progressive wraps, so each outer level CONTAINS the one below) → three - `(optional (switch-variant (nested-head-of "main" i) v_{i+1}))` → one `Test` with case L's exact - precedence asserter. Because the single variant instance has a switchable `:nested-head` at EVERY - level and the levels are progressively nested, a switch at level i propagates outward like a swap. - NOTE on structure: ONE variant + plain wraps is required for cross-level propagation (the levels - nest WITHIN each other). Three independent `make-nested-component-with-variant` would nest SIBLING - variants (none a descendant of another), so switches would not propagate between them — the right - construction for a different test (one asserting switches DON'T cross unrelated instances). +--- -Running: `cd frontend && pnpm run build:test` then `node target/tests/test.js --focus -frontend-tests.composable-tests.comp.sync-test`. To run one case, use var-level focus, e.g. -`…/case-m-variant-switch-scenarios`. NOTE: the production `sync-file` event (case H) additionally -schedules a 3s-delayed `update-file-library-sync-status` RPC, which fails headless (no backend; a -swallowed URL-parse trace is benign). The interpreter absorbs it: `op-grace-ms` makes the run wait -~3.2s after a `SyncFromLibrary` settles, so the failure lands inside case H instead of leaking into -(and potentially destabilising) whichever test runs next. +# TypeScript suite (the plugin) — full e2e -## Frontend fidelity — read before extending -The frontend runs the REAL production logic from the dispatched event onward, so observed semantics -are genuine. But it drives a MINIMALLY-ASSEMBLED app: it installs a file into the global store and -starts only the watchers known to be needed. The real app assembles its workspace via -`initialize-workspace`, which wires many subscriptions; the harness reproduces only some. +`plugins/apps/composable-test-suite/` — same principles against the FULL production app through the +Plugin API (real frontend, real propagation). Continuation of the CLJS suite per issue #10584. +Operational details (build/run, connect URL, remote control, reading logs, auto-reload, CI): the +plugin README. -The risk is SILENT UNDER-WIRING — a behaviour that works in the real app can be silently absent in -the harness with no error (e.g. the undo stack is empty unless `watch-undo-stack` is started). -Therefore: when adding a case needing app behaviour beyond a raw edit (undo, persistence, selection, -layout, thumbnails, library auto-detection), first check whether that behaviour lives in an -`initialize-workspace` subscription the harness has not wired — and verify by PROBING store state, -not by trusting a green assertion. The harness hand-wires two stand-ins (`install-file-event`, -`watch-undo-stack`); track them for drift. A durable fix would be to drive the real -`initialize-workspace` headlessly (not done — full init may pull in machinery that doesn't run -cleanly headless). +Distinguishing abstractions (the OOP articulation of the shared principles): +- `TestCase {identifier, description, operation}` with the three-part description mandated in the + constructor docstring. +- The accessor-interface principle is class-level: foundation operations (e.g. + `OpCreateSimpleComponentWithCopy`) expose the roles they build; **content-creation strategies** + (pluggable: what content a foundation builds around) expose accessors for the content they + created; edit operations expose their checks (`OpChangeProperty.assertHasChangedProperty`); + `OpOneOf`/`OpOptional` are queried for what ran. Tests never grope the document for something a + producer can be asked for. +- `ShapeProp` model: property duals with numeric tolerance; rotation is a writable attr, height + goes via resize (readonly in the Plugin API). +- `TestSuite` enumerates cases into a `TestTree` with stable per-test ids; + `run(ids, TestRunObserver)` is the ONLY output channel — the framework is UI-free by + construction. `plugin.ts` (panel adapter), `main.ts` (panel UI) and `src/ci/headless.ts` + (CI adapter) are three thin consumers. +- Cases live in `src/composable-tests/cases/` as `case.ts` (e.g. `MainEditSyncs` — the + sweep that found #10109). +- Panel checkboxes carry stable DOM ids (case identifier / `Identifier-N` composites) for remote + control via Playwright; recipe in the README. -## Other caveats -- Cross-namespace leaks land in this suite first because it (correctly) uses the real global - store: besides the store swap above, `frontend-tests.helpers.wasm/teardown-wasm-mocks!` used to - `set!` every WASM fn to nil when run against an empty snapshot (double teardown / async misuse of - `with-wasm-mocks*`), which a leaked debounced `resize-wasm-text` event then tripped over during - our cases (a "Store error: initialized? is not a function"). The teardown is now guarded - (no-op on empty snapshot). If a new inexplicable full-run-only failure appears here, suspect - leaked global state from a preceding namespace before suspecting the framework. -- INLINE `Test` exceptions on the frontend are UNCAUGHT (they run during the async fold, not under - `check`'s try): a throwing checkpoint crashes the whole runner rather than failing one test. -- A `RecordedChoice` wrapping a `Sequence` (i.e. `(optional (in-sequence […]))`) is NOT flattened by - `sequence-ops`, so `op->events` chokes on the `Sequence`. Use independent optionals instead (as - case K does with two `(optional make-nested-component)`), or have the interpreter recurse into a - choice's composite alternative. -- The Serena symbol index / clj-kondo cache for `nodes.cljs` can go STALE and report PHANTOM symbols - or spurious "unresolved symbol" errors against code that compiles — TRUST THE BUILD (a real - `pnpm run build:test`), not the lint or the symbol overview, for this file. -- Label-after-the-fact resolution: `add-child`'s `added-shape` resolves `:new-label` via `thi/id`, - relying on the global label map still reflecting that run's setup — unsound if a structural node - is swept via `one-of`. Fix when needed by capturing the created shape's id at apply-time (as roles - already do). +## CI +Headless per-PR gate: `.github/workflows/tests-composable-suite.yml` runs +`pnpm --filter composable-test-suite run test:ci` — mocked backend (frontend e2e static server + +Playwright RPC fixtures, no backend/login), the in-sandbox bundle injected via `ɵloadPlugin`, +results streamed via console markers, `TEST_FILTER` by identifier substring. The mocked backend is +NOT a limitation for this suite (everything asserted is frontend store logic; empirically +confirmed against the interactive runs). Architecture mirrors `plugin-api-test-suite`'s CI driver; +the mock harness exists in THREE places that must stay in sync (provenance note in `ci/run-ci.ts`). +Details: README, "Running in CI". ## Substrate `mem:common/test-setup`, `mem:common/component-data-model`, `mem:common/component-swap-pipeline`, diff --git a/.serena/memories/frontend/core.md b/.serena/memories/frontend/core.md index b229e2b124..b5fb47dce4 100644 --- a/.serena/memories/frontend/core.md +++ b/.serena/memories/frontend/core.md @@ -23,7 +23,7 @@ From `frontend/`: - JS lint currently no-ops via `pnpm run lint:js`. - SCSS lint: `pnpm run lint:scss`. - Format checks: `pnpm run check-fmt:clj`, `pnpm run check-fmt:js`, `pnpm run check-fmt:scss`. -- Format fix: `pnpm run fmt`, or targeted `fmt:clj` / `fmt:js` / `fmt:scss`. +- Format fix: `pnpm run fmt`, or targeted `fmt:clj` / `fmt:js` / `fmt:scss`. After running `fmt:*`, `check-fmt:*` is redundant. - Translation formatting after i18n edits: `pnpm run translations`. **Before linting:** if delimiter errors are suspected (after LLM edits, or diff --git a/.serena/memories/media-processor/core.md b/.serena/memories/media-processor/core.md new file mode 100644 index 0000000000..209d4b1a37 --- /dev/null +++ b/.serena/memories/media-processor/core.md @@ -0,0 +1,100 @@ +# Media Processor + +Stateless HTTP service for Penpot image and font processing. Handles image info extraction, thumbnail generation (sharp), and font conversion (FontForge, woff-tools). + +## Tech Stack + +- Language: TypeScript +- Runtime: Node.js +- Framework: Express +- Image processing: sharp (libvips) +- Font processing: FontForge (TTF/OTF), sfnt2woff, woff2_decompress +- Upload handling: multer (hybrid storage: memory for small, disk for large) +- Logging: pino (with optional Loki transport) +- Config validation: Zod +- Testing: Vitest +- Package Manager: pnpm + +## Project Structure + +``` +media-processor/ +├── src/ +│ ├── index.ts # Express app setup, routes, middleware +│ ├── config.ts # Zod-validated env config, HKDF key derivation +│ ├── types.ts # TypeScript type definitions +│ ├── upload.ts # Multer configuration, getFileBuffer helper +│ ├── upload-storage.ts # Hybrid storage engine (memory < threshold, disk >= threshold) +│ ├── logger.ts # Pino logger setup +│ ├── middleware/ +│ │ ├── auth.ts # Timing-safe shared key authentication +│ │ ├── error-handler.ts # ProcessingError class, centralized error handling +│ │ └── timeout.ts # Request timeout middleware +│ ├── routes/ +│ │ ├── health.ts # GET /api/health +│ │ ├── image.ts # POST /api/image/info, /api/image/thumbnail +│ │ └── font.ts # POST /api/font/convert +│ └── services/ +│ ├── image.ts # sharp-based image info/thumbnail generation +│ ├── font.ts # FontForge/woff-tools font conversion +│ └── errors.ts # throwValidation, throwRestriction, throwProcessing +├── test/ # Vitest test files +├── vitest.config.ts # Test configuration +├── tsconfig.json # TypeScript configuration +├── esbuild.config.mjs # Build configuration +└── package.json # Dependencies and scripts +``` + +## Key Conventions + +### Auth +- Requests authenticated via `x-shared-key` header using timing-safe comparison +- When no key configured, all requests rejected with 403 +- Key derived from `PENPOT_SECRET_KEY` via HKDF (blake2b512) or set directly via `PENPOT_MEDIA_PROCESSOR_SHARED_KEY` + +### Resource Limits +- Image: max pixels, max width/height enforced before processing +- Font: prlimit wraps FontForge processes with memory (AS) and CPU time limits +- Concurrency: p-queue limits concurrent requests (default 10) +- Upload: hybrid storage — memory for files < 10MB, disk for larger; configurable via `PENPOT_MEDIA_PROCESSOR_MEMORY_THRESHOLD` +- Max file size: configurable (default 350MB) + +### Error Handling +- `throwValidation(code, hint)` — 400 errors for invalid input +- `throwRestriction(code, hint)` — 413 errors for resource limits exceeded +- `throwProcessing(code, hint)` — 503 errors for processing failures (e.g., resource limit kills) + +### Image Processing +- EXIF orientation applied before dimension validation and thumbnail generation +- sharp caching disabled to prevent unbounded memory growth +- `withoutEnlargement: true` prevents upscaling small images + +### Font Conversion +- Supported formats: TTF, OTF, WOFF, WOFF2 +- SFNT type detected via magic bytes (0x4f54544f = OTF, 0x00010000 = TTF) +- Temp files cleaned up in finally blocks (best-effort) + +## Commands + +All commands run from `media-processor/` directory: + +- `pnpm run test` — Run Vitest test suite +- `pnpm run types:check` — TypeScript type checking (tsc --noEmit) +- `pnpm run fmt` — Format code with Prettier +- `pnpm run fmt:check` — Check formatting without modifying +- `pnpm run build` — Build for production (esbuild) +- `pnpm run start:dev` — Start development server (tsx) + +## Docker + +- Exposed port: 6065 (configurable via `PENPOT_MEDIA_PROCESSOR_PORT`) +- Must be deployed on internal Docker network only (not public-facing) +- Backend communicates via `PENPOT_MEDIA_PROCESSING_SERVICE_URI` + +## Testing Principles + +Cross-cutting testing principles and anti-patterns: `mem:testing`. + +- Run `pnpm run test` after changes +- Run `pnpm run types:check` after TypeScript changes +- Run `pnpm run fmt:check` before commits diff --git a/.serena/memories/scripts/error-reports.md b/.serena/memories/scripts/error-reports.md new file mode 100644 index 0000000000..126aae7903 --- /dev/null +++ b/.serena/memories/scripts/error-reports.md @@ -0,0 +1,289 @@ +# Error Reports CLI Tool + +`scripts/error-reports.mjs` is a Node.js CLI tool for querying Penpot error reports via the RPC API. Provides access to error logs with filtering, pagination, and multiple output formats. + +## When to use + +- Querying error reports from the database for debugging or analysis +- Filtering errors by source, kind, tenant, or backend version +- Exporting error data in JSON, NDJSON, or table format +- Computing error statistics (top signatures, version, source, audit-log kind, hourly distribution, bursts, heatmap) +- Investigating specific error reports by ID + +## Prerequisites + +- Node.js with `commander` and `dotenv` packages installed (in root `package.json`) +- Running Penpot backend with error-reports RPC endpoints +- Access token with `error-reports:read` permission + +## Configuration + +Create a `.env` file in the project root: + +```bash +PENPOT_API_URI=http://localhost:3450 +PENPOT_ACCESS_TOKEN= +``` + +Grant the required permission to your access token: + +```sql +UPDATE access_token +SET perms = ARRAY['error-reports:read']::text[], + updated_at = now() +WHERE id = ''; +``` + +## Usage + +```bash +./scripts/error-reports.mjs [options] +``` + +### Commands + +#### `list` - List error reports with pagination and filters + +```bash +./scripts/error-reports.mjs list [options] +``` + +**Options:** + +| Flag | Description | Default | +|------|-------------|---------| +| `-l, --limit ` | Max items per page (max: 200) | `50` | +| `--from ` | ISO timestamp — oldest boundary (items after this) | — | +| `--to ` | ISO timestamp — newest boundary (items before this) | — | +| `--since ` | ISO timestamp — explicit cursor for manual pagination | — | +| `--since-id ` | Fetch errors after this ID (cursor pagination) | — | +| `-s, --source ` | Filter by source (see source names below) | — | +| `-p, --profile-id ` | Filter by profile ID | — | +| `-k, --kind ` | Filter by kind (string) | — | +| `-t, --tenant ` | Filter by tenant (string) | — | +| `--version ` | Filter by version | — | +| `--hint ` | Filter by hint (ILIKE match) | — | +| `-a, --all` | Fetch all pages automatically (streams output) | `false` | +| `-f, --format ` | Output format: `json`, `table`, or `ndjson` | `table` | +| `--normalize-hints` | Normalize hints by stripping dynamic values | `false` | +| `-o, --output ` | Write output to file instead of stdout | — | +| `--env ` | Custom .env file path | `.env` | +| `-h, --help` | Show help message | — | + +**Streaming behavior:** With `--all`, output must be `ndjson` or `table`; `--all --format json` is rejected because `--all` streams output. `--all --format table` prints rows immediately. `--format ndjson` always streams one JSON object per line. + +#### `get` - Get a single error report by ID + +```bash +./scripts/error-reports.mjs get [options] +``` + +**Options:** + +| Flag | Description | Required | +|------|-------------|----------| +| `--id ` | Error report ID | Yes (or --error-id) | +| `--error-id ` | Error report error-id | Yes (or --id) | +| `-f, --format ` | Output format: `json` or `table` | No (default: `table`) | +| `--env ` | Custom .env file path | No (default: `.env`) | +| `-h, --help` | Show help message | No | + +#### `stats` - Compute error report statistics + +```bash +./scripts/error-reports.mjs stats [options] +``` + +Reads from `--input `, stdin (piped), or fetches from API. Computes aggregations by signature, version, source, audit-log kind, hour, optional 5-minute bursts, and optional day-of-week × hour heatmap. + +**Options:** + +| Flag | Description | Default | +|------|-------------|---------| +| `--from ` | Start of interval (ISO timestamp) | — | +| `--to ` | End of interval (ISO timestamp) | — | +| `--limit ` | Items per page when fetching from API | `200` | +| `--input ` | Read from local JSON/NDJSON file instead of API | — | +| `--burst` | Detect 5-minute windows above 3× the average rate | `false` | +| `--heatmap` | Show day-of-week × hour-of-day heatmap | `false` | +| `-f, --format ` | Output format: `json` or `table` | `table` | +| `--env ` | Custom .env file path | `.env` | + +## Source Names + +The `--source` filter accepts these values: + +- `logging` +- `audit-log` +- `rlimit` + +## Hint Normalization + +With `--normalize-hints` (or always in `stats`), hints are normalized by stripping dynamic values: + +1. File IDs in file-id context → `` +2. UUIDs (8-4-4-4-12 hex) → `` +3. Numeric IDs in parentheses `(12345)` → `()` +4. Elapsed times (`7.5s`, `2m3.027s`) → `` +5. URIs (`https://...`) → `` +6. Unicode quotes and whitespace normalized + +## Examples + +### List recent errors +```bash +./scripts/error-reports.mjs list --limit 10 +``` + +### Time-range query (today) +```bash +./scripts/error-reports.mjs list --from 2026-07-23T00:00:00Z --to 2026-07-23T23:59:59Z --all +``` + +### Stream all errors as NDJSON +```bash +./scripts/error-reports.mjs list --all --format ndjson > errors.ndjson +``` + +### Save to file with --output +```bash +./scripts/error-reports.mjs list --all --format ndjson -o errors.ndjson +./scripts/error-reports.mjs list --format json -o errors.json +``` + +### Filter by source +```bash +./scripts/error-reports.mjs list --source audit-log --limit 20 +``` + +### Filter by kind +```bash +./scripts/error-reports.mjs list --kind exception-page +``` + +### Filter by tenant +```bash +./scripts/error-reports.mjs list --tenant production +``` + +### Filter by version +```bash +./scripts/error-reports.mjs list --version 2.1.0 +``` + +### Search by hint (partial match) +```bash +./scripts/error-reports.mjs list --hint "NullPointerException" +``` + +### Fetch all errors with pagination +```bash +./scripts/error-reports.mjs list --all +``` + +### Get specific error by ID +```bash +./scripts/error-reports.mjs get --id 550e8400-e29b-41d4-a716-446655440000 +``` + +### Output as JSON +```bash +./scripts/error-reports.mjs list --limit 5 --format json +``` + +### Combine filters +```bash +./scripts/error-reports.mjs list --source audit-log --kind exception-page --tenant production --limit 50 +``` + +### Stats with burst and heatmap analysis +```bash +./scripts/error-reports.mjs stats --from 2026-07-23T00:00:00Z --to 2026-07-23T23:59:59Z --burst --heatmap +``` + +### Stats from file +```bash +./scripts/error-reports.mjs stats --input errors.json +``` + +### Stats from pipe +```bash +./scripts/error-reports.mjs list --all --format json | ./scripts/error-reports.mjs stats +``` + +## Output Formats + +### Table (default) +Human-readable table format for terminal display. With `--all`, rows stream as they arrive. + +### JSON +Single page: `{items: [...], nextSince, nextId}`. `--all` cannot be combined with `--format json`; use `--format ndjson` for streaming. + +### NDJSON +One JSON object per line, always streaming. Pipe-friendly: `| jq -c '.hint'`, `| wc -l`. + +## Pagination + +The server returns items in **ascending** order (oldest first). Cursor pagination uses `--since` / `--since-id` to fetch the next page of newer items. + +### Manual pagination +Use `--since` and `--since-id` with values from `nextSince` and `nextId` in the response: + +```bash +./scripts/error-reports.mjs list --limit 50 +# Use nextSince and nextId from response +./scripts/error-reports.mjs list --limit 50 --since "2026-01-20T10:29:00Z" --since-id "next-uuid" +``` + +### Automatic pagination +Use `--all` to fetch all pages automatically (streams output): + +```bash +./scripts/error-reports.mjs list --all +``` + +### Time-range queries +Use `--from` and `--to` to bound the query. These map to the server's `--since` and `--until` parameters: + +```bash +./scripts/error-reports.mjs list --from 2026-07-20T00:00:00Z --to 2026-07-23T23:59:59Z --all +``` + +## Key principles + +- **Authentication required** - Uses access token with `error-reports:read` permission +- **API endpoint configurable** - Set via `PENPOT_API_URI` in `.env` file +- **Table is default format** - Use `--format json` for structured JSON, `--format ndjson` for streaming +- **Streaming with --all** - Items print as they arrive, no buffering. Use `--format ndjson` or `--format table`; `--all --format json` is rejected. +- **Filters are combinable** - All filter options can be used together +- **Both flag formats supported** - `--option=value` and `--option value` both work +- **Ascending order** - Server returns oldest items first (changed from DESC) + +## Error handling + +The tool provides helpful error messages for common issues: + +- **Missing configuration**: Shows setup instructions for `.env` file +- **Authentication errors (401)**: Indicates invalid or expired token +- **Authorization errors (403)**: Indicates missing `error-reports:read` permission +- **RPC errors**: Displays error code and message from the API + +## Integration with other scripts + +- **jq**: Pipe NDJSON output to `jq` for further processing + ```bash + ./scripts/error-reports.mjs list --all --format ndjson | jq -c '{id, hint}' + ``` +- **stats from pipe**: Fetch data once, compute stats + ```bash + ./scripts/error-reports.mjs list --all --format ndjson | ./scripts/error-reports.mjs stats + ``` +- **stats from NDJSON pipe**: Works with NDJSON format too + ```bash + ./scripts/error-reports.mjs list --all --format ndjson | ./scripts/error-reports.mjs stats + ``` +- **grep/search**: Filter output by specific patterns +- **--output**: Save to file without shell redirection + ```bash + ./scripts/error-reports.mjs list --all --format ndjson -o errors.ndjson + ``` diff --git a/.serena/memories/scripts/paren-repair.md b/.serena/memories/scripts/paren-repair.md index 162e6d28d8..234a4c8688 100644 --- a/.serena/memories/scripts/paren-repair.md +++ b/.serena/memories/scripts/paren-repair.md @@ -29,7 +29,7 @@ bb scripts/paren-repair --help ## Native Tool Available (opencode) -A native opencode tool `paren-repair` is available at `.opencode/tools/paren-repair.ts`. +A native opencode tool `paren-repair` is available at `.opencode/scripts/paren-repair.ts`. The LLM can call it directly with: - `files`: Array of file paths to fix - `code`: Code string to fix via stdin diff --git a/.serena/memories/testing.md b/.serena/memories/testing.md index ce4990ba12..295da86212 100644 --- a/.serena/memories/testing.md +++ b/.serena/memories/testing.md @@ -137,17 +137,32 @@ E2E tests should not be added unless explicitly requested. ## Execution discipline -When running CLJS/JS tests (frontend, common): +**CRITICAL: Test output handling rules** +When running ANY test command (CLJS/JS or JVM): + +1. **NEVER pipe test output directly to `| head`, `| tail`, `| grep`, or similar filters** — this can hide failures and cause you to miss critical errors. +2. **ALWAYS pipe to a file first, then read the file:** + ```bash + # CORRECT: + pnpm run test 2>&1 > /tmp/test-output.txt + grep -A 5 "failures" /tmp/test-output.txt + + # WRONG: + pnpm run test 2>&1 | tail -20 + pnpm run test 2>&1 | grep "failures" + ``` +3. **Use `--focus` to narrow test scope** instead of filtering output. +4. **Read the full output file** to understand test results completely. + +When running CLJS/JS tests (frontend, common): - **Always use `pnpm run test:quiet`** — it silently builds the test bundle then runs the test runner, giving you clean test output. -- **Never pipe test output through `tail`, `head`, or similar filters** — doing so can silently hide test failures. Use `--focus` to narrow scope instead. -- **If you need to filter output, tee to a temp file first:** `pnpm run test:quiet 2>&1 | tee /tmp/penpot-test-output.txt`. The full output is preserved on disk so you can `grep`/`tail`/`head` the file without re-running. - Use `pnpm run test` when you want to see build output alongside test results (always builds, then runs). - After `build:test` has been run once, you can invoke the runner directly: `node target/tests/test.js [--focus ...] [--log-level ...]`. When running JVM tests (backend, common): - Use `clojure -M:dev:test` directly (no pnpm wrapper). -- The same no-piping rule applies: use `--focus` to narrow scope. +- Same file-piping rule applies. ## Verification Checklist diff --git a/.serena/memories/workflow/creating-commits.md b/.serena/memories/workflow/creating-commits.md index d37d4672a5..2fc766d4ad 100644 --- a/.serena/memories/workflow/creating-commits.md +++ b/.serena/memories/workflow/creating-commits.md @@ -14,6 +14,8 @@ automatically pull the identity from the local git config `user.name` and `user. :emoji: Subject line (imperative, capitalized, no period, <=70 chars) Body explaining what changed and why. +Wrap lines at 72 characters — git log and tooling +render long lines poorly. Keep each line concise. AI-assisted-by: model-name ``` @@ -25,3 +27,7 @@ AI-assisted-by: model-name ## Commit Type Emojis `:bug:` bug fix · `:sparkles:` enhancement · `:tada:` new feature · `:recycle:` refactor · `:lipstick:` cosmetic · `:ambulance:` critical fix · `:books:` docs · `:construction:` WIP · `:boom:` breaking · `:wrench:` config · `:zap:` perf · `:whale:` docker · `:paperclip:` other · `:arrow_up:` dep upgrade · `:arrow_down:` dep downgrade · `:fire:` removal · `:globe_with_meridians:` translations · `:rocket:` epic/highlight + +## Referencing Issues + +Use `Closes #NNNN` (not `Fixes #NNNN`) to link a commit to a GitHub issue. diff --git a/.serena/memories/workflow/creating-prs.md b/.serena/memories/workflow/creating-prs.md index 00252a7661..a92c199e22 100644 --- a/.serena/memories/workflow/creating-prs.md +++ b/.serena/memories/workflow/creating-prs.md @@ -30,7 +30,7 @@ See `mem:workflow/creating-commits` for emoji codes. Squash merge uses the PR ti Include concise sections covering: - what changed and why; -- related GitHub issues or Taiga stories (`Fixes #NNNN`, `Relates to #NNNN`, `Taiga #NNNN`); +- related GitHub issues or Taiga stories (`Closes #NNNN`, `Relates to #NNNN`, `Taiga #NNNN`); - screenshots or recordings for UI-visible changes; - testing performed and residual risk; - breaking changes or migration notes, if any. @@ -42,15 +42,15 @@ PR descriptions follow this structure: ## What - + ## Why - + ## How - + ``` The "Note:" line is required at the top. Adjust if this is a manual (non-AI) PR. @@ -59,6 +59,8 @@ The "Note:" line is required at the top. Adjust if this is a manual (non-AI) PR. - **Write for humans.** The diff shows what changed. The description explains why. - **Be concise.** Focus on reasoning: What was the problem? Why did it happen? How did you solve it? +- **Prefer bullets over paragraphs.** Short bullet items, grouped by area with bold lead-ins where helpful, are far easier to digest than prose; keep any remaining paragraph to a few sentences. +- **No manual line wraps.** Markdown renders adapting to the viewport; hard-wrapped lines degrade rendering. One line per paragraph or bullet, however long. - **Skip the obvious.** Don't explain what `git diff` already shows. ### What NOT to Include diff --git a/AGENTS.md b/AGENTS.md index b6aae1f32d..ac4da5c663 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,9 @@ wait for the user to push. Do not change the remote URL, do not switch SSH↔HTTPS. - **Never amend a commit that has been pushed** unless the user explicitly asks. If the user pushes, treat that commit as final from the agent's side. +- **Never pipe test output directly to filters** (`| head`, `| tail`, `| grep`, etc.). + Always redirect to a file first: `command > /tmp/output.txt 2>&1`, then read/grep the file. + This prevents hiding test failures. See `mem:testing` for details. - **Read the workflow memory BEFORE the corresponding action**: - Before `git commit` → `mem:workflow/creating-commits` (commit format, AI-assisted-by trailer) - Before `gh issue create` → `mem:workflow/creating-issues` (title derivation, body template, Issue Type) @@ -109,4 +112,5 @@ precision while maintaining a strong focus on maintainability and performance. - `scripts/nrepl-eval.mjs` — Evaluate Clojure code via nREPL (backend + frontend). - `scripts/check-commit` — Validate commit messages against Penpot's commit guidelines. - `scripts/check-fmt-clj` — Check Clojure formatting without modifying files. +- `scripts/ci` — CI orchestration script for running lint, tests, and format checks across modules. See `scripts/ci --help`. diff --git a/CHANGES.md b/CHANGES.md index a9df8cff57..bcfd77b8bc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -23,6 +23,18 @@ - Refactor wasm rulers and UI state [#10116](https://github.com/penpot/penpot/issues/10116) (PR: [#10461](https://github.com/penpot/penpot/pull/10461)) - Improve team invitations modal in the dashboard [#10484](https://github.com/penpot/penpot/issues/10484) (PR: [#10459](https://github.com/penpot/penpot/pull/10459)) + +## 2.17.1 (Unreleased) + +### :bug: Bugs fixed + +- Fix malformed get-font-variants request when team-id is missing from dashboard URL [#10644](https://github.com/penpot/penpot/issues/10644) (PR: [#10645](https://github.com/penpot/penpot/pull/10645)) +- Fix malformed get-profiles-for-file-comments request when file-id is missing from workspace URL [#10652](https://github.com/penpot/penpot/issues/10652) (PR: [#10655](https://github.com/penpot/penpot/pull/10655)) +- Fix workspace crash when holding an arrow key on a selection due to excessive re-renders [#10726](https://github.com/penpot/penpot/issues/10726) (PR: [#10736](https://github.com/penpot/penpot/pull/10736)) +- Fix asset download failing with S3 auth conflict when using access token [#10776](https://github.com/penpot/penpot/issues/10776) (PR: [#10777](https://github.com/penpot/penpot/pull/10777)) +- Fix internal error when dragging inner layout with Boolean operations [#10647](https://github.com/penpot/penpot/issues/10647) (PR: [#10778](https://github.com/penpot/penpot/pull/10778)) +- Fix viewer crash with WASM panic when opening URL with page-id [#10800](https://github.com/penpot/penpot/issues/10800) (PR: [#10805](https://github.com/penpot/penpot/pull/10805)) + ## 2.17.0 ### :rocket: Epics and highlights @@ -59,49 +71,28 @@ - Render guides in WebGL [#10068](https://github.com/penpot/penpot/issues/10068) (PR: [#10014](https://github.com/penpot/penpot/pull/10014)) - Add configurable resource limits to ImageMagick image processing [#10223](https://github.com/penpot/penpot/issues/10223) (PR: [#10240](https://github.com/penpot/penpot/pull/10240)) - Add resource limits to font processing child processes [#10234](https://github.com/penpot/penpot/issues/10234) (PR: [#10274](https://github.com/penpot/penpot/pull/10274)) -- Add color variants and positioning to selection size badge (by @bittoby) [#10258](https://github.com/penpot/penpot/issues/10258) (PR: [#9210](https://github.com/penpot/penpot/pull/9210)) +- Add color variants and positioning to selection size badge [#10258](https://github.com/penpot/penpot/issues/10258) (PR: [#9210](https://github.com/penpot/penpot/pull/9210)) - Use hard reload for render engine switching in the workspace menu [#10441](https://github.com/penpot/penpot/issues/10441) (PR: [#10444](https://github.com/penpot/penpot/pull/10444)) - Rotate size badge when shape is rotated [#10386](https://github.com/penpot/penpot/issues/10386) (PR: [#10393](https://github.com/penpot/penpot/pull/10393)) - Add separate internal URI for exporter to handle Docker deployments where internal and public URIs differ [#10627](https://github.com/penpot/penpot/issues/10627) (PR: [#10630](https://github.com/penpot/penpot/pull/10630)) ### :bug: Bugs fixed -- Fix LDAP provider params schema typo (`bind-passwor` → `bind-password`) introduced during the `clojure.spec` → `malli` migration; the schema slot now matches the runtime key actually read by `prepare-params` (`:password (:bind-password cfg)`) and `try-connectivity` (`(:bind-password cfg)`), so a wrong type for the password no longer slips through unvalidated -- Fix `login-with-ldap` silently dropping its error message on the `ldap-not-initialized` restriction (typo `:hide` → `:hint`); the message `"ldap auth provider is not initialized"` now actually surfaces in logs and error responses instead of being discarded into an unread key -- Fix `get-view-only-bundle` crashing when a share-link viewer encounters a team member whose email lacks `@` (NullPointerException in `obfuscate-email`) or whose domain has no `.` (previously produced a dangling-dot `****@****.`); now the viewer-side obfuscation is nil-safe and omits the trailing dot when the domain has no TLD -- Fix Copy as SVG: emit a single valid SVG document when multiple shapes are selected, and publish `image/svg+xml` to the clipboard so the paste target works in Inkscape and other SVG-native tools [Github #838](https://github.com/penpot/penpot/issues/838) -- Add export panel to inspect styles tab [Taiga #13582](https://tree.taiga.io/project/penpot/issue/13582) -- Fix styles between grid layout inputs [Taiga #13526](https://tree.taiga.io/project/penpot/issue/13526) -- Fix id prop on switch component [Taiga #13534](https://tree.taiga.io/project/penpot/issue/13534) -- Update copy on penpot update message [Taiga #12924](https://tree.taiga.io/project/penpot/issue/12924) -- Fix scroll on library modal [Taiga #13639](https://tree.taiga.io/project/penpot/issue/13639) -- Fix dates to avoid show them in english when browser is in auto [Taiga #13786](https://tree.taiga.io/project/penpot/issue/13786) -- Fix focus radio button [Taiga #13841](https://tree.taiga.io/project/penpot/issue/13841) -- Token tree should be expanded by default [Taiga #13631](https://tree.taiga.io/project/penpot/issue/13631) -- Fix opacity incorrectly disabled for visible shapes [Taiga #13906](https://tree.taiga.io/project/penpot/issue/13906) -- Update onboarding image [Taiga #13864](https://tree.taiga.io/project/penpot/issue/13864) -- Fix plugin modal drag interactions over iframe and close-button behavior (by @marekhrabe) [Github #8871](https://github.com/penpot/penpot/pull/8871) -- Fix hot update on color-row on texts [Taiga #13923](https://tree.taiga.io/project/penpot/issue/13923) -- Fix selected color tokens [Taiga #13930](https://tree.taiga.io/project/penpot/issue/13930) -- Display resolved values of inactive tokens [Taiga #13628](https://tree.taiga.io/project/penpot/issue/13628) -- Fix app crash when selecting shapes with one hidden [Taiga #13959](https://tree.taiga.io/project/penpot/issue/13959) -- Fix opacity mixed value [Taiga #13960](https://tree.taiga.io/project/penpot/issue/13960) -- Fix gap input throwing an error [Github #8984](https://github.com/penpot/penpot/pull/8984) -- Fix copy to be more specific [Taiga #13990](https://tree.taiga.io/project/penpot/issue/13990) -- Fix colorpicker layout so the eyedropper button is visible again [Taiga #14057](https://tree.taiga.io/project/penpot/issue/14057) +- Fix Plugin API variant creation failing due to undocumented multi-step workflow [#10075](https://github.com/penpot/penpot/issues/10075) (PR: [#10149](https://github.com/penpot/penpot/pull/10149)) +- Fix workspace crash when editing text shapes with degenerate selrect [#10617](https://github.com/penpot/penpot/issues/10617) (PR: [#10618](https://github.com/penpot/penpot/pull/10618)) - Fix SVG stroke line join not applied when pasting strokes [#4836](https://github.com/penpot/penpot/issues/4836) (PR: [#9982](https://github.com/penpot/penpot/pull/9982), [#10019](https://github.com/penpot/penpot/pull/10019)) -- Fix blend-mode hover preview on canvas not reverted when dismissing dropdown (by @jack-stormentswe) [#9235](https://github.com/penpot/penpot/issues/9235) (PR: [#9237](https://github.com/penpot/penpot/pull/9237)) +- Fix blend-mode hover preview on canvas not reverted when dismissing dropdown (by @davidv399) [#9235](https://github.com/penpot/penpot/issues/9235) (PR: [#9237](https://github.com/penpot/penpot/pull/9237)) - Fix View Mode mouse-leave and click in combination not working [#4855](https://github.com/penpot/penpot/issues/4855) (PR: [#9991](https://github.com/penpot/penpot/pull/9991)) - Fix Storybook UI missing scrollbar (by @MilosM348) [#6049](https://github.com/penpot/penpot/issues/6049) (PR: [#9319](https://github.com/penpot/penpot/pull/9319)) - Fix font selector missing intermediate font weights for Source Sans Pro and similar fonts (by @dhgoal) [#7378](https://github.com/penpot/penpot/issues/7378) (PR: [#9247](https://github.com/penpot/penpot/pull/9247)) -- Fix plugin API `typography.remove()` passing wrong parameter format (by @leonaIee) [#8223](https://github.com/penpot/penpot/issues/8223) (PR: [#9279](https://github.com/penpot/penpot/pull/9279)) +- Fix plugin API `typography.remove()` passing wrong parameter format (by @peter-rango) [#8223](https://github.com/penpot/penpot/issues/8223) (PR: [#9279](https://github.com/penpot/penpot/pull/9279)) - Fix plugin API fills and strokes array elements being read-only (by @RenzoMXD) [#8357](https://github.com/penpot/penpot/issues/8357) (PR: [#9161](https://github.com/penpot/penpot/pull/9161)) - Fix "Show Guides" shortcut not working on German keyboards (by @RenzoMXD) [#8423](https://github.com/penpot/penpot/issues/8423) (PR: [#9209](https://github.com/penpot/penpot/pull/9209)) - Fix token validation failing when a malformed token exists in the Component category [#9010](https://github.com/penpot/penpot/issues/9010) (PR: [#9025](https://github.com/penpot/penpot/pull/9025), [#9825](https://github.com/penpot/penpot/pull/9825)) - Fix Docker frontend image missing CSS reference (by @NativeTeachingAidsB) [#9135](https://github.com/penpot/penpot/issues/9135) (PR: [#9840](https://github.com/penpot/penpot/pull/9840)) - Fix MCP media upload error and SVG data URI image parsing (by @claytonlin1110) [#9164](https://github.com/penpot/penpot/issues/9164) (PR: [#9201](https://github.com/penpot/penpot/pull/9201)) -- Fix lost-update race on team features during concurrent file creation (by @JPette1783) [#9197](https://github.com/penpot/penpot/issues/9197) (PR: [#9198](https://github.com/penpot/penpot/pull/9198)) -- Fix get-profile RPC method silently masking DB errors as "Anonymous User" (by @jack-stormentswe) [#9253](https://github.com/penpot/penpot/issues/9253) (PR: [#9254](https://github.com/penpot/penpot/pull/9254)) +- Fix lost-update race on team features during concurrent file creation (by @Lobster-0429) [#9197](https://github.com/penpot/penpot/issues/9197) (PR: [#9198](https://github.com/penpot/penpot/pull/9198)) +- Fix get-profile RPC method silently masking DB errors as "Anonymous User" (by @davidv399) [#9253](https://github.com/penpot/penpot/issues/9253) (PR: [#9254](https://github.com/penpot/penpot/pull/9254)) - Fix crash when creating or editing tokens named "white" or "black" [#9256](https://github.com/penpot/penpot/issues/9256) (PR: [#9034](https://github.com/penpot/penpot/pull/9034)) - Fix conditional use-ctx hook violation in shape-wrapper (by @Dexterity104) [#9280](https://github.com/penpot/penpot/issues/9280) (PR: [#9281](https://github.com/penpot/penpot/pull/9281)) - Make ShapeImageIds byte conversion fallible to prevent panics (by @Dexterity104) [#9282](https://github.com/penpot/penpot/issues/9282) (PR: [#9283](https://github.com/penpot/penpot/pull/9283)) diff --git a/backend/deps.edn b/backend/deps.edn index c60adf10ca..1450f4de58 100644 --- a/backend/deps.edn +++ b/backend/deps.edn @@ -6,7 +6,7 @@ org.clojure/clojure {:mvn/version "1.12.5"} org.clojure/tools.namespace {:mvn/version "1.5.1"} - com.github.luben/zstd-jni {:mvn/version "1.5.7-11"} + com.github.luben/zstd-jni {:mvn/version "1.5.7-12"} io.prometheus/simpleclient {:mvn/version "0.16.0"} io.prometheus/simpleclient_hotspot {:mvn/version "0.16.0"} @@ -34,27 +34,28 @@ :exclusions [org.slf4j/slf4j-api]} com.github.seancorfield/next.jdbc - {:mvn/version "1.3.1108"} + {:mvn/version "1.3.1118"} metosin/reitit-core {:mvn/version "0.10.1"} nrepl/nrepl {:mvn/version "1.7.0"} - org.postgresql/postgresql {:mvn/version "42.7.12"} - org.xerial/sqlite-jdbc {:mvn/version "3.53.2.0"} + org.postgresql/postgresql {:mvn/version "42.7.13"} + org.xerial/sqlite-jdbc {:mvn/version "3.53.2.1"} - com.zaxxer/HikariCP {:mvn/version "7.0.2"} + com.zaxxer/HikariCP {:mvn/version "7.1.0"} io.whitfin/siphash {:mvn/version "2.0.0"} buddy/buddy-hashers {:mvn/version "2.0.167"} buddy/buddy-sign {:mvn/version "3.6.1-359"} + org.passay/passay {:mvn/version "1.6.6"} com.github.ben-manes.caffeine/caffeine {:mvn/version "3.2.4"} - org.jsoup/jsoup {:mvn/version "1.22.2"} + org.jsoup/jsoup {:mvn/version "1.23.1"} at.yawk.lz4/lz4-java - {:mvn/version "1.11.0"} + {:mvn/version "1.11.1"} org.clojars.pntblnk/clj-ldap {:mvn/version "0.0.17"} @@ -63,8 +64,8 @@ ;; Pretty Print specs pretty-spec/pretty-spec {:mvn/version "0.1.4"} - software.amazon.awssdk/s3 {:mvn/version "2.46.18"} - software.amazon.awssdk/sts {:mvn/version "2.46.18"}} + software.amazon.awssdk/s3 {:mvn/version "2.50.1"} + software.amazon.awssdk/sts {:mvn/version "2.50.1"}} :paths ["src" "resources" "target/classes"] :aliases diff --git a/backend/dev/user.clj b/backend/dev/user.clj index 406d0c53fd..16908f4cab 100644 --- a/backend/dev/user.clj +++ b/backend/dev/user.clj @@ -104,24 +104,20 @@ [] (try (main/start) - :started (catch Throwable cause (ex/print-throwable cause)))) (defn- stop [] - (main/stop) - :stopped) + (main/stop)) (defn restart [] - (stop) - (repl/refresh :after 'user/start)) + (main/restart)) (defn restart-all [] - (stop) - (repl/refresh-all :after 'user/start)) + (main/restart-all)) ;; (defn compression-bench ;; [data] diff --git a/backend/package.json b/backend/package.json index 96bd4cbada..c6baf43f73 100644 --- a/backend/package.json +++ b/backend/package.json @@ -4,23 +4,25 @@ "license": "MPL-2.0", "author": "Kaleidos INC Sucursal en España SL", "private": true, - "packageManager": "pnpm@11.9.0+sha512.bd682d5d03fe525ef7c9fd6780c6884d1e756ac4c9c9fe00c538782824310dcf90e3ddc4f53835f06dfaebd5085e41855e0bcbb3b60de2ac5bbab89e5036f03b", + "packageManager": "pnpm@11.20.0+sha512.9a6f330a95b66446ea088faf1521405a8a01f07fde7124cc9958dfed52d4bb436737e65b08f85f37b46fcba375092558ac51262b816844b22f63406ed166bfee", "repository": { "type": "git", "url": "https://github.com/penpot/penpot" }, "dependencies": { - "luxon": "^3.4.4", - "sax": "^1.6.0" + "eventsource-parser": "^3.0.6", + "luxon": "^3.7.2", + "sax": "^1.6.1" }, "devDependencies": { "nodemon": "^3.1.14", "source-map-support": "^0.5.21", - "ws": "^8.21.0" + "ws": "^8.21.1" }, "scripts": { - "lint": "clj-kondo --parallel --lint ../common/src src/", - "check-fmt": "cljfmt check --parallel=true src/ test/", - "fmt": "cljfmt fix --parallel=true src/ test/" + "lint:clj": "clj-kondo --config-dir ../.clj-kondo --lint ../common/src src/", + "check-fmt:clj": "cljfmt check --parallel=true src/ test/", + "fmt:clj": "cljfmt fix --parallel=true src/ test/", + "test:e2e": "node --test --test-concurrency=1 test/e2e/*.test.mjs" } } diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yaml index d789e2c2f8..a0b16465e9 100644 --- a/backend/pnpm-lock.yaml +++ b/backend/pnpm-lock.yaml @@ -8,12 +8,15 @@ importers: .: dependencies: + eventsource-parser: + specifier: ^3.0.6 + version: 3.1.0 luxon: - specifier: ^3.4.4 + specifier: ^3.7.2 version: 3.7.2 sax: - specifier: ^1.6.0 - version: 1.6.0 + specifier: ^1.6.1 + version: 1.6.1 devDependencies: nodemon: specifier: ^3.1.14 @@ -22,8 +25,8 @@ importers: specifier: ^0.5.21 version: 0.5.21 ws: - specifier: ^8.21.0 - version: 8.21.0 + specifier: ^8.21.1 + version: 8.21.1 packages: @@ -39,9 +42,9 @@ packages: resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==} engines: {node: '>=8'} - brace-expansion@5.0.7: - resolution: {integrity: sha512-7oFy703dxfY3/NLxC1fh2SUCQ0H9rmAY+5EpDVfXjUTTs+HEwR2nYaqLv+GWcTsumwxPfiz6CzCNkwXwBUwqCA==} - engines: {node: 18 || 20 || >=22} + brace-expansion@5.0.9: + resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} + engines: {node: 20 || >=22} braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} @@ -63,6 +66,10 @@ packages: supports-color: optional: true + eventsource-parser@3.1.0: + resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==} + engines: {node: '>=18.0.0'} + fill-range@7.1.1: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} @@ -130,8 +137,8 @@ packages: resolution: {integrity: sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==} engines: {node: '>=8.10.0'} - sax@1.6.0: - resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==} + sax@1.6.1: + resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==} engines: {node: '>=11.0.0'} semver@7.8.5: @@ -165,8 +172,8 @@ packages: undefsafe@2.0.5: resolution: {integrity: sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==} - ws@8.21.0: - resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} + ws@8.21.1: + resolution: {integrity: sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw==} engines: {node: '>=10.0.0'} peerDependencies: bufferutil: ^4.0.1 @@ -188,7 +195,7 @@ snapshots: binary-extensions@2.3.0: {} - brace-expansion@5.0.7: + brace-expansion@5.0.9: dependencies: balanced-match: 4.0.4 @@ -216,6 +223,8 @@ snapshots: optionalDependencies: supports-color: 5.5.0 + eventsource-parser@3.1.0: {} + fill-range@7.1.1: dependencies: to-regex-range: 5.0.1 @@ -247,7 +256,7 @@ snapshots: minimatch@10.2.5: dependencies: - brace-expansion: 5.0.7 + brace-expansion: 5.0.9 ms@2.1.3: {} @@ -274,7 +283,7 @@ snapshots: dependencies: picomatch: 2.3.2 - sax@1.6.0: {} + sax@1.6.1: {} semver@7.8.5: {} @@ -301,4 +310,4 @@ snapshots: undefsafe@2.0.5: {} - ws@8.21.0: {} + ws@8.21.1: {} diff --git a/backend/pnpm-workspace.yaml b/backend/pnpm-workspace.yaml index e69de29bb2..b3fbd9192b 100644 --- a/backend/pnpm-workspace.yaml +++ b/backend/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +minimumReleaseAgeExclude: + - brace-expansion@5.0.8 || 5.0.9 diff --git a/backend/resources/app/email/invite-to-org/en.html b/backend/resources/app/email/invite-to-organization/en.html similarity index 95% rename from backend/resources/app/email/invite-to-org/en.html rename to backend/resources/app/email/invite-to-organization/en.html index fd5ee679b0..2a23407f4b 100644 --- a/backend/resources/app/email/invite-to-org/en.html +++ b/backend/resources/app/email/invite-to-organization/en.html @@ -219,9 +219,15 @@
"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its - teams and files goes - through your organization's identity provider. If you can't get in, your account probably isn't - in the directory yet. + teams and files now goes through your organization's identity provider. +
+ + + + +
+ If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner.
diff --git a/backend/resources/app/email/invite-to-org/en.subj b/backend/resources/app/email/invite-to-organization/en.subj similarity index 100% rename from backend/resources/app/email/invite-to-org/en.subj rename to backend/resources/app/email/invite-to-organization/en.subj diff --git a/backend/resources/app/email/invite-to-org/en.txt b/backend/resources/app/email/invite-to-organization/en.txt similarity index 60% rename from backend/resources/app/email/invite-to-org/en.txt rename to backend/resources/app/email/invite-to-organization/en.txt index 4b94fe6331..72c97eead7 100644 --- a/backend/resources/app/email/invite-to-org/en.txt +++ b/backend/resources/app/email/invite-to-organization/en.txt @@ -3,8 +3,10 @@ Hello! {{invited-by|abbreviate:25}} has invited you to join the organization “{{ organization.name|abbreviate:50 }}”. {% if organization.sso-active %} -"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files goes -through your organization's identity provider. If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. +"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files now goes +through your organization's identity provider. + +If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. {% endif %} Accept invitation using this link: diff --git a/backend/resources/app/email/invite-to-team/en.html b/backend/resources/app/email/invite-to-team/en.html index 9035d01a70..02e148a2ec 100644 --- a/backend/resources/app/email/invite-to-team/en.html +++ b/backend/resources/app/email/invite-to-team/en.html @@ -197,10 +197,15 @@
"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to - its - teams and files goes - through your organization's identity provider. If you can't get in, your account probably isn't - in the directory yet. + its teams and files now goes through your organization's identity provider. +
+ + + + +
+ If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner.
@@ -257,4 +262,4 @@ - \ No newline at end of file + diff --git a/backend/resources/app/email/invite-to-team/en.txt b/backend/resources/app/email/invite-to-team/en.txt index 8cdced742a..ecbd5d0be1 100644 --- a/backend/resources/app/email/invite-to-team/en.txt +++ b/backend/resources/app/email/invite-to-team/en.txt @@ -3,8 +3,10 @@ Hello! {{invited-by|abbreviate:25}} has invited you to join the team "{{ team|abbreviate:50 }}"{% if organization %}, part of the organization "{{ organization.name|abbreviate:50 }}"{% endif %}. {% if organization.sso-active %} -"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files goes -through your organization's identity provider. If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. +"{{ organization.name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files now goes +through your organization's identity provider. + +If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. {% endif %} Accept invitation using this link: diff --git a/backend/resources/app/email/organization-setup-sso/en.html b/backend/resources/app/email/organization-setup-sso/en.html index cfc72548ad..4d1f3395c6 100644 --- a/backend/resources/app/email/organization-setup-sso/en.html +++ b/backend/resources/app/email/organization-setup-sso/en.html @@ -179,7 +179,7 @@
- Hi{% if user-name %} {{ user-name|abbreviate:25 }}{% endif %}, + Hi,
@@ -188,8 +188,16 @@
"{{ organization-name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its - teams and files goes through your organization's identity provider. If you can't get in, your - account probably isn't in the directory yet. To get access, contact the organization owner. + teams and files now goes through your organization's identity provider. +
+ + + + +
+ If you can't get in, your account probably isn't in the directory yet. To get access, contact the + organization owner.
diff --git a/backend/resources/app/email/organization-setup-sso/en.subj b/backend/resources/app/email/organization-setup-sso/en.subj index e8e3e42f39..1a34f020f6 100644 --- a/backend/resources/app/email/organization-setup-sso/en.subj +++ b/backend/resources/app/email/organization-setup-sso/en.subj @@ -1 +1 @@ -“{{ organization-name|abbreviate:25 }}” has set up single sign-on (SSO) in Penpot +“{{ organization-name|abbreviate:25 }}” uses single sign-on diff --git a/backend/resources/app/email/organization-setup-sso/en.txt b/backend/resources/app/email/organization-setup-sso/en.txt index 4521da3160..976809e451 100644 --- a/backend/resources/app/email/organization-setup-sso/en.txt +++ b/backend/resources/app/email/organization-setup-sso/en.txt @@ -1,7 +1,8 @@ -Hello! +Hi, -"{{ organization-name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files goes -through your organization's identity provider. If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. +"{{ organization-name|abbreviate:50 }}" has set up single sign-on (SSO) in Penpot. Access to its teams and files now goes +through your organization's identity provider. +If you can't get in, your account probably isn't in the directory yet. To get access, contact the organization owner. The Penpot team. diff --git a/backend/resources/app/templates/error-list.tmpl b/backend/resources/app/templates/error-list.tmpl index 043a29034e..2f6f9da735 100644 --- a/backend/resources/app/templates/error-list.tmpl +++ b/backend/resources/app/templates/error-list.tmpl @@ -10,9 +10,10 @@ penpot - error list [BACK]

Error reports (last 300)

- [BACKEND ERRORS] - [FRONTEND ERRORS] - [RLIMIT REPORTS] + [ALL ERRORS] + [BACKEND ERRORS] + [FRONTEND ERRORS] + [RLIMIT REPORTS]
diff --git a/backend/resources/app/templates/error-report.v3.tmpl b/backend/resources/app/templates/error-report.v3.tmpl index a3eddfaa86..63efeba506 100644 --- a/backend/resources/app/templates/error-report.v3.tmpl +++ b/backend/resources/app/templates/error-report.v3.tmpl @@ -6,7 +6,7 @@ Report: {{hint|abbreviate:150}} - {{id}} - Penpot Error Report (v3) {% block content %}