🐛 Make execute_code wait for save before success (#13027)

* 🐛 Make execute_code wait for save before success

* 🐛 Address review feedback on waitForSave

Reject with an Error carrying a `code`: save-timeout, rolled-back,
save-retrying, or the failure code (save-failed by default). Lower the
default timeout from 90s to 60s, leaving room for the 30s layout wait
and the code under the MCP tool timeout.

When persistence is already in error at the start of the wait, keep the
stored failure code, and tell a failure Penpot keeps retrying apart from
one that needs the file reopened.

Share timeout validation with waitForLayoutUpdate through
app.plugins.utils, and make reject-not-valid reject with an Error, which
also fixes the string rejections of connectLibrary, restore, remove,
pin, export, findVersions and saveVersion.

The MCP execute_code handler now waits for the save only when the
workspace is ready, like the layout wait, so dashboard calls no longer
fail on a save error from an earlier file.

Move the waitForSave tests to frontend-tests.plugins, add tests for the
error codes, the retrying state and a failure during the wait, and add
plugin API suite and MCP handler tests. Update the docs, CHANGELOG and
the generated API files.

AI-assisted-by: claude-opus-5-5
This commit is contained in:
Pablo Alba 2026-11-17 22:35:37 +01:00 committed by GitHub
parent 14b9d77e9f
commit 73e7815817
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 990 additions and 52 deletions

View File

@ -37,5 +37,7 @@
- Plugin listeners are watches on the global store and callbacks are debounced about 10ms. Callback exceptions are caught and logged so plugin code does not crash the app.
- `selectionchange` callbacks receive arrays of shape id strings, while `filechange`, `pagechange`, and `shapechange` return proxies.
- `contentsave` fires only when persistence status transitions to `:saved`; it calls the callback with no value.
- `penpot.waitForSave(timeout?)` (`app.plugins.persist/wait-for-save`; runtime forwarder checks `content:read`) waits on the **shared** persistence queue, not only the plugin's own commits. Flow: ~100ms intake race (buffer/queue non-empty vs deadline, capped to the timeout) → empty resolves; pending emits `::dps/force-persist` and races `dps/wait-persisted-or-error` against `::dps/rollback-rejected` / `::dps/rolled-back` (rollback rejects even if status later reads `:saved`). Default 60s. `:error` status at intake rejects at once (`earlier-failure`): `save-retrying` while `dps/save-retrying?` (slow retry cycle, recovers by itself), otherwise the stored `[:error :code]` with reopen advice (a terminal failure stays until the file is reopened, so it fails every call). Rejections are `Error`s with `code`: `save-timeout`, `rolled-back`, `save-retrying`, or the failure code (`save-failed` unless the backend gave one).
- Plugin timeouts validate through `u/valid-timeout?` (positive finite number ≤ `u/max-timeout`, signed 32-bit) and reject through `u/reject-not-valid`, which rejects an `Error` (never a bare string) so callers can read `.message`.
- `contentrollback` is not a state watch: it subscribes to `st/stream` for `::dps/rolled-back` (kept in `subscriptions`, disposed by `remove-listener`), not debounced, delivered async so the reverted state is in place. Payload `{fileIds pageIds shapeIds}` from `pcm/rollback-targets` (page shapes only, from the reverted commits' redo changes). When the rollback falls back to reloading the file, `::dps/rolled-back` waits for the reloaded data, so the callback never reads the rejected data. The runtime's `validEvents` must list every event name, or `penpot.on` rejects it; a stale runtime build rejects new events. The MCP plugin forwards these rollbacks with the next task response and the server puts a warning first in that tool response (`RollbackNotices`). Unsent ones survive a tab or plugin reload in `penpot.localStorage` (key `rollbacks/<file-id>`, `LocalStorageRollbackStore`; the MCP manifest in `app.main.data.workspace.mcp` and `mcp/packages/plugin/public/manifest.json` grant `allow:localstorage`, which the runtime checks on access); the entry goes once a response carried them.
- Plugin history `undoBlockBegin` creates a workspace undo transaction with a JS `Symbol`; `undoBlockFinish` commits that symbol. Missing finish eventually relies on the workspace transaction timeout.

View File

@ -154,4 +154,5 @@ For parallel devenvs, prefer same-origin MCP routing: each Penpot instance shoul
## Rollback warnings
- `ExecuteCodeTaskHandler` awaits `penpot.waitForSave()` after the code and outside its swallow catch, so a save failure, save timeout or rollback during the wait fails that `execute_code` call itself. It hard-fails as "missing Plugin API support" when `penpot.waitForSave` is absent (old Penpot or stale runtime build, or broken `api.cljs` wiring). Both waits run only when `penpotMgmt.workspace.status` is `"ready"` (or there is no `penpotMgmt`), checked at each wait: dashboard calls skip them, because persistence `:error` outlives the workspace and would fail successful `penpotMgmt` calls. Budget: layout wait 30s before the code + save wait 60s after it, under `PENPOT_MCP_TOOL_TIMEOUT_S` (120s). `RollbackNotices` below only cover rollbacks that land after the call returned (concurrent edits, a response after a timeout).
- The plugin's `RollbackLog` (`packages/plugin/src/RollbackLog.ts`) holds the `contentrollback` events not yet sent with a task response; `Task.sendResponse` attaches them and acknowledges them once sent, and the server's `unclaimed-rollbacks` message (a response that came after its task timed out) puts them back. With a `RollbackStore` (`LocalStorageRollbackStore` over `penpot.localStorage`, one entry per file) every change is written through, so a reload of the tab or plugin keeps them; storage failures fall back to memory. Plugin tests run with `node --experimental-strip-types`, which rejects TypeScript parameter properties: declare fields explicitly.

View File

@ -46,6 +46,7 @@
[app.plugins.management :as management]
[app.plugins.page :as page]
[app.plugins.parser :as parser]
[app.plugins.persist :as wpsp]
[app.plugins.reflow :as wrfp]
[app.plugins.register :as r]
[app.plugins.shape :as shape]
@ -765,4 +766,9 @@
:waitForLayoutUpdate
(fn [timeout]
;; Resolves once every shape with reflow work in flight has settled.
(wrfp/wait-for-layout-update timeout))))
(wrfp/wait-for-layout-update timeout))
:waitForSave
(fn [timeout]
;; Resolves once pending edits are saved (or there is nothing to save).
(wpsp/wait-for-save timeout))))

View File

