From 04b2e0d81950e83cd55b88278c48b311866ab040 Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Tue, 24 Nov 2026 09:53:46 +0100 Subject: [PATCH 1/6] Revert ":bug: Upload large imports from the kept File on the main thread (#13183)" This reverts commit 8239bd36522774d68b1d26447de8c01b92c7ca2e. --- frontend/src/app/main/data/imports.cljs | 124 ------------------ .../src/app/main/ui/dashboard/import.cljs | 51 +++---- .../src/app/main/ui/onboarding/templates.cljs | 4 +- frontend/src/app/worker/import.cljs | 103 +++++++++++++++ .../frontend_tests/data/imports_test.cljs | 76 ----------- frontend/test/frontend_tests/runner.cljs | 2 - 6 files changed, 124 insertions(+), 236 deletions(-) delete mode 100644 frontend/src/app/main/data/imports.cljs delete mode 100644 frontend/test/frontend_tests/data/imports_test.cljs diff --git a/frontend/src/app/main/data/imports.cljs b/frontend/src/app/main/data/imports.cljs deleted file mode 100644 index cbfac91143..0000000000 --- a/frontend/src/app/main/data/imports.cljs +++ /dev/null @@ -1,124 +0,0 @@ -;; This Source Code Form is subject to the terms of the Mozilla Public -;; License, v. 2.0. If a copy of the MPL was not distributed with this -;; file, You can obtain one at http://mozilla.org/MPL/2.0/. -;; -;; Copyright (c) KALEIDOS SUBSIDIARY SL - -(ns app.main.data.imports - "Upload and import-binfile on the main thread from the dropped File." - (:require - [app.common.logging :as log] - [app.main.data.uploads :as uploads] - [app.main.repo :as rp] - [app.util.i18n :as i18n :refer [tr]] - [app.util.sse :as sse] - [beicon.v2.core :as rx] - [cuerdas.core :as str])) - -(log/set-level! :warn) - -(defn- import-cause-message - [cause default-msg] - (let [data (ex-data cause) - hint (some-> data :hint str/trim) - explain (some-> data :explain str/trim)] - (cond - (not (str/blank? hint)) hint - (not (str/blank? explain)) explain - :else - (let [msg (some-> (ex-message cause) str/trim)] - (if (or (str/blank? msg) (= msg "stream exception")) - default-msg - msg))))) - -(defn- import-blob - [blob {:keys [name version project-id]}] - (->> (uploads/upload-blob-chunked blob) - (rx/mapcat - (fn [{:keys [session-id]}] - (rp/cmd! ::sse/import-binfile - {:name name - :upload-id session-id - :version version - :project-id project-id}))) - (rx/tap (fn [event] - (let [payload (sse/get-payload event) - type (sse/get-type event)] - (if (= type "progress") - (log/dbg :hint "import-binfile: progress" - :section (:section payload) - :name (:name payload)) - (log/dbg :hint "import-binfile: end"))))) - (rx/filter sse/end-of-stream?))) - -(defn- entry-blob - [entry] - (or (:blob entry) - (throw (ex-info "import entry is missing the dropped file" - {:type :internal - :code :missing-import-blob - :uri (:uri entry) - :name (:name entry)})))) - -(defn import-files - "Upload and import analyzed entries. Emits per-file `:finish`/`:error`, - then `{:libraries-resolution …}`." - [{:keys [project-id files]}] - (let [binfile-v1 (filter #(= :binfile-v1 (:type %)) files) - binfile-v3 (filter #(= :binfile-v3 (:type %)) files) - resolutions (volatile! {})] - - (rx/merge - (->> (rx/from binfile-v1) - (rx/merge-map - (fn [data] - (->> (import-blob (entry-blob data) - {:name (str/replace (:name data) #".penpot$" "") - :version 1 - :project-id project-id}) - (rx/map (fn [_] - {:status :finish - :file-id (:file-id data)})) - (rx/catch - (fn [cause] - (log/error :hint "unexpected error on import process" - :project-id project-id - :cause cause) - (rx/of {:status :error - :error (import-cause-message cause (tr "labels.error")) - :file-id (:file-id data)}))))))) - - (rx/concat - (->> (rx/from binfile-v3) - (rx/reduce (fn [result file] - (update result (:uri file) (fnil conj []) file)) - {}) - (rx/mapcat identity) - (rx/merge-map - (fn [[_uri entries]] - (->> (import-blob (entry-blob (first entries)) - {:name (-> entries first :name) - :version 3 - :project-id project-id}) - (rx/mapcat (fn [message] - (let [{:keys [resolution]} (sse/get-payload message)] - (when (seq resolution) - (vswap! resolutions merge resolution)) - (->> (rx/from entries) - (rx/map (fn [entry] - {:status :finish - :file-id (:file-id entry)})))))) - (rx/catch (fn [cause] - (log/error :hint "import-binfile: unexpected error on importing" - :project-id project-id - ::log/sync? true - :cause cause) - (let [err (import-cause-message cause (tr "labels.error"))] - (->> (rx/from entries) - (rx/map (fn [entry] - {:status :error - :error err - :file-id (:file-id entry)})))))))))) - (->> (rx/defer #(rx/of @resolutions)) - (rx/map (fn [resolutions] - {:libraries-resolution resolutions}))))))) diff --git a/frontend/src/app/main/ui/dashboard/import.cljs b/frontend/src/app/main/ui/dashboard/import.cljs index ea6c2f4ba7..dd459da077 100644 --- a/frontend/src/app/main/ui/dashboard/import.cljs +++ b/frontend/src/app/main/ui/dashboard/import.cljs @@ -13,7 +13,6 @@ [app.common.logging :as log] [app.main.data.dashboard :as dd] [app.main.data.event :as ev] - [app.main.data.imports :as imports] [app.main.data.modal :as modal] [app.main.data.notifications :as ntf] [app.main.repo :as rp] @@ -51,8 +50,7 @@ (let [entries (->> entries (mapv (fn [file] {:name (.-name file) - :uri (wapi/create-uri file) - :blob file})) + :uri (wapi/create-uri file)})) (not-empty))] (when entries (st/emit! (modal/show @@ -89,25 +87,13 @@ (assoc :deleted true))) entries)) -(defn- blobs-by-uri - [entries] - (into {} - (keep (fn [{:keys [uri blob]}] - (when (and uri blob) [uri blob]))) - entries)) - (defn- update-with-analyze-result [entries {:keys [file-id status] :as updated}] - ;; Analyze replies have no :blob (transit); copy it back by :uri. - (let [blobs (blobs-by-uri entries) - entries (filterv (comp uuid? :file-id) entries) + (let [entries (filterv (comp uuid? :file-id) entries) status (case status :success :import-ready :error :analyze-error) - updated (-> updated - (assoc :status status) - (cond-> (contains? blobs (:uri updated)) - (assoc :blob (get blobs (:uri updated)))))] + updated (assoc updated :status status)] (if (some #(= file-id (:file-id %)) entries) (mapv (fn [entry] (if (= (:file-id entry) file-id) @@ -194,11 +180,10 @@ (defn- analyze-entries [state entries] - (let [features (get @st/state :features) - files (mapv #(dissoc % :blob) entries)] + (let [features (get @st/state :features)] (->> (mw/ask-many! {:cmd :analyze-import - :files files + :files entries :features features}) (rx/mapcat #(rx/delay emit-delay (rx/of %))) (rx/filter some?) @@ -214,17 +199,21 @@ (st/emit! (ev/event {::ev/name "import-files" :num-files (count entries)})) - (->> (imports/import-files {:project-id project-id - :files entries}) - (rx/filter some?) - (rx/subs! - (fn [message] - ;; Capture library-resolution data if present (same for all - ;; entries from the same zip, so first one wins) - (if-let [resolution (-> (:libraries-resolution message) - (not-empty))] - (reset! library-resolution-data* resolution) - (swap! state update-entry-status message)))))) + (let [features (get @st/state :features)] + (->> (mw/ask-many! + {:cmd :import-files + :project-id project-id + :files entries + :features features}) + (rx/filter some?) + (rx/subs! + (fn [message] + ;; Capture library-resolution data if present (same for all + ;; entries from the same zip, so first one wins) + (if-let [resolution (-> (:libraries-resolution message) + (not-empty))] + (reset! library-resolution-data* resolution) + (swap! state update-entry-status message))))))) (mf/defc import-entry* {::mf/memo true diff --git a/frontend/src/app/main/ui/onboarding/templates.cljs b/frontend/src/app/main/ui/onboarding/templates.cljs index 77943cda8a..5ef15a2546 100644 --- a/frontend/src/app/main/ui/onboarding/templates.cljs +++ b/frontend/src/app/main/ui/onboarding/templates.cljs @@ -40,9 +40,7 @@ (reset! downloading? true) (->> (http/send! {:method :get :uri link :response-type :blob :mode :no-cors}) (rx/subs! (fn [{:keys [body] :as response}] - (open-import-modal {:name name - :uri (wapi/create-uri body) - :blob body})) + (open-import-modal {:name name :uri (wapi/create-uri body)})) (fn [error] (reset! downloading? false) (js/console.error "error" error)) diff --git a/frontend/src/app/worker/import.cljs b/frontend/src/app/worker/import.cljs index 389c0a16f2..e8310efa89 100644 --- a/frontend/src/app/worker/import.cljs +++ b/frontend/src/app/worker/import.cljs @@ -12,8 +12,11 @@ [app.common.logging :as log] [app.common.schema :as sm] [app.common.uuid :as uuid] + [app.main.data.uploads :as uploads] + [app.main.repo :as rp] [app.util.http :as http] [app.util.i18n :as i18n :refer [tr]] + [app.util.sse :as sse] [app.util.zip :as uz] [app.worker.impl :as impl] [beicon.v2.core :as rx] @@ -148,3 +151,103 @@ [{:keys [files]}] (->> (rx/from files) (rx/merge-map analyze-file))) + +(defn- import-blob-via-upload + "Fetches `uri` as a Blob, uploads it using the generic chunked-upload + session API and calls `import-binfile` with the resulting upload-id. + Returns an observable of SSE events from the import stream." + [uri {:keys [name version project-id]}] + (->> (slurp-uri uri :blob) + (rx/mapcat + (fn [blob] + (->> (uploads/upload-blob-chunked blob) + (rx/mapcat + (fn [{:keys [session-id]}] + (rp/cmd! ::sse/import-binfile + {:name name + :upload-id session-id + :version version + :project-id project-id})))))))) + +(defmethod impl/handler :import-files + [{:keys [project-id files]}] + (let [binfile-v1 (filter #(= :binfile-v1 (:type %)) files) + binfile-v3 (filter #(= :binfile-v3 (:type %)) files) + resolutions (volatile! {})] + + (rx/merge + (->> (rx/from binfile-v1) + (rx/merge-map + (fn [data] + (->> (import-blob-via-upload (:uri data) + {:name (str/replace (:name data) #".penpot$" "") + :version 1 + :project-id project-id}) + (rx/tap (fn [event] + (let [payload (sse/get-payload event) + type (sse/get-type event)] + (if (= type "progress") + (log/dbg :hint "import-binfile: progress" + :section (:section payload) + :name (:name payload)) + (log/dbg :hint "import-binfile: end"))))) + (rx/filter sse/end-of-stream?) + (rx/map (fn [_] + {:status :finish + :file-id (:file-id data)})) + (rx/catch + (fn [cause] + (log/error :hint "unexpected error on import process" + :project-id project-id + :cause cause) + (rx/of {:status :error + :error (import-cause-message cause (tr "labels.error")) + :file-id (:file-id data)}))))))) + + + (rx/concat + (->> (rx/from binfile-v3) + (rx/reduce (fn [result file] + (update result (:uri file) (fnil conj []) file)) + {}) + (rx/mapcat identity) + (rx/merge-map + (fn [[uri entries]] + (->> (import-blob-via-upload uri + {:name (-> entries first :name) + :version 3 + :project-id project-id}) + (rx/tap (fn [event] + (let [payload (sse/get-payload event) + type (sse/get-type event)] + (cond + (= type "progress") + (log/dbg :hint "import-binfile: progress" + :section (:section payload) + :name (:name payload)) + + :else + (log/dbg :hint "import-binfile: end"))))) + (rx/filter sse/end-of-stream?) + (rx/mapcat (fn [message] + (let [{:keys [resolution]} (sse/get-payload message)] + (when (seq resolution) + (vswap! resolutions merge resolution)) + (->> (rx/from entries) + (rx/map (fn [entry] + {:status :finish + :file-id (:file-id entry)})))))) + (rx/catch (fn [cause] + (log/error :hint "import-binfile: unexpected error on importing" + :project-id project-id + ::log/sync? true + :cause cause) + (let [err (import-cause-message cause (tr "labels.error"))] + (->> (rx/from entries) + (rx/map (fn [entry] + {:status :error + :error err + :file-id (:file-id entry)})))))))))) + (->> (rx/defer #(rx/of @resolutions)) + (rx/map (fn [resolutions] + {:libraries-resolution resolutions}))))))) diff --git a/frontend/test/frontend_tests/data/imports_test.cljs b/frontend/test/frontend_tests/data/imports_test.cljs deleted file mode 100644 index c322ddea5a..0000000000 --- a/frontend/test/frontend_tests/data/imports_test.cljs +++ /dev/null @@ -1,76 +0,0 @@ -;; This Source Code Form is subject to the terms of the Mozilla Public -;; License, v. 2.0. If a copy of the MPL was not distributed with this -;; file, You can obtain one at http://mozilla.org/MPL/2.0/. -;; -;; Copyright (c) KALEIDOS SUBSIDIARY SL - -(ns frontend-tests.data.imports-test - (:require - [app.common.uuid :as uuid] - [app.main.data.imports :as imports] - [app.main.repo :as rp] - [app.util.sse :as sse] - [beicon.v2.core :as rx] - [cljs.test :as t :include-macros true] - [frontend-tests.helpers.async :as hva] - [frontend-tests.helpers.mock :as mock])) - -(defn- make-blob - [size] - (js/Blob. #js [(js/Uint8Array. size)] #js {:type "application/octet-stream"})) - -(t/deftest ^:async import-files-uses-kept-blob - (let [session-id (uuid/next) - file-id (uuid/next) - project-id (uuid/next) - blob (make-blob 30) - uri "blob:https://localhost/test-import" - seen-cmds (atom []) - fetch-uris (atom []) - seen (atom []) - orig-fetch (.-fetch js/globalThis)] - - (set! (.-fetch js/globalThis) - (fn [url _opts] - (swap! fetch-uris conj (str url)) - (js/Promise.reject (js/Error. "fetch must not run for import")))) - - (await - (mock/with-mocks* - {rp/cmd! - (mock/stub - (fn [cmd params] - (swap! seen-cmds conj [cmd (dissoc params :content)]) - (cond - (= cmd :create-upload-session) - (rx/of {:session-id session-id}) - - (= cmd :upload-chunk) - (rx/of {:session-id session-id :index (:index params)}) - - (= cmd ::sse/import-binfile) - (rx/of #js {:type "end" :data {:resolution {}}}) - - :else - (rx/throw (ex-info "unexpected cmd" {:cmd cmd})))))} - - (await - (hva/observe - (imports/import-files - {:project-id project-id - :files [{:type :binfile-v3 - :uri uri - :blob blob - :name "Package" - :file-id file-id}]}) - {:on-next #(swap! seen conj %)})))) - - (set! (.-fetch js/globalThis) orig-fetch) - - (t/is (= [:create-upload-session :upload-chunk ::sse/import-binfile] - (mapv first @seen-cmds))) - (t/is (= session-id (-> @seen-cmds (nth 2) second :upload-id))) - (t/is (= [{:status :finish :file-id file-id} - {:libraries-resolution {}}] - @seen)) - (t/is (empty? @fetch-uris)))) diff --git a/frontend/test/frontend_tests/runner.cljs b/frontend/test/frontend_tests/runner.cljs index ca8bf3586e..3bea068a6b 100644 --- a/frontend/test/frontend_tests/runner.cljs +++ b/frontend/test/frontend_tests/runner.cljs @@ -17,7 +17,6 @@ [frontend-tests.data.exports-assets-test] [frontend-tests.data.exports-files-test] [frontend-tests.data.fix-deleted-fonts-test] - [frontend-tests.data.imports-test] [frontend-tests.data.modal-test] [frontend-tests.data.nitrate-test] [frontend-tests.data.persistence-retry-test] @@ -184,7 +183,6 @@ 'frontend-tests.data.exports-files-test 'frontend-tests.data.svg-upload-test 'frontend-tests.data.team-test - 'frontend-tests.data.imports-test 'frontend-tests.data.uploads-test 'frontend-tests.data.viewer-test 'frontend-tests.data.workspace-colors-test From eaac3f58c42a56943c9e8e2ed4aedf580d4542dd Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Tue, 24 Nov 2026 09:55:26 +0100 Subject: [PATCH 2/6] :paperclip: Update changelog --- CHANGES.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 5d0b4cb3aa..f25f6ab38f 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,11 @@ # CHANGELOG +## 2.19.5 + +### :bug: Bugs fixed + +- Revert [#13165](https://github.com/penpot/penpot/issues/13165), because it causes more regression, the issue is already correctly fixed on the upcoming 2.20.0 + ## 2.19.4 ### :bug: Bugs fixed From 35278f391719cccfd94837874460410a8bc82dfd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bel=C3=A9n=20Albeza?= Date: Fri, 13 Nov 2026 09:39:43 +0100 Subject: [PATCH 3/6] :bug: Restore the WASM stack pointer after a failed call (#12978) A failed render-wasm call traps without popping its shadow-stack frames. Each failure leaked stack until it overwrote static data, and from then on every call trapped as wasm-critical. h/call now saves the stack pointer before the call and restores it on failure. Closes #12977 Related to #12906 AI-assisted-by: claude-opus-5-5 --- .../src/app/common/render_wasm/helpers.cljc | 43 ++++++++----- .../frontend_tests/render_wasm/call_test.cljs | 62 +++++++++++++++++++ frontend/test/frontend_tests/runner.cljs | 2 + render-wasm/_build_env | 2 +- 4 files changed, 91 insertions(+), 18 deletions(-) create mode 100644 frontend/test/frontend_tests/render_wasm/call_test.cljs diff --git a/common/src/app/common/render_wasm/helpers.cljc b/common/src/app/common/render_wasm/helpers.cljc index 3657ccb026..64ee812a7a 100644 --- a/common/src/app/common/render_wasm/helpers.cljc +++ b/common/src/app/common/render_wasm/helpers.cljc @@ -5,31 +5,40 @@ ;; Copyright (c) KALEIDOS SUBSIDIARY SL (ns app.common.render-wasm.helpers - #?(:cljs (:require-macros [app.common.render-wasm.helpers])) - (:require [app.common.data :as d])) + #?(:cljs (:require-macros [app.common.render-wasm.helpers]))) (def error-code "WASM error code constants (must match render-wasm/src/error.rs and mem.rs)." {0x01 :non-blocking 0x02 :panic}) +#?(:cljs + (defn on-call-error + "Restores the stack pointer after a failed WASM call and throws the + classified error." + [module fn-name stack cause] + (when (some? stack) + ((unchecked-get module "stackRestore") stack)) + (let [read-code-fn (unchecked-get module "_read_error_code") + code-num (when read-code-fn (read-code-fn)) + code (get error-code code-num :wasm-critical) + hint (str "WASM Error (" (name code) ")")] + (throw (ex-info hint {:type :wasm-error :code code :hint hint :fn fn-name} cause))))) + (defmacro call "Calls the WASM function `name`. On failure, throws a `:wasm-error` whose - `:code` comes from `error-code`, or `:wasm-critical` when WASM set none." + `:code` comes from `error-code`, or `:wasm-critical` when WASM set none. + Restores the stack pointer on failure, since a trap leaves its shadow-stack + frames behind." [module name & params] - (let [fn-sym (with-meta (gensym "fn-") {:tag 'function}) - cause-sym (gensym "cause")] - `(let [~fn-sym (cljs.core/unchecked-get ~module ~name)] + (let [fn-sym (with-meta (gensym "fn-") {:tag 'function}) + module-sym (gensym "module") + stack-sym (gensym "stack")] + `(let [~module-sym ~module + ~fn-sym (cljs.core/unchecked-get ~module-sym ~name) + save-fn# (cljs.core/unchecked-get ~module-sym "stackSave") + ~stack-sym (when save-fn# (save-fn#))] (try (~fn-sym ~@params) - (catch :default ~cause-sym - (let [read-code-fn# (cljs.core/unchecked-get ~module "_read_error_code") - code-num# (when read-code-fn# (read-code-fn#)) - code# (get error-code code-num# :wasm-critical) - hint# (str "WASM Error (" (d/name code#) ")") - context# {:type :wasm-error - :code code# - :hint hint# - :fn ~name} - cause# (ex-info hint# context# ~cause-sym)] - (throw cause#))))))) + (catch :default cause# + (on-call-error ~module-sym ~name ~stack-sym cause#)))))) diff --git a/frontend/test/frontend_tests/render_wasm/call_test.cljs b/frontend/test/frontend_tests/render_wasm/call_test.cljs new file mode 100644 index 0000000000..17d4331519 --- /dev/null +++ b/frontend/test/frontend_tests/render_wasm/call_test.cljs @@ -0,0 +1,62 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS SUBSIDIARY SL + +(ns frontend-tests.render-wasm.call-test + "Unit tests for the `app.common.render-wasm.helpers/call` macro." + (:require + [app.common.render-wasm.helpers :as h] + [cljs.test :as t :include-macros true])) + +(defn- fake-module + "Module whose `_fail` export throws like a WASM trap after moving the + shadow stack pointer down 64 bytes, leaking the frame as a trap does." + [error-code] + (let [sp (atom 1000) + restored (atom [])] + {:sp sp + :restored restored + :module #js {"stackSave" (fn [] @sp) + "stackRestore" (fn [v] + (swap! restored conj v) + (reset! sp v)) + "_read_error_code" (fn [] error-code) + "_ok" (fn [x] (* 2 x)) + "_fail" (fn [] + (swap! sp - 64) + (throw (js/Error. "unreachable")))}})) + +(t/deftest failed-call-restores-stack-pointer + (let [{:keys [module sp restored]} (fake-module 0x02)] + (dotimes [_ 3] + (t/is (thrown? js/Error (h/call module "_fail")))) + (t/is (= 1000 @sp)) + (t/is (= [1000 1000 1000] @restored)))) + +(t/deftest failed-call-keeps-error-classification + (let [{:keys [module]} (fake-module 0x01) + data (try + (h/call module "_fail") + nil + (catch :default cause + (ex-data cause)))] + (t/is (= :wasm-error (:type data))) + (t/is (= :non-blocking (:code data))) + (t/is (= "_fail" (:fn data))))) + +(t/deftest successful-call-does-not-restore + (let [{:keys [module restored]} (fake-module 0)] + (t/is (= 42 (h/call module "_ok" 21))) + (t/is (empty? @restored)))) + +(t/deftest module-without-stack-methods-still-reports-errors + (let [module #js {"_read_error_code" (fn [] 0x02) + "_fail" (fn [] (throw (js/Error. "unreachable")))} + data (try + (h/call module "_fail") + nil + (catch :default cause + (ex-data cause)))] + (t/is (= :panic (:code data))))) diff --git a/frontend/test/frontend_tests/runner.cljs b/frontend/test/frontend_tests/runner.cljs index 465fa50050..82ba79e6b1 100644 --- a/frontend/test/frontend_tests/runner.cljs +++ b/frontend/test/frontend_tests/runner.cljs @@ -117,6 +117,7 @@ [frontend-tests.plugins.value-objects-test] [frontend-tests.plugins.wait-for-save-test] [frontend-tests.render-dimensions-test] + [frontend-tests.render-wasm.call-test] [frontend-tests.render-wasm.fonts-test] [frontend-tests.render-wasm.process-objects-test] [frontend-tests.render-wasm.serialization-test] @@ -331,6 +332,7 @@ 'frontend-tests.plugins.utils-test 'frontend-tests.plugins.value-objects-test 'frontend-tests.plugins.wait-for-save-test + 'frontend-tests.render-wasm.call-test 'frontend-tests.render-wasm.fonts-test 'frontend-tests.render-wasm.process-objects-test 'frontend-tests.render-wasm.serialization-test diff --git a/render-wasm/_build_env b/render-wasm/_build_env index c8d1fdd1e5..6dcd24b860 100644 --- a/render-wasm/_build_env +++ b/render-wasm/_build_env @@ -67,7 +67,7 @@ export EMCC_CFLAGS="--no-entry \ -sERROR_ON_UNDEFINED_SYMBOLS=0 \ -sMAX_WEBGL_VERSION=2 \ -sEXPORT_NAME=createRustSkiaModule \ - -sEXPORTED_RUNTIME_METHODS=GL,UTF8ToString,stringToUTF8,HEAPU8,HEAP32,HEAPU32,HEAPF32 \ + -sEXPORTED_RUNTIME_METHODS=GL,UTF8ToString,stringToUTF8,HEAPU8,HEAP32,HEAPU32,HEAPF32,stackSave,stackRestore \ -sENVIRONMENT=web,worker,node \ -sMODULARIZE=1 \ -sFILESYSTEM=0 \ From f807e749dbf986bfcbbc5e590ab3fe73f7f0a76a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bel=C3=A9n=20Albeza?= Date: Wed, 18 Nov 2026 12:29:38 +0100 Subject: [PATCH 4/6] :bug: Fix render-wasm panic when an auto layout has only absolute children An auto flex or grid layout whose children were all absolute shrank to zero, and a rotated shape below it got a matrix that cannot be inverted, which panicked in `_propagate_modifiers`. Skip auto-size when there is no content, as CLJS does. A matrix that still cannot be inverted is now a recoverable error, which shows a toast instead of the error page. Closes #12763 AI-assisted-by: claude-opus-5-5 --- render-wasm/src/shapes/modifiers.rs | 224 ++++++++++++++++++ render-wasm/src/shapes/modifiers/common.rs | 10 + .../src/shapes/modifiers/constraints.rs | 2 +- .../src/shapes/modifiers/flex_layout.rs | 10 +- .../src/shapes/modifiers/grid_layout.rs | 10 +- 5 files changed, 249 insertions(+), 7 deletions(-) diff --git a/render-wasm/src/shapes/modifiers.rs b/render-wasm/src/shapes/modifiers.rs index b79d811459..c46cce21a9 100644 --- a/render-wasm/src/shapes/modifiers.rs +++ b/render-wasm/src/shapes/modifiers.rs @@ -1039,4 +1039,228 @@ mod tests { assert!(is_close_to(bounds.min_x(), 0.0)); } + + #[derive(Clone, Copy)] + enum TestLayout { + None, + Flex, + Grid, + } + + #[derive(Clone, Copy, PartialEq)] + enum Child { + InFlow, + Absolute, + Hidden, + } + + /// Adds a shape with no gaps or padding: auto-sized at the root, fixed below. + fn add_shape( + state: &mut State, + parent: Option, + (left, top, right, bottom): (f32, f32, f32, f32), + layout: TestLayout, + ) -> Uuid { + let id = Uuid::new_v4(); + let sizing = if parent.is_some() { + Sizing::Fix + } else { + Sizing::Auto + }; + let shape = state.shapes.add_shape(id); + if !matches!(layout, TestLayout::None) { + shape.set_shape_type(Type::Frame(Frame::default())); + } + let (align, justify) = (AlignItems::Start, JustifyContent::Start); + let (content, items) = (AlignContent::Start, JustifyItems::Start); + match layout { + TestLayout::Flex => shape.set_flex_layout_data( + FlexDirection::Row, + 0.0, + 0.0, + align, + content, + items, + justify, + WrapType::NoWrap, + 0.0, + 0.0, + 0.0, + 0.0, + ), + TestLayout::Grid => shape.set_grid_layout_data( + GridDirection::Row, + 0.0, + 0.0, + align, + content, + items, + justify, + 0.0, + 0.0, + 0.0, + 0.0, + ), + TestLayout::None => {} + } + shape.set_selrect(left, top, right, bottom); + shape.set_flex_layout_child_data( + 0.0, 0.0, 0.0, 0.0, sizing, sizing, None, None, None, None, None, false, None, + ); + if let Some(parent) = parent { + shape.set_parent(parent); + state.shapes.get_mut(&parent).unwrap().add_child(id); + } + id + } + + fn shape_mut(state: &mut State, id: Uuid) -> &mut Shape { + state.shapes.get_mut(&id).unwrap() + } + + fn set_absolute(state: &mut State, id: Uuid) { + shape_mut(state, id) + .layout_item + .as_mut() + .unwrap() + .is_absolute = true; + } + + fn rotate(state: &mut State, id: Uuid, degrees: f32) { + let (sin, cos) = degrees.to_radians().sin_cos(); + let shape = shape_mut(state, id); + shape.set_rotation(degrees); + shape.set_transform(cos, sin, -sin, cos, 0.0, 0.0); + } + + /// Reflows every layout above `id`, as a committed text resize does. + fn reflow(state: &State, id: Uuid) -> Vec { + let entry = TransformEntry::from_input(id, Matrix::default()); + propagate_modifiers(state, &[entry], PixelPrecision::Disabled).unwrap() + } + + fn size_after(state: &State, result: &[TransformEntry], id: Uuid) -> (f32, f32) { + let mut bounds = state.shapes.get_raw(&id).unwrap().bounds(); + if let Some(entry) = result.iter().find(|e| e.id == id) { + bounds = bounds.transform(&entry.transform); + } + (bounds.width(), bounds.height()) + } + + fn assert_size((width, height): (f32, f32), (expected_w, expected_h): (f32, f32)) { + assert!( + is_close_to(width, expected_w) && is_close_to(height, expected_h), + "got {width}x{height}, expected {expected_w}x{expected_h}" + ); + } + + #[test] + fn test_rotated_shape_under_absolute_child_of_auto_flex_does_not_collapse() { + // Tree from #12763: auto flex > absolute frame > rotated flex row > leaf. + for absolute_layout in [TestLayout::Flex, TestLayout::Grid] { + let mut state = State::new(); + state.shapes.initialize(10); + let root = (-1545.0, -72.0, 232.0, 824.0); + let auto = add_shape(&mut state, None, root, TestLayout::Flex); + let frame = (-1399.0, 9.0, 72.75, 763.0); + let absolute = add_shape(&mut state, Some(auto), frame, absolute_layout); + set_absolute(&mut state, absolute); + let row = (-1379.0, 29.0, -1043.0, 83.0); + let row = add_shape(&mut state, Some(absolute), row, TestLayout::Flex); + let leaf = (-1365.0, 47.0, -1335.0, 64.0); + let leaf = add_shape(&mut state, Some(row), leaf, TestLayout::None); + rotate(&mut state, row, 0.0915); + rotate(&mut state, leaf, 0.0915); + + let result = reflow(&state, leaf); + + for entry in &result { + let (width, height) = size_after(&state, &result, entry.id); + assert!(width > 1.0 && height > 1.0, "{} collapsed", entry.id); + } + } + } + + #[test] + fn test_collapsing_a_rotated_frame_is_a_recoverable_error() { + let mut state = State::new(); + state.shapes.initialize(10); + let frame = (0.0, 0.0, 300.0, 100.0); + let frame = add_shape(&mut state, None, frame, TestLayout::Flex); + let child = add_shape( + &mut state, + Some(frame), + (10.0, 10.0, 50.0, 50.0), + TestLayout::None, + ); + set_absolute(&mut state, child); + rotate(&mut state, frame, 0.0915); + + // Squash the frame to zero width: its rotated corners end on one line. + let entry = TransformEntry::from_input(frame, Matrix::scale((0.0, 1.0))); + let result = propagate_modifiers(&state, &[entry], PixelPrecision::Disabled); + + assert!(matches!( + result, + Err(crate::error::Error::RecoverableError(_)) + )); + } + + /// Size of an auto-size 500x300 frame with one 100x50 child, after reflow. + /// Grids get two fixed 100px columns and one fixed 50px row. + fn auto_frame_size(layout: TestLayout, child: Child) -> (f32, f32) { + let mut state = State::new(); + state.shapes.initialize(10); + let frame = add_shape(&mut state, None, (0.0, 0.0, 500.0, 300.0), layout); + let rect = (10.0, 10.0, 110.0, 60.0); + let child_id = add_shape(&mut state, Some(frame), rect, TestLayout::None); + match child { + Child::Absolute => set_absolute(&mut state, child_id), + Child::Hidden => shape_mut(&mut state, child_id).set_hidden(true), + Child::InFlow => {} + } + if matches!(layout, TestLayout::Grid) { + let column = GridTrack { + track_type: GridTrackType::Fixed, + value: 100.0, + }; + let row = GridTrack { + track_type: GridTrackType::Fixed, + value: 50.0, + }; + let shape = shape_mut(&mut state, frame); + shape.set_grid_columns(vec![column.clone(), column]); + shape.set_grid_rows(vec![row]); + if child != Child::Absolute { + shape.set_grid_cells(vec![GridCell { + row: 1, + row_span: 1, + column: 1, + column_span: 1, + align_self: None, + justify_self: None, + shape: Some(child_id), + }]); + } + } + let result = reflow(&state, frame); + size_after(&state, &result, frame) + } + + #[test] + fn test_auto_flex_size_by_child_kind() { + use Child::*; + assert_size(auto_frame_size(TestLayout::Flex, InFlow), (100.0, 50.0)); + assert_size(auto_frame_size(TestLayout::Flex, Absolute), (500.0, 300.0)); + // Known difference from CLJS, which sizes the frame to hidden children. + assert_size(auto_frame_size(TestLayout::Flex, Hidden), (500.0, 300.0)); + } + + #[test] + fn test_auto_grid_size_by_child_kind() { + use Child::*; + assert_size(auto_frame_size(TestLayout::Grid, InFlow), (200.0, 50.0)); + assert_size(auto_frame_size(TestLayout::Grid, Absolute), (500.0, 300.0)); + assert_size(auto_frame_size(TestLayout::Grid, Hidden), (500.0, 300.0)); + } } diff --git a/render-wasm/src/shapes/modifiers/common.rs b/render-wasm/src/shapes/modifiers/common.rs index 475e8812f7..b622b94672 100644 --- a/render-wasm/src/shapes/modifiers/common.rs +++ b/render-wasm/src/shapes/modifiers/common.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use crate::math::Bounds; use crate::shapes::Shape; +use crate::state::ShapesPoolRef; use crate::uuid::Uuid; pub trait GetBounds { @@ -13,3 +14,12 @@ impl GetBounds for HashMap { self.get(&shape.id).copied().unwrap_or(shape.bounds()) } } + +/// Whether a layout has a child that takes part in the flow (neither absolute +/// nor hidden). Without one there is no content to auto-size the layout to. +pub fn has_in_flow_children(shape: &Shape, shapes: ShapesPoolRef) -> bool { + shape + .children_ids_iter(true) + .filter_map(|id| shapes.get(id)) + .any(|child| !child.is_absolute() && !child.hidden()) +} diff --git a/render-wasm/src/shapes/modifiers/constraints.rs b/render-wasm/src/shapes/modifiers/constraints.rs index 4f5a9cb228..6b625a0029 100644 --- a/render-wasm/src/shapes/modifiers/constraints.rs +++ b/render-wasm/src/shapes/modifiers/constraints.rs @@ -134,7 +134,7 @@ pub fn propagate_shape_constraints( parent_transform.post_translate(center); parent_transform.pre_translate(-center); - let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError( + let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError( "Failed to invert parent transform".to_string(), ))?; let origin = parent_transform_inv.map_point(child_bounds_after.nw); diff --git a/render-wasm/src/shapes/modifiers/flex_layout.rs b/render-wasm/src/shapes/modifiers/flex_layout.rs index 5bdd64e488..af0862e785 100644 --- a/render-wasm/src/shapes/modifiers/flex_layout.rs +++ b/render-wasm/src/shapes/modifiers/flex_layout.rs @@ -9,7 +9,7 @@ use crate::uuid::Uuid; use std::collections::{HashMap, VecDeque}; -use super::common::GetBounds; +use super::common::{has_in_flow_children, GetBounds}; const MIN_SIZE: f32 = 0.01; const MAX_SIZE: f32 = f32::INFINITY; @@ -686,7 +686,11 @@ pub fn reflow_flex_layout( } } - if layout_axis.is_auto_across || layout_axis.is_auto_main { + // Like the CLJS layout, keep the size when there is no content to fit: + // auto-sizing to padding only would collapse the frame. + if (layout_axis.is_auto_across || layout_axis.is_auto_main) + && has_in_flow_children(shape, shapes) + { let width = layout_bounds.width(); let height = layout_bounds.height(); @@ -749,7 +753,7 @@ pub fn reflow_flex_layout( let parent_transform = layout_bounds.transform_matrix().unwrap_or_default(); - let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError( + let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError( "Failed to invert parent transform".to_string(), ))?; let origin = parent_transform_inv.map_point(layout_bounds.nw); diff --git a/render-wasm/src/shapes/modifiers/grid_layout.rs b/render-wasm/src/shapes/modifiers/grid_layout.rs index e28c6dbb46..62d8604e24 100644 --- a/render-wasm/src/shapes/modifiers/grid_layout.rs +++ b/render-wasm/src/shapes/modifiers/grid_layout.rs @@ -10,7 +10,7 @@ use crate::uuid::Uuid; use std::collections::{HashMap, HashSet, VecDeque}; -use super::common::GetBounds; +use super::common::{has_in_flow_children, GetBounds}; const MIN_SIZE: f32 = 0.01; const MAX_SIZE: f32 = f32::INFINITY; @@ -890,7 +890,11 @@ pub fn reflow_grid_layout( } } - if shape.is_layout_horizontal_auto() || shape.is_layout_vertical_auto() { + // Like the CLJS layout, keep the size when there is no content to fit: + // auto-sizing to empty tracks would collapse the frame. + if (shape.is_layout_horizontal_auto() || shape.is_layout_vertical_auto()) + && has_in_flow_children(shape, shapes) + { let width = layout_bounds.width(); let height = layout_bounds.height(); @@ -915,7 +919,7 @@ pub fn reflow_grid_layout( let parent_transform = layout_bounds.transform_matrix().unwrap_or_default(); - let parent_transform_inv = &parent_transform.invert().ok_or(Error::CriticalError( + let parent_transform_inv = &parent_transform.invert().ok_or(Error::RecoverableError( "Failed to invert parent transform".to_string(), ))?; let origin = parent_transform_inv.map_point(layout_bounds.nw); From 76adaf86b13b0b3f32d88a01e0d913f4aee8036b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bel=C3=A9n=20Albeza?= Date: Wed, 18 Nov 2026 12:55:02 +0100 Subject: [PATCH 5/6] :bug: Count hidden children in render-wasm grid auto-size A grid takes its size from its tracks, so, like CLJS, it skips auto-size only when every child is absolute. Flex still skips hidden children, since its line building leaves them out. Refs #12763 AI-assisted-by: claude-opus-5-5 --- render-wasm/src/shapes.rs | 5 +++++ render-wasm/src/shapes/modifiers.rs | 3 ++- render-wasm/src/shapes/modifiers/common.rs | 14 +++++++++++--- render-wasm/src/shapes/modifiers/flex_layout.rs | 6 +++--- render-wasm/src/shapes/modifiers/grid_layout.rs | 8 ++++---- 5 files changed, 25 insertions(+), 11 deletions(-) diff --git a/render-wasm/src/shapes.rs b/render-wasm/src/shapes.rs index c8d218dd9b..97703096ef 100644 --- a/render-wasm/src/shapes.rs +++ b/render-wasm/src/shapes.rs @@ -1785,6 +1785,11 @@ impl Shape { } } + /// Whether flex layout places this shape: neither absolute nor hidden. + pub fn is_in_flow(&self) -> bool { + !self.is_absolute() && !self.hidden() + } + pub fn z_index(&self) -> i32 { match &self.layout_item { Some(LayoutItem { diff --git a/render-wasm/src/shapes/modifiers.rs b/render-wasm/src/shapes/modifiers.rs index c46cce21a9..52e8c488cb 100644 --- a/render-wasm/src/shapes/modifiers.rs +++ b/render-wasm/src/shapes/modifiers.rs @@ -1261,6 +1261,7 @@ mod tests { use Child::*; assert_size(auto_frame_size(TestLayout::Grid, InFlow), (200.0, 50.0)); assert_size(auto_frame_size(TestLayout::Grid, Absolute), (500.0, 300.0)); - assert_size(auto_frame_size(TestLayout::Grid, Hidden), (500.0, 300.0)); + // Grid takes its size from its tracks; hidden children still count. + assert_size(auto_frame_size(TestLayout::Grid, Hidden), (200.0, 50.0)); } } diff --git a/render-wasm/src/shapes/modifiers/common.rs b/render-wasm/src/shapes/modifiers/common.rs index b622b94672..fa12ec5e20 100644 --- a/render-wasm/src/shapes/modifiers/common.rs +++ b/render-wasm/src/shapes/modifiers/common.rs @@ -15,11 +15,19 @@ impl GetBounds for HashMap { } } -/// Whether a layout has a child that takes part in the flow (neither absolute -/// nor hidden). Without one there is no content to auto-size the layout to. +/// Whether a flex layout has a child it places (see `Shape::is_in_flow`). pub fn has_in_flow_children(shape: &Shape, shapes: ShapesPoolRef) -> bool { shape .children_ids_iter(true) .filter_map(|id| shapes.get(id)) - .any(|child| !child.is_absolute() && !child.hidden()) + .any(Shape::is_in_flow) +} + +/// Whether a layout has a child that is not absolute. Hidden children count, +/// as in the CLJS layout. +pub fn has_non_absolute_children(shape: &Shape, shapes: ShapesPoolRef) -> bool { + shape + .children_ids_iter(true) + .filter_map(|id| shapes.get(id)) + .any(|child| !child.is_absolute()) } diff --git a/render-wasm/src/shapes/modifiers/flex_layout.rs b/render-wasm/src/shapes/modifiers/flex_layout.rs index af0862e785..6209a5c4c6 100644 --- a/render-wasm/src/shapes/modifiers/flex_layout.rs +++ b/render-wasm/src/shapes/modifiers/flex_layout.rs @@ -202,7 +202,7 @@ fn initialize_tracks( continue; }; - if child.is_absolute() || child.hidden() { + if !child.is_in_flow() { continue; } @@ -686,8 +686,8 @@ pub fn reflow_flex_layout( } } - // Like the CLJS layout, keep the size when there is no content to fit: - // auto-sizing to padding only would collapse the frame. + // With nothing to place, keep the size instead of collapsing to padding. + // CLJS would also size to hidden children; flex here leaves them out. if (layout_axis.is_auto_across || layout_axis.is_auto_main) && has_in_flow_children(shape, shapes) { diff --git a/render-wasm/src/shapes/modifiers/grid_layout.rs b/render-wasm/src/shapes/modifiers/grid_layout.rs index 62d8604e24..24604f19bb 100644 --- a/render-wasm/src/shapes/modifiers/grid_layout.rs +++ b/render-wasm/src/shapes/modifiers/grid_layout.rs @@ -10,7 +10,7 @@ use crate::uuid::Uuid; use std::collections::{HashMap, HashSet, VecDeque}; -use super::common::{has_in_flow_children, GetBounds}; +use super::common::{has_non_absolute_children, GetBounds}; const MIN_SIZE: f32 = 0.01; const MAX_SIZE: f32 = f32::INFINITY; @@ -890,10 +890,10 @@ pub fn reflow_grid_layout( } } - // Like the CLJS layout, keep the size when there is no content to fit: - // auto-sizing to empty tracks would collapse the frame. + // Like the CLJS layout, skip auto-size when every child is absolute: the + // size comes from the tracks, and hidden children still count. if (shape.is_layout_horizontal_auto() || shape.is_layout_vertical_auto()) - && has_in_flow_children(shape, shapes) + && has_non_absolute_children(shape, shapes) { let width = layout_bounds.width(); let height = layout_bounds.height(); From b52fcc7e6d822e6dc5310cb9d200a6593417900f Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Thu, 19 Nov 2026 19:54:52 +0000 Subject: [PATCH 6/6] :tada: Add a command to create pull requests Add `gh.py create-pr` to create pull requests with automatic base detection, optional issue linking and support for project and draft options. Normalize and validate detected base branches, and report the created URL if issue linking fails. Update the skill and workflow documentation, and cover the command and base detection with tests. AI-assisted-by: hy4-flash-free --- .agents/README.md | 2 +- .agents/skills/create-pr/SKILL.md | 138 ++++----- .serena/memories/critical-info.md | 2 +- .serena/memories/scripts/gh.md | 35 +++ .serena/memories/workflow/creating-prs.md | 36 +-- scripts/detect-target-branch | 40 ++- scripts/gh.py | 201 +++++++++++++ scripts/test_gh.py | 327 ++++++++++++++++++++++ 8 files changed, 670 insertions(+), 111 deletions(-) diff --git a/.agents/README.md b/.agents/README.md index 98937323af..6b9ab72d62 100644 --- a/.agents/README.md +++ b/.agents/README.md @@ -481,7 +481,7 @@ JSON, REPL access, and so on. | [`review-plan`](skills/review-plan/SKILL.md) | Evaluates a plan before anyone writes code: completeness, ordering, risks. Approves it or asks for changes. | "review this plan before we start" | | [`implement-plan`](skills/implement-plan/SKILL.md) | Shows you the full flow first — the issue and branch it will create (or the branch it continues on), the execution style, and the task checklist — and, after your go-ahead, executes a ready plan. Default: every task, one commit. On request ("step by step"): one task, one commit, your confirmation between tasks. On request ("direct"): no issue and no branch, commits on the current branch. | "implement the plan" · "step by step, one commit per task" · "direct, no branch" | | [`review-code`](skills/review-code/SKILL.md) | Reviews a diff, branch, or PR and returns findings ranked by impact. | "review my changes before I push" | -| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch — with checks on base branch, commits, issue, and push state — or updates an existing PR's title and description. | "open a PR for this branch" | +| [`create-pr`](skills/create-pr/SKILL.md) | Opens a pull request for the current branch with `scripts/gh.py create-pr` (base autodetection, optional issue link) or updates an existing PR's title and description. | "open a PR for this branch" | | [`resolve-git-conflicts`](skills/resolve-git-conflicts/SKILL.md) | Untangles merge or rebase conflicts: explains both sides, proposes a resolution, applies it after you approve. Never runs `git rebase --continue`. | "resolve these conflicts" | ### References diff --git a/.agents/skills/create-pr/SKILL.md b/.agents/skills/create-pr/SKILL.md index 00d8fd7dc6..82ef8567e3 100644 --- a/.agents/skills/create-pr/SKILL.md +++ b/.agents/skills/create-pr/SKILL.md @@ -1,108 +1,66 @@ --- name: create-pr -description: PR flow — open a new PR for the current task branch (validates base branch, commits, issue and push state) or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing. +description: PR flow — open a new PR for the current task branch or update an existing PR's title or description to match Penpot conventions. Use it when the user asks to open or create a PR, in any phrasing. --- -# Create PR +# Skill: create-pr -Two modes. **Open mode** takes the current task branch to a new, validated -PR. **Update mode** rewrites an existing PR's title or description. Gather -information, validate, and act in one pass. If validation fails, STOP with a -single coherent message that lists every problem and states exactly what -information is missing — never fix or work around problems silently. +Entry point for all GitHub PR work. Authentication, base-branch detection, +push state and the existing-PR check are handled by `python3 scripts/gh.py +create-pr` and by `gh` itself — do not perform them here. The canonical rules +for titles, bodies, merge strategy and issue linking live in +`mem:workflow/creating-prs` (file: +`.serena/memories/workflow/creating-prs.md`). This skill routes to the right +flow. -Both modes require an authenticated `gh` CLI (`gh auth status`) and never -push — the user pushes from their own shell. +## When to Use -## When to use - -- The user asks to open or create a NEW PR for the current task branch, in - any phrasing ("open a PR", "create the pull request", "put this up for - review") — or invokes `@create-pr`. → **Open mode**. -- The user asks to fix or update an EXISTING PR's title or description to - match conventions. → **Update mode**. +- **Open mode** — the user asks to open or create a NEW PR for the current + task branch, in any phrasing ("open a PR", "create the pull request", + "put this up for review") — or invokes `@create-pr`. + → **Open mode** below. +- **Update mode** — the user asks to fix or update an existing PR's title or + description. → **Update mode** below. If the running agent cannot write (for example, the plan agent), say so and stop — this skill needs the build agent. +The user pushes from their own shell. Never push, force-push or modify a +remote. If the command reports that the branch was not pushed, tell the user +to push it and invoke the skill again. + +For draft PRs, warn that CI does not run on them and only add `--draft` when +the user agrees. + ## Open mode -### 1. Gather context (read-only) - -- Current branch: `git rev-parse --abbrev-ref HEAD`. -- Target base branch: run `./scripts/detect-target-branch` from the repo root. - It prints the nearest ancestor branch of HEAD (exit 0) or fails (exit 1). -- Commits: `git log --oneline ..HEAD`. -- Push state (local): `git rev-parse --verify origin/` and compare - with HEAD. It reads the local remote-tracking ref — no network, no SSH. It - reflects the last push or fetch this clone knows about. -- Issue: from the session context, or from the branch name — `issue-NNNN` - maps to issue NNNN; recover its title and body with `gh issue view NNNN`. - -### 2. Validate — stop with one message if anything fails - -Run all checks before reporting, then report every failure together: - -1. **Base branch not usable.** If the script fails (exit 1), or its output — - after stripping an optional `remotes/origin/` prefix — is not one of the - canonical branches (`develop`, `staging`, `main`), stop and ask the user - to re-run with more context — for example, passing the base branch - explicitly in their invocation. An explicit base given by the user - overrides the script's output. -2. **On a base branch.** There is no task branch to merge — say so and stop. -3. **No commits.** The branch has no commits ahead of the base — say so and - stop. -4. **No clear issue.** There is no issue in the session context, and the - branch name has no `issue-NNNN` pattern (or `gh issue view` finds nothing) - — say so and stop. Exception: the user's invocation says `no issue` / - `without issue` — then continue without an issue reference. -5. **Branch not pushed.** The remote-tracking ref `origin/` is - missing, or `git rev-parse origin/` differs from HEAD — the - branch was never pushed, or has commits the remote does not have. Never - push yourself; ask the user to push and to invoke `@create-pr` again - afterwards, then stop. - -### 3. Already-open PR - -Check whether a PR already exists for this branch (`gh pr list --head -`). If one exists, report its URL and stop — do not create a second -one. Title or description fixes belong to Update mode. - -### 4. Write and create the PR - -Write the title and body following `mem:workflow/creating-prs` (title format, -description structure, writing principles) and `mem:workflow/creating-commits` -(commit type emojis). Derive the title and body from the commits and, when -there is one, from the issue body. Include `Closes #NNNN` for readable context, -but do not treat it as the link; use `python3 scripts/gh.py link-issue ` after creating the PR. - -Repeat the `AI-assisted-by:` trailer in the body, once per model that worked -on the branch, so the PR states the assistance where a reviewer reads it. The -branch commits keep their own trailers, and a squash merge carries every one -of them into the landed message. - -Before offering or accepting a draft PR, warn that CI doesn't run on them. Add -`--draft` only when the user agrees to that. +1. Write the title and the body following `mem:workflow/creating-prs`: + `:emoji:` title, the `**Note:**` line, and the `## What` / `## Why` / + `## How` sections. Derive them from the commits and the issue body when + there is one. Repeat the `AI-assisted-by:` trailer once per model that + worked on the branch. Put the body in a temp file to avoid shell quoting. +2. Decide whether the PR resolves an issue. If it does, include `Closes + #NNNN` in the body for human readers and pass `--issue NNNN` so the + command creates the GitHub link. If the user's invocation says `no issue` + / `without issue`, pass no `--issue`. +3. Run the command: ```bash -gh pr create --repo penpot/penpot --base "" --title "" \ - --project "Main" --body-file /tmp/pr-body.md +python3 scripts/gh.py create-pr \ + --title "<TITLE>" --body-file /tmp/pr-body.md [--issue NNNN] [--base BASE] ``` -`--base` is the branch resolved in step 1: without it the PR opens against the -repository default, which is wrong for a branch cut from `staging`. `--project -"Main"` is required by `mem:workflow/creating-prs`. +`--base` is optional: by default the command detects the nearest ancestor +branch of `HEAD`, ported from `scripts/detect-target-branch`. Pass it only +when the detected base is not the one you want. `--head` defaults to the +current branch and `--draft` marks the PR as draft. -If an issue is present, run the explicit assignment command from -`mem:workflow/creating-prs` before reporting success: +If the command fails with `detected base '<name>' is not a local branch; pass +--base explicitly`, rerun it with `--base <name>` using the name from the +error. Do not ask the user and do not add pre-flight checks for this case. -```bash -python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER> -``` - -### 5. Report - -Report the PR URL and stop. +4. Report the URL from the command's output and stop. If it fails, report + the `gh` error as-is; do not add local pre-flight checks. ## Update mode @@ -127,7 +85,7 @@ python3 scripts/gh.py link-issue <ISSUE_NUMBER> <PR_NUMBER> ## User context -Extra context in the user's invocation (the message that triggered this skill) -plays the role command arguments play elsewhere: overrides such as `no issue` / -`without issue`, an explicit base branch (`from origin/staging`), a PR number -for Update mode, and so on. +Extra context in the user's invocation (the message that triggered this +skill) plays the role command arguments play elsewhere: overrides such as +`no issue` / `without issue`, an explicit base branch (`from origin/staging`), +a PR number for Update mode, and so on. diff --git a/.serena/memories/critical-info.md b/.serena/memories/critical-info.md index ce3284686a..0d353c377d 100644 --- a/.serena/memories/critical-info.md +++ b/.serena/memories/critical-info.md @@ -59,7 +59,7 @@ The memory is structured in a way that you can get the critical information abou - `scripts/paren-repair` — Fix mismatched delimiters in Clojure/CLJS files and reformat with cljfmt. Run before lint checks when LLM edits break parens. See `mem:scripts/paren-repair`. - `scripts/psql` — PostgreSQL client wrapper with devenv defaults. Companion: `scripts/db-schema` for DDL dumps. See `mem:scripts/psql`. - `scripts/taiga.py` — Fetch public issues, user stories, and tasks from the Penpot Taiga project without authentication. See `mem:scripts/taiga`. -- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type in one command. Requires `gh` CLI. See `mem:scripts/gh`. +- `scripts/gh.py` — GitHub operations helper: list milestone issues, fetch PR details, compare against CHANGES.md, create issues with their Issue Type and pull requests with optional issue linking in one command. Requires `gh` CLI. See `mem:scripts/gh`. - `scripts/coverage-summary.mjs` — Renders an lcov file as a markdown table grouped by source area, for `$GITHUB_STEP_SUMMARY` (`--title`, `--lcov`, optional `--note`, `--unloaded`). Used by the backend, common and frontend test workflows; module coverage commands are in `mem:backend/testing`, `mem:common/testing`, `mem:frontend/testing`. - `scripts/coverage-comment.mjs` — Keeps one PR comment (`<!-- coverage-report -->`) with the coverage table of Backend, Common, Frontend and Render WASM, in the format of the Vitest Coverage Report Action (status, metric, %, covered/total, changed-file coverage, run/commit footer). Each test job updates its own project: the data of all three lives base64-encoded in a hidden `coverage-data` block, and the job re-reads after `SETTLE_MS` and rewrites if a concurrent job dropped its data; extra report comments from simultaneous creates are merged and deleted. Targets (`THRESHOLDS`, per project and metric, status colour only, never fail CI) are on lines only: 70 Backend, 70 Common, 50 Frontend, 40 Render WASM; other metrics get the blue dot. Statements are Clojure forms for Backend/Common (`--emma-xml`) and llvm regions for Render WASM (`--llvm-json`). Shared lcov parsing: `scripts/coverage-lcov.mjs`. The test workflows run it only for PRs from branches of this repo (job-level `pull-requests: write`, `continue-on-error`): fork PRs get a read-only token, so they only get the run-page summary. A fork-safe `workflow_run` commenter would run only from the default branch's copy of the workflow. - `scripts/project-anomalies.py` — Main-board anomaly check for a milestone (`check` writes `tmp/<MILESTONE>-ANOMALIES.md`). Bulk resolution via `scripts/gh.py`. See `mem:scripts/project-anomalies`. diff --git a/.serena/memories/scripts/gh.md b/.serena/memories/scripts/gh.md index 22b8aef03a..9a7d6f8aab 100644 --- a/.serena/memories/scripts/gh.md +++ b/.serena/memories/scripts/gh.md @@ -11,6 +11,7 @@ repository via GraphQL and REST APIs through the authenticated `gh` CLI. - Comparing milestone issues against CHANGES.md to find missing entries. - Explicitly linking a GitHub issue to a pull request. - Creating an issue with its Issue Type set in a single command. +- Creating a pull request with optional issue linking in a single command. - Listing or inspecting GitHub Security Advisories (GHSA). - Fetching issue comments (the `## Breaking change note` markdown for the changelog). @@ -124,6 +125,40 @@ python3 scripts/gh.py create-issue --type bug --title "..." \ **Output**: JSON object on stdout; progress and errors on stderr. A bad type, a `gh` failure, or a type that was not applied exits non-zero. +### `create-pr` + +Create a pull request and optionally link its issue in one command. + +```bash +python3 scripts/gh.py create-pr \ + --title "Expand backend email tests" --body-file /tmp/pr-body.md \ + [--issue 13202] [--base staging] [--head issue-13202] \ + [--project Main] [--draft] +``` + +`gh pr create` is run with `--repo penpot/penpot`, `--base`, `--head`, +`--title`, `--project` (default `Main`) and `--body-file`, plus `--draft` +when requested. +`--base` defaults to `detect_target_branch()`, a port of +`scripts/detect-target-branch` that uses `git name-rev` plus a graph-walk +fallback; it is local-only and needs no network. It strips trailing `~`/`^` +suffixes and `remotes/<remote>/`, `heads/`, `refs/heads/` and `tags/` prefixes, +then checks the result is a local branch. If it is not, the command fails with +`detected base '<name>' is not a local branch; pass --base explicitly`, and the +caller retries with that `--base`. Pass `--base` to override the detection. +`--head` defaults to the current branch. The PR number is parsed +from the URL returned by `gh`. The URL is printed to stderr immediately, before +any issue linking. When `--issue N` is given, the command calls +`link_issue_to_pr(N, PR)` after creation; a failure there leaves the PR in +place and exits non-zero with the URL in the error message. + +**Output**: JSON object on stdout with `number`, `url`, `title`, `base`, +`head` and `linked_issue`; progress and errors on stderr. A blank title, an +undetectable base, a URL without a number or a `gh` failure exits non-zero. +The command does not check authentication or push state: `gh` reports those +errors itself. Keep `scripts/detect-target-branch` and `detect_target_branch` +in sync — the heuristic is implemented twice by decision. + ### `advisories` List or inspect GitHub Security Advisories for the repository. diff --git a/.serena/memories/workflow/creating-prs.md b/.serena/memories/workflow/creating-prs.md index e8e34181e6..4eaf7f84e2 100644 --- a/.serena/memories/workflow/creating-prs.md +++ b/.serena/memories/workflow/creating-prs.md @@ -10,13 +10,15 @@ PR only on explicit request. ## Target Branch -Auto-detect the base branch with `scripts/detect-target-branch`: - -```bash -TARGET=$(scripts/detect-target-branch) -``` - -This outputs `staging` or `develop` by walking the local commit graph (pure local, no remote/network). Do not ask the user for the target branch unless the tool fails. +The `create-pr` shortcut detects the base branch automatically: it ports the +heuristic of `scripts/detect-target-branch` into `detect_target_branch()` in +`scripts/gh.py` (local commit graph, no remote/network), usually yielding +`staging` or `develop`. Do not ask the user for the target branch unless the +command fails. Pass `--base` only when the detected branch is not the one +wanted; explicit user context overrides the detection. If detection fails +with `detected base '<name>' is not a local branch; pass --base explicitly`, +rerun with `--base <name>` using the name from the error; do not ask the +user and do not add pre-flight checks for this case. ## Metadata @@ -107,20 +109,22 @@ When the PR requests a regular merge instead of a squash merge, its ## Creating the PR +Write the body to a temp file and run the shortcut. It detects the base, runs +`gh pr create` with `--project Main`, parses the PR number and, with +`--issue N`, creates the explicit issue link (see `mem:scripts/gh`): + ```bash cat > /tmp/pr-body.md << 'PR_BODY' <body content here> PR_BODY -TARGET=$(scripts/detect-target-branch) - -gh pr create \ - --repo penpot/penpot \ - --base "$TARGET" \ - --head <branch> \ - --title "<title>" \ - --project "Main" \ - --body-file /tmp/pr-body.md +python3 scripts/gh.py create-pr \ + --title "<title>" --body-file /tmp/pr-body.md \ + [--issue NNNN] [--base <branch>] [--project <project>] rm -f /tmp/pr-body.md ``` + +Do not pre-check authentication, push state or an existing PR: the command +and `gh` report those errors. Never push yourself; ask the user if the +command reports that the branch was not pushed. diff --git a/scripts/detect-target-branch b/scripts/detect-target-branch index 65ff49c0ca..30e95d428f 100755 --- a/scripts/detect-target-branch +++ b/scripts/detect-target-branch @@ -7,6 +7,8 @@ set -euo pipefail # # Uses git name-rev to find the nearest ref (branch/tag) that is an ancestor of # HEAD, falling back to a graph walk if name-rev returns the current branch. +# The ref description is normalized to a local branch name and checked +# against the local branches before it is printed. # # Pure local — no remote, no SSH, no network. Works even when the current # branch shares its tip commit with the target (not yet diverged). @@ -17,7 +19,8 @@ set -euo pipefail # # Exit status: # 0 — target found -# 1 — no target found (orphan commit, no other branches) +# 1 — no target found (orphan commit, no other branches), or the detected +# ref is not a local branch (pass --base explicitly) verbose=false @@ -39,9 +42,30 @@ done current=$(git rev-parse --abbrev-ref HEAD) +# git name-rev describes refs, not branch names: "remotes/origin/staging~1", +# "develop^2~1" and "tags/v2.0" are all possible outputs. +normalize_ref() { + local name="$1" + name=${name%%[~^]*} + case "$name" in + refs/heads/*) name=${name#refs/heads/} ;; + heads/*) name=${name#heads/} ;; + remotes/*) + name=${name#remotes/} + if [[ "$name" == */* ]]; then + name=${name#*/} + else + name="" + fi + ;; + tags/*) name=${name#tags/} ;; + esac + printf '%s' "$name" +} + # Use name-rev to find the nearest ref — it has smart tie-breaking -raw=$(git name-rev --name-only HEAD 2>/dev/null) -target=${raw%%~[0-9]*} # strip ~N distance suffix +raw=$(git name-rev --name-only HEAD 2>/dev/null || true) +target=$(normalize_ref "$raw") # If name-rev returned the current branch itself, walk backwards if [ "$target" = "$current" ] || [ -z "$target" ]; then @@ -61,6 +85,16 @@ if [ "$target" = "$current" ] || [ -z "$target" ]; then fi fi +target=$(normalize_ref "$target") +if [ -z "$target" ]; then + echo "error: unable to determine target branch" >&2 + exit 1 +fi +if ! git show-ref --verify --quiet "refs/heads/$target"; then + echo "error: detected base '$target' is not a local branch; pass --base explicitly" >&2 + exit 1 +fi + if [ "$verbose" = true ]; then target_commit=$(git rev-parse "$target" 2>/dev/null || true) if [ -n "$target_commit" ]; then diff --git a/scripts/gh.py b/scripts/gh.py index 3881fb158a..c0e86940ac 100755 --- a/scripts/gh.py +++ b/scripts/gh.py @@ -12,6 +12,7 @@ Subcommands: advisories List or inspect GitHub security advisories link-issue Explicitly link a GitHub issue to a pull request create-issue Create an issue and set its Issue Type in one command + create-pr Create a pull request, optionally linking its issue Usage: python3 scripts/gh.py issues <milestone-title> (default: state=closed) @@ -37,6 +38,8 @@ Usage: python3 scripts/gh.py link-issue 11235 11243 python3 scripts/gh.py create-issue --type task \ --title "Expand backend email tests" --body-file /tmp/issue-body.md + python3 scripts/gh.py create-pr --title "Expand backend email tests" \ + --body-file /tmp/pr-body.md --issue 13202 [--base staging] Prerequisites: - gh CLI authenticated (gh auth status) @@ -135,6 +138,17 @@ def run_gh_rest(path: str) -> Any: fail_gh(err.stderr) +def run_git(*args: str) -> str: + """Run a ``git`` command and return its stripped stdout. + + Raises `GhCommandFailed` on failure so callers can degrade gracefully. + """ + result = subprocess.run(["git", *args], capture_output=True, text=True) + if result.returncode != 0: + raise GhCommandFailed(result.stderr) + return result.stdout.strip() + + # ───────────────────────────────────────────── # Subcommand: create-issue # ───────────────────────────────────────────── @@ -255,6 +269,166 @@ def cmd_create_issue(args: argparse.Namespace) -> None: print(json.dumps(result, indent=2)) +# ───────────────────────────────────────────── +# Subcommand: create-pr +# ───────────────────────────────────────────── + +PR_URL_RE = re.compile(r"/pull/(\d+)") + + +def normalize_branch_ref(ref: str) -> str: + """Turn a ``git name-rev`` description into a local branch name. + + ``name-rev`` can return ``remotes/origin/staging~1``, ``develop^2~1`` or + ``tags/v2.0``; none of them is a valid ``--base`` value. + """ + name = re.split(r"[~^]", ref.strip(), maxsplit=1)[0] + for prefix in ("refs/heads/", "heads/"): + if name.startswith(prefix): + return name[len(prefix):] + if name.startswith("remotes/"): + name = name[len("remotes/"):] + return name.split("/", 1)[1] if "/" in name else "" + if name.startswith("tags/"): + return name[len("tags/"):] + return name + + +def local_branch_exists(name: str) -> bool: + """Return whether ``name`` is a local branch (no network involved).""" + try: + run_git("show-ref", "--verify", "--quiet", f"refs/heads/{name}") + return True + except GhCommandFailed: + return False + + +def detect_target_branch() -> str: + """Return the nearest ancestor branch of HEAD, using only local git. + + Port of ``scripts/detect-target-branch``: ``git name-rev`` picks the + closest ref and a graph walk is the fallback when it resolves to the + current branch. The result is normalized and checked against the local + branches because ``name-rev`` describes refs, not branch names. + """ + current = run_git("rev-parse", "--abbrev-ref", "HEAD") + try: + raw = run_git("name-rev", "--name-only", "HEAD") + except GhCommandFailed: + raw = "" + target = normalize_branch_ref(raw) if raw else "" + if not target or target == current: + target = "" + for commit in run_git("rev-list", "HEAD").splitlines(): + branches = run_git( + "branch", "--points-at", commit, "--format=%(refname:short)" + ).splitlines() + found = next( + ( + branch.strip() + for branch in branches + if branch.strip() and branch.strip() != current + ), + None, + ) + if found: + target = normalize_branch_ref(found) + break + if not target: + raise RuntimeError("unable to determine target branch") + if not local_branch_exists(target): + raise RuntimeError( + f"detected base {target!r} is not a local branch; pass --base explicitly" + ) + return target + + +def create_pr( + title: str, + body_file: str, + base: str | None = None, + head: str | None = None, + issue_number: int | None = None, + project: str = "Main", + draft: bool = False, +) -> dict: + """Create a PR and optionally link its issue in one sequence of calls. + + The base defaults to the nearest ancestor branch of HEAD and the head to + the current branch, so the caller only needs to supply the title and the + body. A failed issue link leaves the PR in place and reports its URL. + """ + if not title.strip(): + raise ValueError("pull request title must not be empty") + resolved_base = (base or detect_target_branch()).strip() + if not resolved_base: + raise ValueError("pull request base must not be empty") + resolved_head = (head or run_git("rev-parse", "--abbrev-ref", "HEAD")).strip() + + cmd = [ + "gh", "pr", "create", + "--repo", REPO, + "--base", resolved_base, + "--head", resolved_head, + "--title", title, + "--project", project, + "--body-file", body_file, + ] + if draft: + cmd.append("--draft") + stdout = run_gh_command(cmd) + url = stdout.strip().splitlines()[-1].strip() + match = PR_URL_RE.search(url) + if not match: + raise RuntimeError( + f"could not read PR number from gh output: {url!r};" + " check whether the PR was created" + ) + number = int(match.group(1)) + print(f"Created PR #{number}: {url}", file=sys.stderr) + + linked_issue = None + if issue_number is not None: + try: + link_issue_to_pr(issue_number, number) + except SystemExit: + raise RuntimeError( + f"issue linking failed; the PR was created at {url}" + ) from None + except (ValueError, RuntimeError) as error: + raise RuntimeError(f"{error}; the PR was created at {url}") from error + linked_issue = issue_number + + return { + "number": number, + "url": url, + "title": title, + "base": resolved_base, + "head": resolved_head, + "linked_issue": linked_issue, + } + + +def cmd_create_pr(args: argparse.Namespace) -> None: + """Handle the ``create-pr`` subcommand.""" + print("Creating pull request...", file=sys.stderr) + try: + result = create_pr( + args.title, + args.body_file, + base=args.base, + head=args.head, + issue_number=args.issue, + project=args.project, + draft=args.draft, + ) + except (ValueError, RuntimeError, GhCommandFailed) as error: + print(f"ERROR: {error}", file=sys.stderr) + sys.exit(1) + + print(json.dumps(result, indent=2)) + + # ───────────────────────────────────────────── # Subcommand: link-issue # ───────────────────────────────────────────── @@ -1291,6 +1465,33 @@ def main() -> None: ) p_create.set_defaults(func=cmd_create_issue) + # --- create-pr --- + p_create_pr = sub.add_parser( + "create-pr", + help="Create a pull request, optionally linking its issue", + ) + p_create_pr.add_argument("--title", required=True, help="Pull request title") + p_create_pr.add_argument( + "--body-file", required=True, + help="Path to the file holding the Markdown body", + ) + p_create_pr.add_argument( + "--base", help="Base branch (default: nearest ancestor branch of HEAD)" + ) + p_create_pr.add_argument( + "--head", help="Head branch (default: current branch)" + ) + p_create_pr.add_argument( + "--issue", type=int, help="Issue number to link to the new PR" + ) + p_create_pr.add_argument( + "--draft", action="store_true", help="Create the PR as a draft" + ) + p_create_pr.add_argument( + "--project", default="Main", help="Project to add the PR to (default: Main)" + ) + p_create_pr.set_defaults(func=cmd_create_pr) + # --- issue (by-number lookup) --- p_issue = sub.add_parser( "issue", help="Fetch details for one or more issues by number (batched)" diff --git a/scripts/test_gh.py b/scripts/test_gh.py index fb15b1a8ce..41f6bd9c4a 100644 --- a/scripts/test_gh.py +++ b/scripts/test_gh.py @@ -179,6 +179,333 @@ class CreateIssueTests(unittest.TestCase): self.assertIn("boom", stderr.getvalue()) +class CreatePrBaseDetectionTests(unittest.TestCase): + @staticmethod + def fake_git(mapping): + def run(*args): + return mapping.get(args, "") + return run + + def test_normalize_branch_ref(self): + cases = [ + ("remotes/origin/staging~2", "staging"), + ("develop^2~1", "develop"), + ("tags/v2.0", "v2.0"), + ("refs/heads/topic~1", "topic"), + ("heads/topic", "topic"), + ] + for raw, expected in cases: + with self.subTest(raw=raw): + self.assertEqual(gh.normalize_branch_ref(raw), expected) + + @patch.object(gh, "run_git") + def test_detects_normalized_base_and_validates_it(self, run_git): + calls = [] + + def fake(*args): + calls.append(args) + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("name-rev", "--name-only", "HEAD"): + return "remotes/origin/staging~2" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + self.assertIn( + ("show-ref", "--verify", "--quiet", "refs/heads/staging"), calls + ) + + @patch.object(gh, "run_git") + def test_rejects_detected_base_without_local_branch(self, run_git): + def fake(*args): + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("name-rev", "--name-only", "HEAD"): + return "tags/v2.0" + if args[:1] == ("show-ref",): + raise gh.GhCommandFailed("not found") + return "" + run_git.side_effect = fake + + with self.assertRaisesRegex(RuntimeError, "pass --base"): + gh.detect_target_branch() + + @patch.object(gh, "run_git") + def test_detects_base_from_name_rev(self, run_git): + run_git.side_effect = self.fake_git({ + ("rev-parse", "--abbrev-ref", "HEAD"): "issue-13202", + ("name-rev", "--name-only", "HEAD"): "staging~3", + }) + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_falls_back_to_graph_walk(self, run_git): + def fake(*args): + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "issue-13202" + if args == ("name-rev", "--name-only", "HEAD"): + return "issue-13202" + if args == ("rev-list", "HEAD"): + return "a\nb\nc\n" + if args[:2] == ("branch", "--points-at"): + return "staging\n" if args[2] == "b" else "" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_tolerates_name_rev_failure(self, run_git): + def fake(*args): + if args == ("name-rev", "--name-only", "HEAD"): + raise gh.GhCommandFailed("boom") + if args == ("rev-parse", "--abbrev-ref", "HEAD"): + return "topic" + if args == ("rev-list", "HEAD"): + return "a\n" + if args[:2] == ("branch", "--points-at"): + return "staging\n" + return "" + run_git.side_effect = fake + + self.assertEqual(gh.detect_target_branch(), "staging") + + @patch.object(gh, "run_git") + def test_raises_when_no_other_branch(self, run_git): + run_git.side_effect = self.fake_git({ + ("rev-parse", "--abbrev-ref", "HEAD"): "topic", + ("name-rev", "--name-only", "HEAD"): "", + ("rev-list", "HEAD"): "a\n", + }) + + with self.assertRaisesRegex(RuntimeError, "unable to determine target branch"): + gh.detect_target_branch() + + +class CreatePrTests(unittest.TestCase): + def setUp(self): + self.url = "https://github.com/penpot/penpot/pull/13204" + self.create_response = self.url + "\n" + + def args(self, **overrides): + values = dict( + title="A title", + body_file="/tmp/pr-body.md", + base=None, + head=None, + issue=None, + project="Main", + draft=False, + ) + values.update(overrides) + return types.SimpleNamespace(**values) + + @patch.object(gh, "link_issue_to_pr") + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git") + @patch.object(gh, "detect_target_branch") + def test_create_pr_detects_base_and_links_issue( + self, detect, run_git, run_command, link_issue + ): + detect.return_value = "staging" + run_git.return_value = "issue-13202" + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr( + "A title", "/tmp/pr-body.md", issue_number=13202 + ) + + self.assertEqual(result, { + "number": 13204, + "url": self.url, + "title": "A title", + "base": "staging", + "head": "issue-13202", + "linked_issue": 13202, + }) + self.assertEqual(run_command.call_args.args[0], [ + "gh", "pr", "create", + "--repo", "penpot/penpot", + "--base", "staging", + "--head", "issue-13202", + "--title", "A title", + "--project", "Main", + "--body-file", "/tmp/pr-body.md", + ]) + link_issue.assert_called_once_with(13202, 13204) + detect.assert_called_once_with() + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git") + @patch.object(gh, "detect_target_branch") + def test_create_pr_uses_explicit_base(self, detect, run_git, run_command): + run_git.return_value = "topic" + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr("T", "/tmp/pr-body.md", base="release/1.0") + + self.assertEqual(result["base"], "release/1.0") + detect.assert_not_called() + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--base") + 1], "release/1.0") + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_passes_head_and_draft(self, _detect, run_command): + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + result = gh.create_pr( + "T", "/tmp/pr-body.md", head="custom", draft=True + ) + + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--head") + 1], "custom") + self.assertIn("--draft", cmd) + self.assertIsNone(result["linked_issue"]) + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "detect_target_branch") + def test_create_pr_rejects_empty_title(self, _detect, run_command): + with self.assertRaisesRegex(ValueError, "title must not be empty"): + gh.create_pr(" ", "/tmp/pr-body.md") + run_command.assert_not_called() + + @patch.object(gh, "run_gh_command", return_value="created") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_fails_when_url_has_no_number( + self, _detect, _run_git, _run_command + ): + with self.assertRaisesRegex(RuntimeError, "could not read PR number"): + gh.create_pr("T", "/tmp/pr-body.md") + + @patch.object(gh, "run_gh_command", side_effect=gh.GhCommandFailed("boom")) + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_propagates_gh_failure( + self, _detect, _run_git, _run_command + ): + with self.assertRaises(gh.GhCommandFailed): + gh.create_pr("T", "/tmp/pr-body.md") + + @patch.object(gh, "link_issue_to_pr") + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_prints_url_once_on_success( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + gh.create_pr("T", "/tmp/pr-body.md", issue_number=13202) + + self.assertEqual(stderr.getvalue().count("Created PR #13204"), 1) + + @patch.object(gh, "link_issue_to_pr", side_effect=RuntimeError("link missing")) + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_cmd_create_pr_keeps_url_when_link_raises_runtime_error( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args(issue=13202)) + + self.assertEqual(error.exception.code, 1) + self.assertIn("Created PR #13204", stderr.getvalue()) + self.assertIn(self.url, stderr.getvalue()) + + @patch.object(gh, "link_issue_to_pr", side_effect=SystemExit(1)) + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_cmd_create_pr_keeps_url_when_link_exits( + self, _detect, _run_git, run_command, _link_issue + ): + run_command.return_value = self.create_response + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args(issue=13202)) + + self.assertEqual(error.exception.code, 1) + self.assertIn("Created PR #13204", stderr.getvalue()) + self.assertIn("issue linking failed", stderr.getvalue()) + self.assertIn(self.url, stderr.getvalue()) + self.assertNotIn("ERROR: 1", stderr.getvalue()) + + @patch.object(gh, "create_pr") + def test_cmd_create_pr_outputs_result(self, create_pr): + expected = { + "number": 13204, + "url": self.url, + "title": "T", + "base": "staging", + "head": "topic", + "linked_issue": None, + } + create_pr.return_value = expected + stdout = io.StringIO() + stderr = io.StringIO() + + with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + gh.cmd_create_pr(self.args()) + + self.assertEqual(json.loads(stdout.getvalue()), expected) + self.assertIn("Creating pull request...", stderr.getvalue()) + create_pr.assert_called_once_with( + "A title", "/tmp/pr-body.md", + base=None, head=None, issue_number=None, + project="Main", draft=False, + ) + + @patch.object(gh, "create_pr") + def test_cmd_create_pr_forwards_project(self, create_pr): + create_pr.return_value = {"number": 13204, "url": self.url} + + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr( + io.StringIO() + ): + gh.cmd_create_pr(self.args(project="Other")) + + self.assertEqual(create_pr.call_args.kwargs["project"], "Other") + + @patch.object(gh, "run_gh_command") + @patch.object(gh, "run_git", return_value="topic") + @patch.object(gh, "detect_target_branch", return_value="staging") + def test_create_pr_uses_explicit_project(self, _detect, _run_git, run_command): + run_command.return_value = self.create_response + + with contextlib.redirect_stderr(io.StringIO()): + gh.create_pr("T", "/tmp/pr-body.md", project="Other") + + cmd = run_command.call_args.args[0] + self.assertEqual(cmd[cmd.index("--project") + 1], "Other") + + @patch.object(gh, "create_pr", side_effect=gh.GhCommandFailed("boom")) + def test_cmd_create_pr_exits_on_error(self, _create_pr): + stderr = io.StringIO() + + with contextlib.redirect_stderr(stderr): + with self.assertRaises(SystemExit) as error: + gh.cmd_create_pr(self.args()) + + self.assertEqual(error.exception.code, 1) + self.assertIn("boom", stderr.getvalue()) + + class LinkIssueTests(unittest.TestCase): def setUp(self): self.target_response = {