@ -0,0 +1,130 @@
;; 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.plugins.persist
"Promise adapter for the plugin `waitForSave` method. Owns timeout
validation, the short commit→buffer intake race, force-flush, and the
save-vs-rollback race; persistence itself lives in
`app.main.data.persistence`."
(:require
[app.common.data.macros :as dm]
[app.main.data.persistence :as dps]
[app.main.refs :as refs]
[app.main.store :as st]
[app.plugins.utils :as u]
[app.util.object :as obj]
[beicon.v2.core :as rx]
[potok.v2.core :as ptk]))
;; Leaves room for the 30s layout wait and the code itself under the
;; default MCP tool timeout (120s).
(def ^:private default-timeout 60000)
;; Primary quiescence: how long to wait for commits to enter buffer/queue
;; before treating empty persistence as "nothing to save". Not the 200ms
;; pending-status debounce.
(def ^:private intake-ms 100)
(defn- pending-work?
"True when persistence still holds buffered or queued commits."
[{:keys [buffer queue]}]
(boolean (or (seq buffer) (seq queue))))
(defn- ->js-error
"Turns a cljs/JS failure into a JS Error for Promise rejection, keeping
the `ex-data` `:code` as the Error `code` property."
[cause]
(let [err (if (instance? js/Error cause)
cause
(js/Error. (or (ex-message cause) (str cause))))
code (:code (ex-data cause))]
(when (keyword? code)
(obj/set! err "code" (name code)))
err))
(def ^:private earlier-failure-message
(dm/str "Changes could not be saved: the file has a failed save that "
"stays until the file is reopened, so no change can be confirmed "
"as saved. Reopen the file to resume saving."))
(def ^:private retrying-message
(dm/str "Changes could not be saved yet: saves are failing and Penpot "
"keeps retrying them. Try again later."))
(defn- earlier-failure
"Rejection for a wait that starts while persistence is `:error`."
[pstate]
(if (dps/save-retrying? pstate)
(ex-info retrying-message {:type :persistence :code :save-retrying})
(ex-info earlier-failure-message
{:type :persistence
:code (get-in pstate [:error :code] :save-failed)})))
(defn- wait-intake
"Races buffer/queue becoming non-empty against an intake deadline of
`delay-ms` (capped by the caller to the wait timeout)."
[delay-ms]
(->> (rx/race (->> (rx/from-atom refs/persistence {:emit-current-value? true})
(rx/filter pending-work?)
(rx/take 1)
(rx/map (constantly :pending)))
(->> (rx/of :empty)
(rx/delay delay-ms)))
(rx/take 1)))
(defn- wait-save-or-rollback
"Races a clean persist settle against rollback start or completion.
Soft rejection emits `::rollback-rejected` before settle can publish
empty `:saved`; `::rolled-back` may arrive later after a reload."
[timeout-ms]
(rx/race (->> (dps/wait-persisted-or-error timeout-ms)
(rx/map (constantly :saved)))
(->> st/stream
(rx/filter (some-fn (ptk/type? ::dps/rollback-rejected)
(ptk/type? ::dps/rolled-back)))
(rx/take 1)
(rx/mapcat (fn [_]
(rx/throw (ex-info "Changes were rolled back"
{:type :persistence :code :rolled-back})))))))
(defn wait-for-save
"Returns a JS Promise that resolves once pending file changes are saved,
or there is nothing to save after a short intake window.
Rejects when `timeout` is invalid, the save fails (also a failure from
before the call: a terminal one stays until the file is reopened),
changes are rolled back during the wait, or the deadline elapses. The
Error `code` is `save-timeout`, `rolled-back`, `save-retrying` (an
earlier failure Penpot keeps retrying), or the failure code
(`save-failed` unless the backend gave a more specific one). A nil
`timeout` uses `default-timeout`."
([] (wait-for-save nil))
([timeout]
(js/Promise.
(fn [resolve reject]
(if-not (u/valid-timeout? timeout)
(u/reject-not-valid reject :waitForSave timeout)
(let [timeout-ms (or timeout default-timeout)
delay-ms (js/Math.min intake-ms timeout-ms)]
(->> (wait-intake delay-ms)
(rx/mapcat
(fn [_]
(let [pstate @refs/persistence]
(cond
(= :error (:status pstate))
(rx/throw (earlier-failure pstate))
(pending-work? pstate)
(do
(st/emit! ::dps/force-persist)
(wait-save-or-rollback timeout-ms))
:else
(rx/of :empty)))))
(rx/take 1)
(rx/subs!
(fn [_] (resolve))
(fn [cause] (reject (->js-error cause)))))))))))

View File

@ -9,35 +9,16 @@
argument validation, the default deadline and the rejection shape; the
workspace only reports when its pending work has drained."
(:require
[app.common.data.macros :as dm]
[app.common.files.helpers :as cfh]
[app.common.uuid :as uuid]
[app.main.data.workspace.reflow :as wrf]
[app.plugins.utils :as u]
[beicon.v2.core :as rx]))
;; Ceiling for callers that pass no timeout, so a pipeline that never drains
;; its marks rejects the promise rather than leaving it unsettled.
(def ^:private default-timeout 30000)
;; Largest value a signed 32-bit timer accepts.
(def ^:private max-timeout 2147483647)
(defn- valid-timeout?
"Checks that a plugin timeout fits a signed 32-bit timer."
[value]
(or (nil? value)
(and (number? value)
(pos? value)
(<= value max-timeout)
(js/Number.isFinite value))))
(defn- reject-invalid!
[reject value]
(let [msg (dm/str "[PENPOT PLUGIN] Value not valid: " value
". Code: " :waitForLayoutUpdate)]
(.error js/console msg)
(reject (js/Error. msg))))
(defn shape-wait-ids
"Ids a per-shape wait covers: the shape subtree, its ancestors, and the file
its components sync from."
@ -59,8 +40,8 @@
([ids timeout]
(js/Promise.
(fn [resolve reject]
(if-not (valid-timeout? timeout)
(reject-invalid! reject timeout)
(if-not (u/valid-timeout? timeout)
(u/reject-not-valid reject :waitForLayoutUpdate timeout)
;; Race the settle signal against the deadline; the loser is
;; unsubscribed. `settled` replays on subscribe, so an already drained
;; map wins even against a 1ms deadline.

View File

@ -341,10 +341,24 @@
(display-not-valid code value)))
(defn reject-not-valid
"Rejects a promise with the standard invalid-value Error and logs it."
[reject code value]
(let [msg (dm/str "[PENPOT PLUGIN] Value not valid: " value ". Code: " code)]
(.error js/console msg)
(reject msg)))
(reject (js/Error. msg))))
(def max-timeout
"Largest value a signed 32-bit timer accepts."
2147483647)
(defn valid-timeout?
"Checks that a plugin timeout fits a signed 32-bit timer."
[value]
(or (nil? value)
(and (number? value)
(pos? value)
(<= value max-timeout)
(js/Number.isFinite value))))
(defn mixed-value
[values]

View File

@ -289,3 +289,9 @@
message (plugins.utils/error-messages (sm/explain schema {:value ""}))]
(t/is (= "Field value is invalid: Empty input" message))))
(t/deftest test-reject-not-valid-rejects-an-error
;; Plugins read `.message` off the rejection, so it must be an Error.
(let [rejected (atom nil)]
(plugins.utils/reject-not-valid #(reset! rejected %) :someMethod "bad")
(t/is (instance? js/Error @rejected))
(t/is (str/includes? (.-message @rejected) "Code: :someMethod"))))

View File

@ -0,0 +1,294 @@
;; 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.plugins.wait-for-save-test
"Contract tests for app.plugins.persist/wait-for-save (plugin waitForSave)."
(:require
[app.main.data.persistence :as dps]
[app.main.refs :as refs]
[app.main.store :as st]
[app.plugins.api :as api]
[app.plugins.persist :as persist]
[beicon.v2.core :as rx]
[cljs.test :as t :include-macros true]
[frontend-tests.helpers.async :as async]
[frontend-tests.helpers.mock :as mock]
[frontend-tests.helpers.persistence :as thp :refer [local-commit with-persistence]]
[okulary.core :as l]
[potok.v2.core :as ptk]))
(defn- with-save-mocks
"Redirects persistence refs and st/emit! onto the fixture store."
[store body]
(mock/with-mocks*
{refs/persistence (l/derived :persistence store)
st/state store
st/stream (ptk/input-stream store)}
(body)))
(defn- await-outcome
"Resolves to {:ok value} or {:error err} for a JS promise."
[p]
(-> p
(.then (fn [v] {:ok v}))
(.catch (fn [e] {:error e}))))
(defn- error-code
[outcome]
(some-> (:error outcome) .-code))
(t/deftest ^:async empty-persistence-resolves-after-intake
(await
(with-persistence
(^:async fn [{:keys [requests store]}]
(await
(with-save-mocks store
(^:async fn []
(let [outcome (await (await-outcome (persist/wait-for-save 2000)))]
(t/is (contains? outcome :ok)
"empty buffer and queue resolve after intake")
(t/is (empty? @requests)
"nothing to save sends no update-file")))))))))
(t/deftest ^:async context-wait-for-save-resolves
;; Goes through the plugin context proxy, the only way plugins reach it.
(await
(with-persistence
(^:async fn [{:keys [store]}]
(await
(with-save-mocks store
(^:async fn []
(let [^js ctx (api/create-context "00000000-0000-0000-0000-000000000000")
outcome (await (await-outcome (.waitForSave ctx 2000)))]
(t/is (contains? outcome :ok)
"context waitForSave resolves with nothing to save")))))))))
(t/deftest ^:async invalid-timeout-rejects
(await
(with-persistence
(^:async fn [{:keys [store]}]
(await
(with-save-mocks store
(^:async fn []
(doseq [value [-1 0 ##NaN ##Inf 2147483648]]
(let [outcome (await (await-outcome (persist/wait-for-save value)))]
(t/is (instance? js/Error (:error outcome))
(str value " rejects with an Error"))
(t/is (re-find #"not valid.*waitForSave"
(or (some-> (:error outcome) .-message) ""))))))))))))
(t/deftest ^:async terminal-error-rejects
(await
(with-persistence
(^:async fn [{:keys [store]}]
(await
(with-save-mocks store
(^:async fn []
;; Empty queue+buffer with :error is a terminal waiter release
;; (see dps/terminal-status?).
(swap! store assoc-in [:persistence :status] :error)
(swap! store assoc-in [:persistence :error]
{:type :persistence :code :save-permission-denied})
(swap! store assoc-in [:persistence :queue] #queue [])
(swap! store assoc-in [:persistence :buffer] [])
(let [outcome (await (await-outcome (persist/wait-for-save 2000)))]
(t/is (contains? outcome :error)
"terminal :error rejects waitForSave")
(t/is (re-find #"(?i)could not be saved.*reopen"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "save-permission-denied" (error-code outcome))
"the stored failure code is kept")))))))))
(t/deftest ^:async retrying-error-rejects-without-reopen
(await
(with-persistence
(^:async fn [{:keys [store]}]
(await
(with-save-mocks store
(^:async fn []
;; A transport failure the slow retry cycle keeps resending
;; (dps/save-retrying?) recovers by itself: no reopen advice.
(swap! store update :persistence assoc
:status :error
:error {:type :persistence :cause-type :network}
:failing-since (js/Date.now))
(let [outcome (await (await-outcome (persist/wait-for-save 2000)))
message (or (some-> (:error outcome) .-message) "")]
(t/is (contains? outcome :error))
(t/is (= "save-retrying" (error-code outcome)))
(t/is (re-find #"(?i)retrying" message))
(t/is (not (re-find #"(?i)reopen" message)))))))))))
(t/deftest ^:async save-failure-during-wait-rejects
(await
(with-persistence
(^:async fn [{:keys [file-id response requests store]}]
(await
(with-save-mocks store
(^:async fn []
(ptk/emit! store (local-commit file-id))
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
(let [p (persist/wait-for-save 5000)]
(await (async/wait-for #(seq @requests)
"force-persist flushed the buffer"))
(rx/error! response (ex-info "rejected" {:type :validation :code :invalid-data}))
(let [outcome (await (await-outcome p))]
(t/is (contains? outcome :error)
"a save that fails during the wait rejects")
(t/is (re-find #"(?i)could not be saved"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "invalid-data" (error-code outcome))
"the backend failure code reaches err.code"))))))))))
(t/deftest ^:async rolled-back-during-wait-rejects
(await
(with-persistence
(^:async fn [{:keys [file-id response store]}]
(await
(with-save-mocks store
(^:async fn []
(ptk/emit! store (local-commit file-id))
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
(let [p (persist/wait-for-save 5000)
_ (js/setTimeout
(fn []
(ptk/emit! store
(ptk/data-event ::dps/rolled-back
{:file-ids #{file-id}
:page-ids #{}
:shape-ids #{}})))
20)
outcome (await (await-outcome p))]
(t/is (contains? outcome :error)
"rollback during wait rejects even if status later looks saved")
(t/is (re-find #"(?i)roll"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "rolled-back" (error-code outcome)))
;; Keep the save path from hanging the fixture
(when (seq (get-in @store [:persistence :queue]))
(rx/push! response {:revn 1}))))))))))
(t/deftest ^:async buffer-race-waits-for-commit-not-stale-saved
(await
(with-persistence
(^:async fn [{:keys [file-id response requests store]}]
(await
(with-save-mocks store
(^:async fn []
(t/is (empty? (get-in @store [:persistence :buffer])))
(t/is (or (nil? (get-in @store [:persistence :status]))
(= :saved (get-in @store [:persistence :status]))))
;; Emit after starting the wait so a naive immediate empty
;; :saved resolve would succeed before the commit buffers.
(let [p (persist/wait-for-save 5000)]
(js/setTimeout
(fn [] (ptk/emit! store (local-commit file-id)))
0)
(await (async/wait-for #(seq @requests) "force-persist sent the edit"))
(rx/push! response {:revn 1})
(let [outcome (await (await-outcome p))]
(t/is (contains? outcome :ok)
"wait covers the late-buffered commit instead of stale empty :saved"))))))))))
(t/deftest ^:async pending-work-emits-force-persist
(await
(with-persistence
(^:async fn [{:keys [file-id response requests store]}]
(await
(with-save-mocks store
(^:async fn []
(ptk/emit! store (local-commit file-id))
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
(let [p (persist/wait-for-save 5000)]
(await (async/wait-for #(seq @requests) "force-persist flushed the buffer"))
(rx/push! response {:revn 1})
(let [outcome (await (await-outcome p))]
(t/is (contains? outcome :ok)
"pending work resolves once the save lands"))))))))))
(t/deftest ^:async pending-work-short-timeout-rejects
(await
(with-persistence
(^:async fn [{:keys [file-id store]}]
(await
(with-save-mocks store
(^:async fn []
(ptk/emit! store (local-commit file-id))
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
;; Never answer the save; the wait must time out.
(let [outcome (await (await-outcome (persist/wait-for-save 30)))]
(t/is (contains? outcome :error)
"pending work with no save answer rejects on timeout")
(t/is (re-find #"(?i)timed out|waiting"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "save-timeout" (error-code outcome)))))))))))
(t/deftest ^:async empty-short-timeout-resolves
(await
(with-persistence
(^:async fn [{:keys [store]}]
(await
(with-save-mocks store
(^:async fn []
;; Timeout shorter than the default 100ms intake; must still
;; resolve (capped intake), not reject as a timeout.
(let [outcome (await (await-outcome (persist/wait-for-save 5)))]
(t/is (contains? outcome :ok)
"empty short timeout resolves (nothing to save)")))))))))
(t/deftest ^:async soft-rejection-during-wait-rejects
(await
(with-persistence
(^:async fn [{:keys [file-id response requests store]}]
(await
(with-save-mocks store
(^:async fn []
(let [commit (local-commit file-id)]
(ptk/emit! store commit)
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
(let [p (persist/wait-for-save 5000)]
(await (async/wait-for #(seq @requests)
"force-persist flushed the buffer"))
(rx/push! response (thp/rejection (:id @commit)))
(let [outcome (await (await-outcome p))]
(t/is (contains? outcome :error)
"soft rejection rejects wait-for-save, not success on later :saved")
(t/is (re-find #"(?i)roll"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "rolled-back" (error-code outcome)))))))))))))
(t/deftest ^:async rollback-rejected-beats-empty-saved
(await
(with-persistence
(^:async fn [{:keys [file-id response requests store]}]
(await
(with-save-mocks store
(^:async fn []
(ptk/emit! store (local-commit file-id))
(await (async/wait-for #(seq (get-in @store [:persistence :buffer]))
"commit is buffered"))
(let [p (persist/wait-for-save 5000)]
(await (async/wait-for #(seq @requests)
"force-persist flushed the buffer"))
;; Rollback starts before settle can publish empty :saved;
;; never emit ::rolled-back (reload-delay case).
(ptk/emit! store (ptk/data-event ::dps/rollback-rejected {}))
(swap! store assoc-in [:persistence :status] :saved)
(swap! store assoc-in [:persistence :buffer] [])
(swap! store assoc-in [:persistence :queue] #queue [])
(let [outcome (await (await-outcome p))]
(t/is (contains? outcome :error)
"rollback-rejected rejects even when :saved would win the race")
(t/is (re-find #"(?i)roll"
(or (some-> (:error outcome) .-message) "")))
(t/is (= "rolled-back" (error-code outcome)))
(when (seq (get-in @store [:persistence :queue]))
(rx/push! response {:revn 1})))))))))))

View File

@ -111,6 +111,7 @@
[frontend-tests.plugins.user-test]
[frontend-tests.plugins.utils-test]
[frontend-tests.plugins.value-objects-test]
[frontend-tests.plugins.wait-for-save-test]
[frontend-tests.render-dimensions-test]
[frontend-tests.render-wasm.process-objects-test]
[frontend-tests.render-wasm.serialization-test]
@ -319,6 +320,7 @@
'frontend-tests.plugins.user-test
'frontend-tests.plugins.utils-test
'frontend-tests.plugins.value-objects-test
'frontend-tests.plugins.wait-for-save-test
'frontend-tests.render-wasm.process-objects-test
'frontend-tests.render-wasm.serialization-test
'frontend-tests.render-wasm.shape-proxy-test

View File

@ -298,7 +298,7 @@ The Penpot MCP server can be configured using environment variables.
| `PENPOT_MCP_REMOTE_MODE` | Enable remote mode (disables file system access). Set to `true` to enable. In single-user mode it does not open the server to other hosts; see `PENPOT_MCP_ALLOWED_HOSTS`. | `false` |
| `PENPOT_MCP_ALLOWED_HOSTS` | Comma-separated hostnames (no ports; IPv6 in brackets) that requests to the MCP endpoint, the plugin WebSocket and the REPL server may carry in their `Host` and `Origin` headers. Requests with any other hostname are rejected, which stops web pages from driving the server. Entries with a scheme, port or path stop the server from starting. When unset, single-user mode allows only `localhost`, `127.0.0.1` and `[::1]`, with or without remote mode, and multi-user mode allows any hostname. Set it when clients, the plugin or a proxy reach a single-user server under another name. Set it to `*` to turn the check off (not recommended in single-user mode: any web page you open can then drive the server). | (unset) |
| `PENPOT_MCP_DEVENV` | Enable Penpot development environment tools in local single-user mode. Set to `true` to enable. | `false` |
| `PENPOT_MCP_TOOL_TIMEOUT_S` | Timeout, in seconds, for tool calls dispatched to the Penpot plugin | `120` |
| `PENPOT_MCP_TOOL_TIMEOUT_S` | Timeout, in seconds, for tool calls dispatched to the Penpot plugin. `execute_code` waits up to 30s for layout and 60s for the save, so keep it above 90s plus the code's run time | `120` |
| `PENPOT_MCP_MAX_BODY_SIZE` | Maximum size of a JSON request body accepted by the MCP endpoint, in any format supported by Express (e.g. `10mb`) | `10mb` |
| `PENPOT_MCP_EXPORT_SHAPE_MAX_PARALLEL_REQUESTS` | Maximum number of parallel export shape requests (multi-user mode only). | `0` (no limit) |
| `PENPOT_MCP_AUTH_URI` | Public base URL of the MCP authorization service, e.g. `https://penpot.example/api/mcp/oauth`. Set to enable OAuth; requires `--multi-user`. Use HTTPS (HTTP is allowed on loopback for development), without credentials, query parameters, or a fragment. | (unset; OAuth disabled) |

View File

@ -0,0 +1,193 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { runInNewContext } from "node:vm";
import ts from "typescript";
import * as PenpotUtils from "./PenpotUtils.ts";
import { ExecuteCodeTaskConsole } from "./ExecuteCodeTaskConsole.ts";
type TaskResponse = {
type: string;
response: {
id: string;
success: boolean;
data?: unknown;
error?: string;
};
};
/** Compiles a TypeScript source file for a simulated plugin context. */
function compile(name: string) {
return ts.transpileModule(readFileSync(new URL(name, import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
}
/**
* Loads Task + ExecuteCodeTaskHandler with `penpot` / `penpotMgmt` resolved from
* the outer globalThis (so installPenpot can configure them before construction).
*/
function loadHandler(): { ExecuteCodeTaskHandler: any; Task: any } {
const taskExports: Record<string, unknown> = {};
const handlerExports: Record<string, unknown> = {};
const context: Record<string, unknown> = {
console,
exports: taskExports,
require: (id: string) => {
if (id === "../TaskHandler" || id.endsWith("/TaskHandler")) {
return taskExports;
}
if (id.includes("common/src")) {
return {};
}
if (id.includes("PenpotUtils")) {
return PenpotUtils;
}
if (id.includes("ExecuteCodeTaskConsole")) {
return { ExecuteCodeTaskConsole };
}
throw new Error(`Unexpected import: ${id}`);
},
};
Object.defineProperty(context, "penpot", {
enumerable: true,
get: () => (globalThis as any).penpot,
});
Object.defineProperty(context, "penpotMgmt", {
enumerable: true,
get: () => (globalThis as any).penpotMgmt,
});
runInNewContext(compile("TaskHandler.ts"), context);
context.exports = handlerExports;
runInNewContext(compile("task-handlers/ExecuteCodeTaskHandler.ts"), context);
return {
ExecuteCodeTaskHandler: handlerExports.ExecuteCodeTaskHandler,
Task: taskExports.Task,
};
}
function installPenpot(options: { waitForSave?: (() => Promise<void>) | null; workspaceStatus?: string }): {
messages: TaskResponse[];
} {
const messages: TaskResponse[] = [];
const penpot: Record<string, unknown> = {
flags: {
naturalChildOrdering: false,
throwValidationErrors: false,
},
waitForLayoutUpdate: async () => undefined,
ui: {
sendMessage: (message: TaskResponse) => {
messages.push(message);
},
},
};
if (options.waitForSave !== null && options.waitForSave !== undefined) {
penpot.waitForSave = options.waitForSave;
}
(globalThis as any).penpot = penpot;
(globalThis as any).penpotMgmt =
options.workspaceStatus === undefined ? undefined : { workspace: { status: options.workspaceStatus } };
return { messages };
}
function lastResponse(messages: TaskResponse[]) {
assert.ok(messages.length > 0, "expected a task response");
return messages[messages.length - 1].response;
}
test("awaits waitForSave before reporting success", async () => {
let resolveSave!: () => void;
let waitForSaveCalls = 0;
const saveGate = new Promise<void>((resolve) => {
resolveSave = resolve;
});
const { messages } = installPenpot({
waitForSave: async () => {
waitForSaveCalls += 1;
return saveGate;
},
});
const { ExecuteCodeTaskHandler, Task } = loadHandler();
const handler = new ExecuteCodeTaskHandler();
const task = new Task("req-1", "executeCode", { code: "return 42;" });
const done = handler.handle(task);
await new Promise((r) => setTimeout(r, 20));
assert.equal(messages.length, 0, "must not succeed before save settles");
assert.equal(waitForSaveCalls, 1, "must call waitForSave after the code runs");
resolveSave();
await done;
const response = lastResponse(messages);
assert.equal(response.success, true);
assert.equal((response.data as any).result, 42);
});
test("reports an error when waitForSave rejects", async () => {
const { messages } = installPenpot({
waitForSave: async () => {
throw new Error("Changes could not be saved");
},
});
const { ExecuteCodeTaskHandler, Task } = loadHandler();
const handler = new ExecuteCodeTaskHandler();
const task = new Task("req-2", "executeCode", { code: "return 1;" });
await assert.rejects(handler.handle(task), /could not be saved/i);
assert.equal(messages.length, 0, "must not report success");
});
test("hard-fails when waitForSave is missing", async () => {
const { messages } = installPenpot({ waitForSave: null });
const { ExecuteCodeTaskHandler, Task } = loadHandler();
const handler = new ExecuteCodeTaskHandler();
const task = new Task("req-3", "executeCode", { code: "return 1;" });
await assert.rejects(handler.handle(task), /waitForSave/);
assert.equal(messages.length, 0, "must not report success");
});
for (const workspaceStatus of ["none", "loading"]) {
test(`skips waitForSave when the workspace is ${workspaceStatus}`, async () => {
let waitForSaveCalls = 0;
const { messages } = installPenpot({
workspaceStatus,
waitForSave: async () => {
waitForSaveCalls += 1;
throw new Error("Changes could not be saved");
},
});
const { ExecuteCodeTaskHandler, Task } = loadHandler();
const handler = new ExecuteCodeTaskHandler();
const task = new Task("req-4", "executeCode", { code: "return 7;" });
await handler.handle(task);
assert.equal(waitForSaveCalls, 0, "no workspace edit can be pending");
const response = lastResponse(messages);
assert.equal(response.success, true);
assert.equal((response.data as any).result, 7);
});
}
test("awaits waitForSave when the workspace is ready", async () => {
const { messages } = installPenpot({
workspaceStatus: "ready",
waitForSave: async () => {
throw new Error("Changes could not be saved");
},
});
const { ExecuteCodeTaskHandler, Task } = loadHandler();
const handler = new ExecuteCodeTaskHandler();
const task = new Task("req-5", "executeCode", { code: "return 1;" });
await assert.rejects(handler.handle(task), /could not be saved/i);
assert.equal(messages.length, 0, "must not report success");
});

View File

@ -44,28 +44,34 @@ export class ExecuteCodeTaskHandler extends TaskHandler<ExecuteCodeTaskParams> {
// set the flags naturalChildOrdering and throwValidationErrors to true during code execution.
let originalNaturalChildOrdering: any, originalThrowValidationErrors: any;
if (penpot.flags) {
originalNaturalChildOrdering = penpot.flags.naturalChildOrdering;
penpot.flags.naturalChildOrdering = true;
originalThrowValidationErrors = penpot.flags.throwValidationErrors;
penpot.flags.throwValidationErrors = true;
} else {
if (!penpot.flags || typeof penpot.waitForSave !== "function") {
throw new Error(
"You are using a version of the Penpot MCP server which is incompatible " +
"with the connected Penpot version. " +
"The connected Penpot build is missing Plugin API support that this MCP " +
"plugin needs (for example `penpot.waitForSave`), or the MCP plugin is " +
"too new for that Penpot. Upgrade Penpot (and its plugins-runtime) so " +
"they match this MCP version. " +
"Read the documentation for instructions on which version to use: " +
"https://github.com/penpot/penpot/tree/develop/mcp\n" +
"If you are an LLM, tell the user about this!"
);
}
originalNaturalChildOrdering = penpot.flags.naturalChildOrdering;
penpot.flags.naturalChildOrdering = true;
originalThrowValidationErrors = penpot.flags.throwValidationErrors;
penpot.flags.throwValidationErrors = true;
// Layout and save waits only apply with a ready workspace: on the dashboard (or while a file
// loads) no edit of this call can be pending. Checked at each wait, since the code may navigate.
const management = this.context.penpotMgmt;
const workspaceReady = () => !management || management.workspace.status === "ready";
let result: any;
try {
// wait for layout updates prior to executing the supplied code (if method is available)
try {
const management = this.context.penpotMgmt;
// @ts-ignore - TODO Penpot.waitForLayoutUpdate is not yet in the released types
if ((!management || management.workspace.status === "ready") && penpot.waitForLayoutUpdate) {
if (workspaceReady() && penpot.waitForLayoutUpdate) {
// @ts-ignore
await penpot.waitForLayoutUpdate();
}
@ -93,6 +99,11 @@ export class ExecuteCodeTaskHandler extends TaskHandler<ExecuteCodeTaskParams> {
result = ExecuteCodeTaskHandler.encodeBytesAsBase64Envelope(result);
}
// Wait for the save outside any swallow catch: a failed or rolled-back save must fail the task.
if (workspaceReady()) {
await penpot.waitForSave();
}
// return result and captured log
let resultData: ExecuteCodeTaskResultData<any> = {
result: result,

View File

@ -87,6 +87,7 @@ Penpot:
flatten(shapes: Shape[]): Path[];
createVariantFromComponents(shapes: Board[]): VariantContainer;
waitForLayoutUpdate(timeout?: number): Promise<void>;
waitForSave(timeout?: number): Promise<void>;
}
```
@ -354,6 +355,7 @@ Penpot:
* themechange: event emitted when the user changes its theme. The callback will receive the new theme (currently: either `dark` or `light`)
* filechange: event emitted when a different file is opened. The callback will receive the new file.
* contentsave: event emitted after the file content is saved in the backend. The callback receives no arguments.
* contentrollback: event emitted after the backend rejected some changes and they were undone in the workspace. The callback receives a `ContentRollback` with the files, pages and shapes affected.
* finish: event emitted when the current file is closed. The callback will receive the id of the closed file.
Type Parameters
@ -1041,6 +1043,33 @@ Penpot:
The promise to be resolved when the layout is updated. It is
rejected with an Error, both on timeout and on an invalid timeout value.
waitForSave: |-
```
waitForSave(timeout?: number): Promise<void>
```
This method returns a promise that will be resolved when pending file
changes have been saved to the backend, or when there is nothing to save.
It force-flushes the persistence buffer first when work is pending.
Parameters
* timeout: number
Maximum time to wait, in milliseconds. If the timeout
elapses before the save settles, the promise is rejected. Defaults to
60000; the promise never waits indefinitely.
Returns Promise<void>
The promise to be resolved when the save has settled. It is
rejected with an Error on save failure, when changes are rolled back
during the wait, on timeout, or on an invalid timeout value. A save
that failed before the call also rejects: with `save-retrying` while
Penpot keeps retrying it, otherwise with the failure code until the
file is reopened. The Error `code` property tells the cases apart:
`save-timeout`, `rolled-back`, `save-retrying`, or the failure code
(`save-failed` unless the backend gave a more specific one).
ActiveUser:
overview: |-
Interface ActiveUser
@ -5365,7 +5394,8 @@ Team:
Example
```
const [team] = await penpotMgmt.listTeams();const projects = await team.listProjects();
const [team] = await penpotMgmt.listTeams();
const projects = await team.listProjects();
```
listDeletedProjects: |-
```
@ -5519,7 +5549,8 @@ Project:
Example
```
const file = await project.createFile({ name: 'Login' });await file.open();
const file = await project.createFile({ name: 'Login' });
await file.open();
```
duplicate: |-
```
@ -5585,7 +5616,7 @@ ProjectFile:
}
```
Referenced by: PenpotMgmt, Project, ProjectFile
Referenced by: PenpotMgmt, Project, ProjectFile, Team
members:
Properties:
id: |-
@ -5814,7 +5845,8 @@ PenpotMgmt:
Example
```
const file = await penpotMgmt.getFile(penpotMgmt.workspace.fileId!);file.name = 'Checkout';
const file = await penpotMgmt.getFile(penpotMgmt.workspace.fileId!);
file.name = 'Checkout';
```
openFile: |-
```
@ -5940,6 +5972,7 @@ Context:
flatten(shapes: Shape[]): Path[];
createVariantFromComponents(shapes: Board[]): VariantContainer;
waitForLayoutUpdate(timeout?: number): Promise<void>;
waitForSave(timeout?: number): Promise<void>;
}
```
members:
@ -6793,6 +6826,33 @@ Context:
The promise to be resolved when the layout is updated. It is
rejected with an Error, both on timeout and on an invalid timeout value.
waitForSave: |-
```
waitForSave(timeout?: number): Promise<void>
```
This method returns a promise that will be resolved when pending file
changes have been saved to the backend, or when there is nothing to save.
It force-flushes the persistence buffer first when work is pending.
Parameters
* timeout: number
Maximum time to wait, in milliseconds. If the timeout
elapses before the save settles, the promise is rejected. Defaults to
60000; the promise never waits indefinitely.
Returns Promise<void>
The promise to be resolved when the save has settled. It is
rejected with an Error on save failure, when changes are rolled back
during the wait, on timeout, or on an invalid timeout value. A save
that failed before the call also rejects: with `save-retrying` while
Penpot keeps retrying it, otherwise with the failure code until the
file is reopened. The Error `code` property tells the cases apart:
`save-timeout`, `rolled-back`, `save-retrying`, or the failure code
(`save-failed` unless the backend gave a more specific one).
ContextGeometryUtils:
overview: |-
Interface ContextGeometryUtils
@ -8162,6 +8222,7 @@ EventsMap:
finish: string;
shapechange: Shape;
contentsave: void;
contentrollback: ContentRollback;
}
```
@ -8222,6 +8283,56 @@ EventsMap:
```
The `contentsave` event will trigger after the file content is saved in the backend.
contentrollback: |-
```
readonly contentrollback: ContentRollback
```
The `contentrollback` event will trigger after the backend rejected some changes
and the workspace undid them, together with the rest of their undo steps and any
later change to the same file. Changes made by a plugin can be undone this way
after the call that made them returned, so a plugin that relies on them should
read the affected shapes again. The event fires once the undone data is in the
workspace. When the workspace could not undo the changes in place, it reloads the
file from the server first; the whole file then holds the server data, so shapes
outside the listed ones may have changed too.
ContentRollback:
overview: |-
Interface ContentRollback
=========================
What a rollback of rejected changes undid, as given to the `contentrollback` event.
```
interface ContentRollback {
fileIds: string[];
pageIds: string[];
shapeIds: string[];
}
```
Referenced by: EventsMap
members:
Properties:
fileIds: |-
```
readonly fileIds: string[]
```
Ids of the files that lost changes.
pageIds: |-
```
readonly pageIds: string[]
```
Ids of the pages the undone changes touched.
shapeIds: |-
```
readonly shapeIds: string[]
```
Ids of the page shapes the undone changes touched. A shape the undone changes
created no longer exists; one they removed exists again.
Export:
overview: |-
Interface Export

View File

@ -25,13 +25,21 @@ before trying to observe changes.
To wait only for a single shape (and its children), use `await shape.waitForLayoutUpdate();`.
Both accept an optional timeout in milliseconds (default 30000) and reject when it elapses.
Every `execute_code` call waits for updates before applying your code, so you never need to call `waitForLayoutUpdate` at the beginning of your code.
Every `execute_code` call also waits for pending changes to be saved before it returns success, so you should not call
`await penpot.waitForSave()` at the end of your code (that would wait twice).
That automatic save wait defaults to 60s and runs after the automatic layout wait (default 30s); both, plus your code,
must fit inside the MCP tool timeout (`PENPOT_MCP_TOOL_TIMEOUT_S`, default 120s). If layout or saves are slow and tools
time out before a save error appears, raise that env var.
## Rejected Changes and Read-Only Mode
Penpot saves your changes to the backend after your `execute_code` call returns.
When the backend rejects a save, Penpot undoes the rejected changes, together with the rest of their undo steps
and any later change to the same file. This can happen a few seconds after the call that made the changes succeeded.
The next tool response then starts with a warning that names the files, pages and shapes involved.
`execute_code` only reports success after Penpot has saved the changes from that call (or confirmed there was nothing
to save). If the save fails, times out, or the backend rejects the changes and the workspace rolls them back, the tool
call fails with an error — do not treat a failed call as if the design was updated.
A timeout while saves are still retrying means the save was not confirmed; it does not mean the file is fine.
When a rollback is reported only on a later tool response (rare: concurrent edits, or a race after a timed-out response),
that response starts with a warning that names the files, pages and shapes involved.
When you get this warning:
* Do not trust what you know about the design from before: shapes you created may be gone, and removed ones may be back.
* Read the affected pages and shapes again (e.g. `penpotUtils.shapeStructure(page.root, 3)`) and check that they hold what you expect.
@ -39,6 +47,11 @@ When you get this warning:
While saves are failing, the workspace becomes read-only: every write through the API throws an error saying that the
workspace is read-only because changes cannot be saved. Do not retry in a loop; wait and try again later, or tell the user.
Once a save has failed for good, every `execute_code` call in that file fails with "Changes could not be saved", reads
included, until the file is reopened. Tell the user to reopen the file. If the error says Penpot keeps retrying the
saves, wait and try again later instead. Calls made from the dashboard do not wait for saves.
A save failure does not undo `penpotMgmt` calls (projects, files, teams) made in the same code: read that state back
before retrying them.
Writes also throw when the user cannot edit the file, a version is being previewed or the canvas stopped rendering;
the error says which. These do not pass by waiting: tell the user.

View File

@ -2,12 +2,14 @@
### 🚀 Features
- **plugin-types, plugins-runtime:** Added `penpot.waitForSave(timeout?)` to wait until pending file changes are saved (or there is nothing to save). Rejects on save failure, rollback during the wait, timeout (default 60000 ms), or an invalid timeout. The Error `code` property is `save-timeout`, `rolled-back`, `save-retrying` (an earlier failed save Penpot keeps retrying) or the save failure code.
- **plugin-types, plugins-runtime:** `penpotMgmt` returns `Team`, `Project` and `ProjectFile` objects. Assigning `name` renames teams, projects and files, `project.pinned` pins a project and `file.shared` shares a file as a team library; `createProject`, `createFile`, `moveTo`, `duplicate`, `remove` and `restore` live on the objects. Added `penpotMgmt.listTeams`, `penpotMgmt.createTeam`, `penpotMgmt.getFile`, `listDeletedProjects` and `listDeletedFiles`, and the `manage:projects`, `manage:teams` and `manage:delete` permissions. Restoration uses the dashboard's Trash operation; projects need recoverable files and empty projects cannot be restored; the API exposes no permanent deletion method. Team deletion is not exposed.
- **plugins-runtime, plugin-types**: Added global plugins (`scope: "global"`) that remain active across dashboard and workspace navigation until closed or logged out, with `penpotMgmt` for project and file discovery, file navigation and workspace events. Global scope adds the `allow:global` permission, which users must accept when installing the plugin.
- **plugin-types:** Added the `contentrollback` event and the `ContentRollback` type. The event fires after the backend rejected some changes and the workspace undid them, with the ids of the files, pages and shapes affected. It fires once the undone data is in the workspace, also when the workspace has to reload the file to undo the changes.
### 🩹 Fixes
- **plugins-runtime:** Methods that rejected an invalid value with a plain string (`connectLibrary`, file `restore`, `remove`, `pin`, `export`, `findVersions`, `saveVersion`) now reject with an `Error` carrying the same message.
- **plugin-runtime:** `LibraryComponent.instance()`, `createShapeFromSvg()` and `createShapeFromSvgWithImages()` now create shapes at the page root instead of inside a board at the page origin. Closes #12086.
- **plugin-types, plugin-runtime:** Dashboard property setters now update values after backend success and log failures without interrupting the workspace. File moves reject projects in other teams, backend rejections include their type and code, and `project.fileCount` stays at its listing snapshot. Duplicated projects include their file count and pinned state.
- **plugin-runtime:** Cancel plugin loads before they execute after unloading or logout, and allow reopening plugins that close during startup.

View File

@ -74,6 +74,7 @@
"verticalPadding",
"verticalSizing"
],
"ContentRollback": ["fileIds", "pageIds", "shapeIds"],
"Context": [
"activeUsers",
"alignHorizontal",
@ -115,7 +116,8 @@
"uploadMediaUrl",
"version",
"viewport",
"waitForLayoutUpdate"
"waitForLayoutUpdate",
"waitForSave"
],
"ContextGeometryUtils": ["center"],
"ContextTypesUtils": [
@ -135,6 +137,7 @@
"Dissolve": ["duration", "easing", "type"],
"Ellipse": ["fills", "type"],
"EventsMap": [
"contentrollback",
"contentsave",
"filechange",
"finish",
@ -376,6 +379,8 @@
"PenpotMgmt": [
"createTeam",
"getFile",
"listDeletedFiles",
"listDeletedProjects",
"listProjects",
"listTeams",
"off",
@ -399,11 +404,13 @@
"fileCount",
"id",
"isDefault",
"listDeletedFiles",
"listFiles",
"moveTo",
"name",
"pinned",
"remove",
"restore",
"teamId"
],
"ProjectFile": [
@ -415,6 +422,7 @@
"open",
"projectId",
"remove",
"restore",
"shared",
"teamId"
],
@ -528,9 +536,10 @@
"createProject",
"id",
"isDefault",
"listDeletedFiles",
"listDeletedProjects",
"listProjects",
"name",
"remove"
"name"
],
"Text": [
"align",
@ -2145,6 +2154,26 @@
"array": false
}
},
"ContentRollback": {
"fileIds": {
"decl": "ContentRollback",
"kind": "get",
"type": null,
"array": true
},
"pageIds": {
"decl": "ContentRollback",
"kind": "get",
"type": null,
"array": true
},
"shapeIds": {
"decl": "ContentRollback",
"kind": "get",
"type": null,
"array": true
}
},
"Context": {
"management": {
"decl": "Context",
@ -2409,6 +2438,12 @@
"kind": "method",
"type": null,
"array": false
},
"waitForSave": {
"decl": "Context",
"kind": "method",
"type": null,
"array": false
}
},
"ContextGeometryUtils": {
@ -3045,6 +3080,12 @@
"kind": "get",
"type": null,
"array": false
},
"contentrollback": {
"decl": "EventsMap",
"kind": "get",
"type": "ContentRollback",
"array": false
}
},
"Export": {
@ -6843,6 +6884,12 @@
"kind": "method",
"type": null,
"array": false
},
"waitForSave": {
"decl": "Context",
"kind": "method",
"type": null,
"array": false
}
},
"PenpotMgmt": {
@ -6870,6 +6917,18 @@
"type": "Project",
"array": true
},
"listDeletedProjects": {
"decl": "PenpotMgmt",
"kind": "method",
"type": "Project",
"array": true
},
"listDeletedFiles": {
"decl": "PenpotMgmt",
"kind": "method",
"type": "ProjectFile",
"array": true
},
"getFile": {
"decl": "PenpotMgmt",
"kind": "method",
@ -6998,6 +7057,18 @@
"type": "ProjectFile",
"array": true
},
"listDeletedFiles": {
"decl": "Project",
"kind": "method",
"type": "ProjectFile",
"array": true
},
"restore": {
"decl": "Project",
"kind": "method",
"type": null,
"array": false
},
"createFile": {
"decl": "Project",
"kind": "method",
@ -7066,6 +7137,12 @@
"type": null,
"array": false
},
"restore": {
"decl": "ProjectFile",
"kind": "method",
"type": null,
"array": false
},
"moveTo": {
"decl": "ProjectFile",
"kind": "method",
@ -8752,17 +8829,23 @@
"type": "Project",
"array": true
},
"listDeletedProjects": {
"decl": "Team",
"kind": "method",
"type": "Project",
"array": true
},
"listDeletedFiles": {
"decl": "Team",
"kind": "method",
"type": "ProjectFile",
"array": true
},
"createProject": {
"decl": "Team",
"kind": "method",
"type": "Project",
"array": false
},
"remove": {
"decl": "Team",
"kind": "method",
"type": null,
"array": false
}
},
"Text": {

View File

@ -0,0 +1,40 @@
import { expect, expectReject } from '../framework/expect';
import { describe, test } from '../framework/registry';
// waitForSave: resolves once the pending file changes are saved, or when
// there is nothing to save. It waits on the shared persistence queue, so the
// edits of earlier tests may be in flight too; each test only asserts what
// holds whatever else is queued.
describe('WaitForSave', () => {
test('resolves after an edit is saved', async (ctx) => {
const r = ctx.penpot.createRectangle();
ctx.board.appendChild(r);
r.name = 'wait-save-probe';
const value = await ctx.penpot.waitForSave();
expect(value).toBeUndefined();
expect(r.name).toBe('wait-save-probe');
});
test('resolves when there is nothing to save', async (ctx) => {
await ctx.penpot.waitForSave();
await ctx.penpot.waitForSave(5000);
});
test('rejects an invalid timeout with an Error', async (ctx) => {
for (const value of [
-1,
0,
Number.NaN,
Number.POSITIVE_INFINITY,
2 ** 31,
]) {
const p = ctx.penpot.waitForSave(value);
expect(p instanceof Promise).toBe(true);
await expectReject(p, /not valid/);
const error = await p.catch((e: unknown) => e);
expect(error instanceof Error).toBe(true);
}
});
});

View File

@ -1630,6 +1630,24 @@ export interface Context {
* rejected with an Error, both on timeout and on an invalid timeout value.
*/
waitForLayoutUpdate(timeout?: number): Promise<void>;
/**
* This method returns a promise that will be resolved when pending file
* changes have been saved to the backend, or when there is nothing to save.
* It force-flushes the persistence buffer first when work is pending.
* @param timeout Maximum time to wait, in milliseconds. If the timeout
* elapses before the save settles, the promise is rejected. Defaults to
* 60000; the promise never waits indefinitely.
* @return The promise to be resolved when the save has settled. It is
* rejected with an Error on save failure, when changes are rolled back
* during the wait, on timeout, or on an invalid timeout value. A save
* that failed before the call also rejects: with `save-retrying` while
* Penpot keeps retrying it, otherwise with the failure code until the
* file is reopened. The Error `code` property tells the cases apart:
* `save-timeout`, `rolled-back`, `save-retrying`, or the failure code
* (`save-failed` unless the backend gave a more specific one).
*/
waitForSave(timeout?: number): Promise<void>;
}
/**

View File

@ -413,6 +413,11 @@ export function createApi(
checkPermission('content:read');
return plugin.context.waitForLayoutUpdate(timeout);
},
waitForSave(timeout?: number): Promise<void> {
checkPermission('content:read');
return plugin.context.waitForSave(timeout);
},
};
const penpotMgmt: PenpotMgmt = {

View File

@ -37,6 +37,8 @@ describe('Plugin api', () => {
theme: 'dark',
addListener: vi.fn().mockReturnValueOnce(Symbol()),
removeListener: vi.fn(),
waitForSave: vi.fn().mockResolvedValue(undefined),
waitForLayoutUpdate: vi.fn().mockResolvedValue(undefined),
},
};
}
@ -186,6 +188,30 @@ describe('Plugin api', () => {
});
});
describe('waitForSave', () => {
it('forwards to plugin.context.waitForSave', async () => {
await expect(api.penpot.waitForSave(1234)).resolves.toBeUndefined();
expect(pluginManager.context.waitForSave).toHaveBeenCalledWith(1234);
});
it('requires content:read', () => {
const waitForSave = vi.fn().mockResolvedValue(undefined);
const { penpot } = createApi({
...pluginManager,
manifest: {
...pluginManager.manifest,
permissions: [],
},
context: { ...pluginManager.context, waitForSave },
} as any);
expect(() => penpot.waitForSave(100)).toThrow(
'Permission content:read is not granted',
);
expect(waitForSave).not.toHaveBeenCalled();
});
});
describe('ui', () => {
describe.concurrent('permissions', () => {
const api = createApi({