mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
📚 Organize frontend memories by task
Route readers to focused notes for workspace changes, app shell behavior, testing, and diagnostics. Keep cross-file constraints and reference the code for implementation details. Replace conflicting debug recipes and retain old memory paths where local plans still use them. AI-assisted-by: gpt-6.2-sol
This commit is contained in:
parent
8f2405bb8d
commit
e23901a36f
@ -61,8 +61,6 @@ This is a monorepo. Principles that apply to one module do *not* generally apply
|
||||
- Before automating or inspecting Penpot designs through the Plugin API, call the Penpot MCP `high_level_overview` tool.
|
||||
- connection between the JavaScript plugin API and the ClojureScript code: `mem:frontend/plugin-api-to-cljs-binding`.
|
||||
- executing ClojureScript code in the frontend: `mem:frontend/cljs-repl`.
|
||||
- handling Clojure compiler errors, runtime patching and debug helpers: `mem:frontend/handling-errors-and-debugging`.
|
||||
- Failed ClojureScript build or stale hot reload: `mem:frontend/compile-diagnostics`.
|
||||
|
||||
## Detecting Crashes
|
||||
|
||||
The Penpot frontend can crash silently from the JS API's perspective: `execute_code` calls return successfully, but 1-2s later the workspace becomes unusable (Internal Error page). The `execute_code` tool then stops working, but `cljs_repl` still works. Use it to detect a crash via `(some? (:exception @app.main.store/state))`. For details on handling crashes, read memory `mem:frontend/handling-crashes`.
|
||||
- Successful `execute_code` followed by Internal Error: `mem:frontend/handling-crashes` for delayed failures, store inspection and recovery.
|
||||
|
||||
@ -22,7 +22,7 @@ Component instance shapes carry `:component-id` and `:component-file` directly;
|
||||
|
||||
## Navigation recipe
|
||||
|
||||
To programmatically open a workspace file, all three ids are required:
|
||||
To open a specific workspace file and page from the REPL, pass their IDs and the team explicitly. If omitted the event can fall back to the current workspace, which may not be the one you intend to inspect:
|
||||
|
||||
```clojure
|
||||
(do (require '[app.main.data.common :as dcm])
|
||||
@ -66,36 +66,23 @@ Some frontend vars are deliberately mutable escape hatches for runtime instrumen
|
||||
|
||||
`cljs_repl` starts every call in `cljs.user`; begin a call with `(in-ns 'my-ns)` to reuse helpers defined in another namespace.
|
||||
|
||||
`app.main.repo/cmd!` is a multimethod. For a temporary RPC spy, wrap its default method for the target command and remove your method afterward; do not replace the var or its arity property.
|
||||
|
||||
Restore mutable hooks after debugging, or reload the frontend. Use JVM `alter-var-root` only for JVM Clojure; it is not the normal way to patch live CLJS browser vars.
|
||||
|
||||
## Browser-console debug namespace
|
||||
|
||||
In development, the JS console exposes `debug` helpers from `frontend/src/debug.cljs`:
|
||||
|
||||
```javascript
|
||||
debug.set_logging("namespace", "debug");
|
||||
debug.dump_state();
|
||||
debug.dump_buffer();
|
||||
debug.get_state(":workspace-local :selected");
|
||||
debug.dump_objects();
|
||||
debug.dump_object("Rect-1");
|
||||
debug.dump_selected();
|
||||
debug.dump_tree(true, true);
|
||||
```
|
||||
|
||||
Visual workspace debug overlays can be toggled with `debug.toggle_debug("bounding-boxes")`, `"group"`, `"events"`, or `"rotation-handler"`; `debug.debug_all()` and `debug.debug_none()` toggle all visual aids.
|
||||
|
||||
For temporary source traces, prefer existing logging (`app.common.logging` / `app.util.logging`) or short-lived `prn`, `app.common.pprint/pprint`, `js/console.log`, or `js-debugger` calls. Remove temporary source instrumentation before committing.
|
||||
Development builds expose the `debug` JS namespace. Read `frontend/src/debug.cljs` for the current commands and overlays. Remove temporary source traces before committing.
|
||||
|
||||
## Runtime targeting
|
||||
|
||||
`cljs_repl` may connect to the wrong runtime when several are attached, such as workspace plus rasterizer. Verify with `(.-title js/document)`; it should show the workspace file name, not "Penpot - Rasterizer".
|
||||
|
||||
To list or target shadow-cljs runtimes, run from `/home/penpot/penpot/frontend`:
|
||||
To list or target shadow-cljs runtimes, run from `frontend/`:
|
||||
|
||||
```bash
|
||||
printf '(shadow.cljs.devtools.api/repl-runtimes :main)\n' | timeout 10 npx shadow-cljs clj-eval --stdin
|
||||
printf '(shadow.cljs.devtools.api/cljs-eval :main "<cljs-code>" {:client-id 5})\n' | timeout 10 npx shadow-cljs clj-eval --stdin
|
||||
```
|
||||
|
||||
Use command timeouts so a disconnected browser does not hang the session.
|
||||
Use command timeouts so a disconnected browser does not hang the session.
|
||||
|
||||
@ -1,32 +1,6 @@
|
||||
# Frontend Compile Diagnostics
|
||||
# Frontend compile diagnostics
|
||||
|
||||
Separate from runtime crash recovery.
|
||||
|
||||
## First check the shadow-cljs build
|
||||
|
||||
Use the Penpot MCP `cljs_compiler_output` tool to inspect the latest shadow-cljs `:main` build status. This is the fastest way to distinguish a bad build from a runtime error in the browser.
|
||||
|
||||
Recommended order after CLJ/CLJC/CLJS source edits:
|
||||
1. Run `cljs_compiler_output`.
|
||||
2. If the compiler reports a Clojure syntax problem, especially unmatched delimiters or a confusing location, run `clj_check_parentheses` on the absolute path of the suspect `.clj`, `.cljc`, or `.cljs` file.
|
||||
3. After the build is healthy, use `mem:frontend/cljs-repl`, browser tools, or runtime crash checks for behavior.
|
||||
|
||||
## Parentheses checker
|
||||
|
||||
`clj_check_parentheses` analyzes one Clojure/ClojureScript source file and reports the area likely responsible for unclosed parentheses/brackets/braces. Use it when compiler output points near EOF, points at a misleading later form, or says delimiter-related syntax errors.
|
||||
|
||||
## Test build warnings
|
||||
|
||||
`clojure -M:dev:shadow-cljs compile test` (from `frontend/`) is the compile that
|
||||
prints the analyzer warnings CI reports. Warnings are printed only for the
|
||||
namespaces the compiler actually recompiles, so a cached build reports none
|
||||
while old ones are still latent: force it with
|
||||
`find test -name '*.cljs' -exec touch {} +` (or by clearing
|
||||
`.shadow-cljs/builds/test`) before claiming a clean tree. Why `:fn-arity`
|
||||
cannot be ignored: `mem:frontend/testing`.
|
||||
|
||||
## Hot reload notes
|
||||
|
||||
When the frontend shadow-cljs watch process is running, edits to CLJC files in `common/` are normally recompiled into the browser automatically. Do not restart the frontend before checking `cljs_compiler_output`; stale behavior is often a failed build.
|
||||
|
||||
For production/minified stack traces, build the production bundle from `frontend/` with `pnpm run build:app`. Output and source maps are generated under `frontend/resources/public/js`; inspect source maps or shadow-cljs reports using build ids from `shadow-cljs.edn`.
|
||||
- Diagnose the `:main` shadow-cljs build before restarting the app or treating stale behavior as a runtime bug. Read the watch output or use Penpot MCP `cljs_compiler_output` if available. `common/` CLJC changes normally recompile through the same watch.
|
||||
- A delimiter error can point to a later form or EOF. Repair the affected file before linting: `mem:scripts/paren-repair`. Penpot MCP `clj_check_parentheses`, if available, can help locate the mismatch.
|
||||
- From `frontend/`, `clojure -M:dev:shadow-cljs compile test` reports analyzer warnings only for namespaces it recompiles. A warm incremental run with no warnings is not evidence that old warnings are gone; use a fresh test build cache to verify the whole target. Treat `:fn-arity` as a defect; see `mem:frontend/testing-unit`.
|
||||
- If the build succeeds but the browser still fails, use `mem:frontend/cljs-repl` or `mem:frontend/handling-crashes`. For minified stacks, consult the release targets and source-map settings in `frontend/shadow-cljs.edn` and the build commands in `frontend/package.json`.
|
||||
|
||||
@ -1,64 +1,33 @@
|
||||
# Frontend Architecture and Workflow
|
||||
# Frontend
|
||||
|
||||
Frontend: CLJS SPA; React/Rumext; Potok; RxJS; okulary refs; SCSS modules; shared `common/`; JS/TS workspace packages.
|
||||
Start at `app.main.ui` for Rumext components, `app.main.data` for Potok events, and `app.main.refs` for derived state. Shared model rules live in `mem:common/core`.
|
||||
|
||||
## Stable namespace map
|
||||
## UI and integration
|
||||
|
||||
- `app.main.ui.*`: Rumext/React UI components for workspace, dashboard, viewer, settings, auth, nitrate, etc.
|
||||
- `app.main.data.*`: Potok event handlers and side effects.
|
||||
- `app.main.refs`: reactive refs/lenses over store and derived workspace data.
|
||||
- `app.main.store`: Potok store and `emit!`.
|
||||
- `app.plugins.*` and `app.plugins`: CLJS implementation of Plugin JS API proxies.
|
||||
- `app.render_wasm.*`: frontend bridge to Rust/WASM renderer.
|
||||
- `app.util.*`: DOM, HTTP, i18n, keyboard, codegen, and general frontend utilities.
|
||||
- `frontend/packages/*` and `frontend/text-editor`: JS/TS workspace packages consumed by the app.
|
||||
- Nitrate subscription/organization UI and flows live under `app.main.data.nitrate` and `app.main.ui.nitrate*`; backend/API behavior is covered by backend memories, and shared organization permission rules (`allowed?`, `can-send-invitations?`) are in `common/src/app/common/types/organization.cljc`.
|
||||
- `app.config` external bridges (`external-feature-flag`, `external-session-id`, `external-context-info`, `external-notify-register-success`, `initialize-external-context-info`, `add-event-callback` / `get-event-callbacks` via `penpotEventCallbacks` + `penpotAddEventCallback`) delegate to `globalThis` hooks injected by the SaaS host. Never delete `external-feature-flag`, even with zero call sites: it is the seam for future A/B tests. Frontend audit events are forwarded to named host callbacks from `app.main.data.event` after `make-event` (vendor-agnostic; no analytics SDK in Penpot). `resources/js/event-callbacks.js` is copied to `public/js/` and loaded in `index.mustache` **before** `config.js` so hosts can call `penpotAddEventCallback` at config parse time.
|
||||
- CLJS components, Design System, SCSS modules, accessibility and render cost: `mem:frontend/ui-conventions-and-style-system`.
|
||||
- JS/TS packages, shared React UI, Storybook and text editor boundaries: `mem:frontend/ui-packages-text-editor-workflow`.
|
||||
- PO files and locale conventions: `mem:frontend/translations`.
|
||||
- JS Plugin API bindings and proxies: `mem:frontend/plugin-api-to-cljs-binding`. External SaaS hooks and script load order: `mem:frontend/host-integration`.
|
||||
|
||||
## Workspace
|
||||
|
||||
## Lint and Format
|
||||
- Store, refs, and interaction streams: `mem:frontend/workspace-store`.
|
||||
- Local and remote commits, rebase, and undo: `mem:frontend/workspace-commits`.
|
||||
- Save queue, rejected edits, retries, and recovery: `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
- Modifier previews, transform commits, and WASM bridge: `mem:frontend/workspace-transform-subtleties`.
|
||||
- Token application and propagation: `mem:frontend/workspace-token-subtleties`; token model: `mem:common/tokens-schema-subtleties`.
|
||||
|
||||
From `frontend/`:
|
||||
## App shell
|
||||
|
||||
- CLJ/CLJS lint: `pnpm run lint:clj`.
|
||||
- JS lint currently no-ops via `pnpm run lint:js`.
|
||||
- SCSS lint: `pnpm run lint:scss`.
|
||||
- Format checks: `pnpm run check-fmt:clj`, `pnpm run check-fmt:js`, `pnpm run check-fmt:scss`.
|
||||
- Format fix: `pnpm run fmt`, or targeted `fmt:clj` / `fmt:js` / `fmt:scss`. After running `fmt:*`, `check-fmt:*` is redundant.
|
||||
- Translation formatting after i18n edits: `pnpm run translations`.
|
||||
- Router, history, SSO destinations and team context: `mem:frontend/routing-app-shell-subtleties`.
|
||||
- Authentication event sources and invitations: `mem:frontend/auth-events`.
|
||||
- Error boundary, transport errors and reports: `mem:frontend/error-reporting`.
|
||||
- WebSocket lifetime, membership revocation, and job progress: `mem:frontend/websocket-notifications`.
|
||||
- Dashboard and viewer behavior: `mem:frontend/dashboard-viewer-subtleties`.
|
||||
|
||||
**Before linting:** if delimiter errors are suspected (after LLM edits, or
|
||||
lint/compiler reports syntax errors), run `scripts/paren-repair` on the
|
||||
affected files first. Delimiter errors produce misleading linter output.
|
||||
See `mem:scripts/paren-repair`.
|
||||
## Testing and diagnosis
|
||||
|
||||
## Focused memory routing
|
||||
|
||||
UI and packages:
|
||||
- App UI components, SCSS modules, style-system boundaries, accessibility, i18n, and render performance: `mem:frontend/ui-conventions-and-style-system`.
|
||||
- JS/TS packages, shared UI package, text editor, Storybook, and package builds: `mem:frontend/ui-packages-text-editor-workflow`.
|
||||
- PO translation workflow and per-locale conventions: `mem:frontend/translations`.
|
||||
|
||||
Workspace behavior:
|
||||
- Workspace state, commits, persistence, undo, repo calls, and refs: `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
- Workspace transforms, modifier previews, WASM modifier integration, and transform commits: `mem:frontend/workspace-transform-subtleties`.
|
||||
- Workspace token application/propagation: `mem:frontend/workspace-token-subtleties`; shared token data/schema: `mem:common/tokens-schema-subtleties`.
|
||||
|
||||
App shell and product flows:
|
||||
- Routing, root app shell, websocket, and global errors: `mem:frontend/routing-app-shell-subtleties`.
|
||||
- Authentication events, the session origin vocabulary, and the invitation flow: `mem:frontend/auth-events`.
|
||||
- Dashboard and viewer flows: `mem:frontend/dashboard-viewer-subtleties`.
|
||||
- Plugin JS API runtime inside the frontend app: `mem:frontend/plugin-api-to-cljs-binding`.
|
||||
|
||||
Diagnostics and validation:
|
||||
- Runtime inspection and navigation: `mem:frontend/cljs-repl`.
|
||||
- Source-edit compile/hot-reload diagnostics: `mem:frontend/compile-diagnostics`.
|
||||
- Runtime crash recovery: `mem:frontend/handling-crashes`.
|
||||
- Tests and live verification: `mem:frontend/testing`.
|
||||
- CI end-to-end workflow (build-once frontend bundle, check names): `mem:frontend/e2e-ci-workflow`.
|
||||
- Cross-cutting testing principles and anti-patterns: `mem:testing`.
|
||||
- Real pointer/keyboard gesture reproduction: `mem:frontend/playwright-gestures`.
|
||||
|
||||
## Areas without focused memories
|
||||
|
||||
These frontend areas currently have no dedicated Serena memory beyond this architecture entry and nearby source/tests: clipboard, drawing tools, boolean/path operations, interactions/prototyping, color/style asset management, grid-layout editing UI, comments UI, fonts UI, and many dashboard/settings subflows. Treat work there as less memory-covered and inspect source/tests more carefully.
|
||||
- Choose the frontend test suite: `mem:frontend/testing`. Run `./scripts/ci frontend` from the repo root for lint, unit tests and format; see `mem:scripts/ci`.
|
||||
- Failed compile, stale hot reload, or compiler warnings: `mem:frontend/compile-diagnostics`.
|
||||
- Inspect the live browser, navigate or observe events: `mem:frontend/cljs-repl`. For delayed Internal Error pages, see `mem:frontend/handling-crashes`.
|
||||
- Real pointer or keyboard input: `mem:frontend/playwright-gestures`.
|
||||
|
||||
@ -1,43 +1,7 @@
|
||||
# E2E CI workflow (build-once frontend bundle)
|
||||
# E2E CI bundle contract
|
||||
|
||||
`.github/workflows/tests-e2e.yml` ("CI: E2E") is the single workflow for every
|
||||
suite that drives a real frontend bundle:
|
||||
|
||||
- `Integration Tests` — Playwright specs under `frontend/playwright` (sharded).
|
||||
- `Run composable test suite (mocked backend)` — `mem:frontend/composable-component-tests`.
|
||||
- `Run Plugin API Test Suite (mocked)` — `plugins/apps/plugin-api-test-suite`.
|
||||
|
||||
Triggers: PR/push touching `frontend/**`, `common/**`, `render-wasm/**`,
|
||||
`plugins/**` (or the workflow file), plus `workflow_dispatch` (integration only).
|
||||
A `plugins/**` change runs the whole set on purpose: the bundle embeds the
|
||||
built plugins.
|
||||
|
||||
## Invariants
|
||||
|
||||
- ONE `frontend/scripts/build` per SHA. The `build-bundle` job restores
|
||||
`actions/cache` key `frontend-bundle-<sha>`, builds only on a miss, and saves
|
||||
the key before the job ends. A re-run of the same SHA reuses the cache.
|
||||
- Consumer jobs (`needs: build-bundle`) restore the same key with
|
||||
`fail-on-cache-miss: true` and NEVER run `frontend/scripts/build`.
|
||||
- The bundle is `frontend/resources/public`. The integration specs serve it
|
||||
with `frontend/scripts/e2e-server.js`; each mocked plugin driver serves it
|
||||
with its own zero-dependency `ci/static-server.ts` (duplicated in both
|
||||
suites — keep the copies in sync).
|
||||
- Mocked plugin jobs install only `plugins/` deps, so their drivers must not
|
||||
import anything from `frontend/node_modules` at runtime (e.g. no
|
||||
`frontend/scripts/e2e-server.js`, which needs `express`).
|
||||
- Cache key comes from `git rev-parse HEAD` (the checked-out ref), not
|
||||
`github.sha`, because `workflow_dispatch` can target a different ref.
|
||||
- Job `name:` values are the GitHub check contexts. Keep them stable: branch
|
||||
protection may match them by name. Renaming the workflow file/name is safe.
|
||||
|
||||
## Adding a bundle-consuming suite
|
||||
|
||||
Add a job with `needs: build-bundle`, a `Restore Cache` step
|
||||
(`actions/cache/restore@v5`, key `needs.build-bundle.outputs.bundle_key`,
|
||||
`fail-on-cache-miss: true`), then that suite's own deps. Never add a build step.
|
||||
|
||||
## Scope
|
||||
|
||||
Distinct from `Bundles Builder` (`.github/workflows/build-bundle.yml`), the
|
||||
release path that zips the bundle (`manage.sh build-bundle`) and uploads it to S3.
|
||||
- `.github/workflows/tests-e2e.yml` is the source for triggers, jobs and stable check names. Plugin changes also run the frontend suites because the bundle embeds built plugins. Manual dispatch runs integration, not the two mocked plugin jobs.
|
||||
- `build-bundle` builds `frontend/resources/public` only on a cache miss. Derive the key from the SHA actually checked out, not `github.sha`: manual dispatch can choose a different ref.
|
||||
- Consumer jobs depend on `build-bundle`, restore its exact output key with `fail-on-cache-miss: true`, and never rebuild. Copy the restore action pin from the current workflow when adding a consumer. Keep job names stable; branch protection can match the check context by name.
|
||||
- Integration uses `frontend/scripts/e2e-server.js`. The mocked plugin jobs install only plugin dependencies and use their own zero-dependency `ci/static-server.ts` copies; keep those copies aligned and do not import helpers requiring `frontend/node_modules`.
|
||||
- Local integration setup: `mem:frontend/testing-playwright`; composable suite: `mem:frontend/composable-component-tests`. `.github/workflows/build-bundle.yml` is a distinct release packaging path, not a test bundle producer.
|
||||
|
||||
7
.serena/memories/frontend/error-reporting.md
Normal file
7
.serena/memories/frontend/error-reporting.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Frontend errors and reports
|
||||
|
||||
- Start at `app.main.errors`, `app.main.repo/handle-response`, `app.main.ui.error-boundary` and `app.main.ui.static`. For report delivery outside the browser see `mem:audit-log`; for hands-on crash recovery see `mem:frontend/handling-crashes`.
|
||||
- The store's `:exception` clears on `rt/navigated`, but React render errors live inside the boundary. Its reset keys are a real JS array of screen-name strings: the library uses JS array methods and `Object.is`, so a CLJS vector fails and rebuilt keyword objects reset unnecessarily. Reset on screen changes, not solely param changes; a crash on the same screen may need a reload.
|
||||
- `app.main.repo/retryable-types` is the shared transient set. An unexpected transport response is not necessarily an app defect; repo classifies it before downstream handlers choose retry or notification. Keep environment failures on the audit-only path, not the internal defect reporter. Stale compiled chunks may need a throttled reload; plugin errors must stay isolated from the global exception page.
|
||||
- Reserve the dedup slot before formatting. Keep the cache and payload bounded; a single error hint can embed a whole file and block a batch. Report names participate in dedup because external consumers distinguish handled errors from defects. Reset the governor between test cases that expect an emission.
|
||||
- `flash` schedules reporting and the toast off the failing stack and resolves even if reporting fails; tests may await it. Do not reclassify a caller's report name just to select a compact display. For persistence use the underlying `:cause-type` to classify the wrapped error. Authentication and `vern` conflict delegate; `:not-found` is a terminal save failure that keeps the workspace open. The reload action on the save-failure report is a full restart, not a retry of the halted queue. See `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
@ -12,7 +12,7 @@ Check crash state:
|
||||
(some? (:exception @app.main.store/state))
|
||||
```
|
||||
|
||||
It returns `true` when the Internal Error page is showing and `false` on a healthy workspace or after a successful reload.
|
||||
It returns `true` for the store exception page. A React error boundary can show an error without setting this flag; see `mem:frontend/error-reporting`.
|
||||
|
||||
## Read the runtime cause
|
||||
|
||||
@ -33,6 +33,6 @@ For backend validation errors (`:type :validation`), `:details` is usually the m
|
||||
|
||||
## Recover and continue testing
|
||||
|
||||
Simplest path when `cljs_repl` is still live (usually true after a crash): reload via repl with `(.reload js/location)` — see `mem:frontend/cljs-repl`. Alternatively via Playwright: find the workspace tab (URL contains `/#/workspace`, title ends `- Penpot`), select it if not current, then `playwright:browser_navigate` to that same URL. Either way, confirm recovery with `(some? (:exception @app.main.store/state))` returning `false`.
|
||||
If `cljs_repl` still works, reload with `(.reload js/location)`; see `mem:frontend/cljs-repl`. Otherwise select the workspace tab by its current URL (`screen=workspace` in the query) and reload that URL. Confirm that the workspace renders again and `(some? (:exception @app.main.store/state))` returns `false`; the store check alone does not detect a React render boundary.
|
||||
|
||||
For backend-rejected changes, such as validation errors on `update-file`, changes are not persisted. Reload restores the pre-crash state, so it is safe to retry after fixing the cause.
|
||||
Reload reads the saved version, not unsaved local edits. An earlier commit in a partially rejected save can already be durable; see `mem:frontend/workspace-state-persistence-subtleties` before retrying a sequence of edits.
|
||||
|
||||
@ -1,55 +1,5 @@
|
||||
# Handling Errors and Debugging
|
||||
# Frontend debugging (compatibility entry)
|
||||
|
||||
## Finding source errors
|
||||
|
||||
You have access to two tools for finding errors in Clojure source code (which you may introduce yourself through edits):
|
||||
|
||||
1. cljs_compiler_output
|
||||
2. clj_check_parentheses
|
||||
|
||||
The latter is needed because syntax errors in parentheses give an uninformative compiler error, and the second
|
||||
tool can often find the exact location of such errors.
|
||||
|
||||
When delimiter errors are detected (typically from lint or compiler output),
|
||||
fix the affected files with `scripts/paren-repair`. The `clj_check_parentheses`
|
||||
MCP tool can also pinpoint the error location when available, but it is not
|
||||
required — standard build errors are usually enough.
|
||||
See `mem:scripts/paren-repair`.
|
||||
|
||||
## Runtime patching with `set!`
|
||||
|
||||
Some frontend vars are deliberately mutable escape hatches for runtime instrumentation or circular-dependency patching.
|
||||
From `cljs_repl`, use `set!` for temporary debugging of CLJS vars such as
|
||||
`app.main.store/on-event`, `app.main.errors/reload-file`, `app.main.errors/is-plugin-error?`,
|
||||
`app.main.errors/last-report`, or `app.main.errors/last-exception`.
|
||||
These patches affect only the live browser runtime and disappear on reload or recompilation.
|
||||
|
||||
```clojure
|
||||
;; Log non-noisy Potok events temporarily.
|
||||
(set! app.main.store/on-event
|
||||
(fn [event]
|
||||
(when (potok.v2.core/event? event)
|
||||
(.log js/console (potok.v2.core/repr-event event)))))
|
||||
```
|
||||
|
||||
Restore mutable hooks after debugging, or reload the frontend. Use JVM `alter-var-root` only for JVM Clojure;
|
||||
it is not the normal way to patch live CLJS browser vars.
|
||||
|
||||
## Browser-console debug namespace
|
||||
|
||||
In development, the JS console exposes `debug` helpers from `frontend/src/debug.cljs`:
|
||||
|
||||
```javascript
|
||||
debug.set_logging("namespace", "debug");
|
||||
debug.dump_state();
|
||||
debug.dump_buffer();
|
||||
debug.get_state(":workspace-local :selected");
|
||||
debug.dump_objects();
|
||||
debug.dump_object("Rect-1");
|
||||
debug.dump_selected();
|
||||
debug.dump_tree(true, true);
|
||||
```
|
||||
|
||||
Visual workspace debug overlays can be toggled with `debug.toggle_debug("bounding-boxes")`, `"group"`, `"events"`, or `"rotation-handler"`; `debug.debug_all()` and `debug.debug_none()` toggle all visual aids.
|
||||
|
||||
For temporary source traces, prefer existing logging (`app.common.logging` / `app.util.logging`) or short-lived `prn`, `app.common.pprint/pprint`, `js/console.log`, or `js-debugger` calls. Remove temporary source instrumentation before committing.
|
||||
- Build failure or stale hot reload: `mem:frontend/compile-diagnostics`.
|
||||
- Live state or Potok event inspection: `mem:frontend/cljs-repl`.
|
||||
- Runtime crash recovery: `mem:frontend/handling-crashes`.
|
||||
|
||||
5
.serena/memories/frontend/host-integration.md
Normal file
5
.serena/memories/frontend/host-integration.md
Normal file
@ -0,0 +1,5 @@
|
||||
# External host integration
|
||||
|
||||
- The SaaS host can inject `globalThis` hooks consumed by `app.config`. Treat them as an external API: absence of in-repo callers is not evidence that a hook is dead. In particular, preserve `external-feature-flag` as the A/B test seam.
|
||||
- `frontend/resources/templates/index.mustache` loads the callback registry stub before `config.js` so the host can register named callbacks during config evaluation. The CLJS fallback in `app.config` must preserve a registry or registration function already supplied by the host or stub.
|
||||
- `app.main.data.event` forwards audit events after `make-event` via the named callbacks. Keep this boundary vendor-agnostic; don't add a vendor SDK to Penpot to deliver a host event.
|
||||
@ -1,37 +1,8 @@
|
||||
# Frontend Routing, App Shell, Websocket, and Error Subtleties
|
||||
# Routing and app shell
|
||||
|
||||
## Router, app shell, and errors
|
||||
|
||||
- Routing uses browser-history query tokens (`?screen=<route-name>¶ms`, single `/` path), but `on-navigate` rejects navigation if the current origin/path does not match `cf/public-uri`.
|
||||
- `app.util.browser-history` (CLJS, not the old `goog.history.Html5History` wrapper) is the only history layer: the token is `location.search`, the URL of a token is `(:path cf/public-uri)` + token, and every change (own `pushState`/`replaceState` or back/forward) lands on the `token-changes` subject the router subscribes to. Nothing about it lives in the store: `rt/initialize-history` is effect-only.
|
||||
- `set-token!` and `replace-token!` are deliberately asymmetric. `set-token!` is a total no-op when the token already is the current one (no URL write, no report), so navigating to the screen you are on cannot grow the history stack. `replace-token!` always writes and always reports, because it is how the app corrects the URL in place (legacy `#/…` translation, cleaned share links) and that correction must reach the router even when the token did not change. This matches `Html5History`, which did the same; do not "fix" the asymmetry without deciding what navigates to the current screen.
|
||||
- `app.util.dom/replace-history-state!` is the deliberate bypass used by `app.main.ui.dashboard`/`app.main.ui.static` to rewrite the URL **without** routing. Keep using it there instead of `replace-token!`, which would re-enter the router.
|
||||
- Route params live entirely in the query map under the reserved `screen` key; duplicate query params can become vectors, so use `rt/get-query-param` when a scalar is required.
|
||||
- The organization SSO flow sends the **query string** (`rt/get-current-query-string`), not the URL and not the token: the backend builds the destination URL from `public-uri` + `?` + those params, so the client never chooses the origin of the redirect. The history token (`rt/get-current-token`, `location.search`) keeps its leading `?` because every other consumer concatenates it over the base path (`str cf/public-uri token`, `dom/append-query-param`, `dom/remove-query-param`); `rt/token->query-string` is the only bridge between the two shapes, so do not trim at a call site by hand; `rt/token->url` is the single client builder of an absolute destination from either shape (used by the SSO retry and error flow), so do not assemble `public-uri + "?" + params` at call sites. The gate is not the only caller: `dtm/resolve-login-team-id` runs from the root branch of `on-navigate` too, and there the URL carries its params instead of a screen (`?template=…`) — that call only reads `:authorized`, so it never follows the destination, which is exactly why a wrong destination there goes unnoticed. Do not add a rule that requires `screen`. See `mem:backend/auth-permissions-product-domains`.
|
||||
- The router events expose their payload through `@event` (`IDeref`): `rt/navigate` returns `{:id :params :options}` and `rt/nav-raw` returns its `:href`/`:uri`. `rt/nav-raw` is the way out of the router (raw URL, outside the token scheme) and nothing in the app listens to `::rt/nav-raw`; the destination travels in the effect, so `@event` is the only way to tell where the user is being sent (tests included).
|
||||
- Legacy `#/…` hash URLs translate client-side to the query format (one-version compat; see `legacy-routes` in `app.main.ui.routes`, TODO(next-version) to delete).
|
||||
- Unknown/empty routes trigger an extra `get-profile`/`get-teams` check before redirecting. This avoids invitation and root-route race conditions.
|
||||
- The root app has two error layers, and they reset differently. `:exception` in the store renders `static/exception-page*` directly and is cleared by `rt/navigated`; a React render error is caught by `app.main.ui.error-boundary` (`react-error-boundary`), whose error lives in internal React state that only `reset-error-boundary` clears. Because every exit from the error page (the logo, the no-permission dialogs, the SSO dialog, the feedback link) only *navigates*, the boundary is given `:resetKeys [(eb/reset-key route)]` — the screen name — so a navigation counts as a fresh attempt at rendering. Three traps in that `resetKeys` value, all learned the hard way: it must be a real JS array (`#js [...]`), never a ClojureScript vector, because `react-error-boundary` reads `.length` and `.some` and a `PersistentVector` has neither, so `componentDidUpdate` throws `some is not a function`; it must hold the screen name as a *string*, because the library compares entries with `Object.is` and ClojureScript does not intern keywords, so two equal keywords are two objects and a keyword key would read as new on every route rebuilt, resetting the boundary on a param change inside the same screen; and it must be the screen rather than the params, so a param change does not replay the screen that just crashed. Navigating to the *same* screen therefore does not reset, and a reload is the only way out of that case.
|
||||
- The root app renders an exception page from `:exception` state before the normal error boundary. `rt/navigated` clears `:exception`.
|
||||
- Frontend error handling treats stale cross-build JS chunk failures specially: messages containing `$cljs$cst$` or `$cljs$core$I` plus undefined/null/not-a-function signatures trigger throttled reload.
|
||||
- Plugin-originated uncaught errors are identified through the plugin runtime hook and logged rather than turning into the global exception page.
|
||||
- `app.main.errors/submit-report` is governed by a dedup governor: each report carries a fingerprint (`report-name|type|code|hint|first stack frame`; the report name is part of it so a handled report never coalesces with an unhandled/exception-page one), the first occurrence is always emitted, repeats within 2 minutes are counted and included in the next emitted report as `:occurrences`, and the fingerprint cache is bounded (first-inserted entry evicted, FIFO, via `:order` queue) so memory stays fixed. It applies to `handled-exception`, `unhandled-exception` and `exception-page`; a report without an exception cause is ignored and does not consume a reservation.
|
||||
- Errors caused by the environment (`environment-error-types`: `:network`, `:offline`, `:bad-gateway`, `:service-unavailable`, `:gateway-error`, `:nitrate-unavailable`, `:nitrate-not-configured`) are not application defects: they are reported as audit-only `handled-exception` (never `unhandled-exception`/`exception-page`, so they skip internal reports and alerts), with a compact report and a fingerprint that drops the stack frame. `:offline` has its own handler and no longer falls through to `:default`; `:network`/`:offline`/`:gateway-error` show the `errors.connection-error` toast.
|
||||
- `repo/handle-response` classifies responses the backend never wrote (body is not a transit map) by status: 504 and Cloudflare 520–524 → `:gateway-error` (retryable, so GETs and saves retry); 429 → `:rate-limit`; any other ≥400 → `:unexpected-response` (both toast-only via `handle-transport-error`, never the exception page). `:internal :unable-to-process-repository-response` is left for a <400 response that does not decode. Uninterpretable bodies are capped at 500 chars in `:data`.
|
||||
- `generate-report` accepts an explicit `{:format :compact|:full}` (default `:full`) chosen by its caller (`flash`, `exception-section*`): `:compact` keeps the context header plus type/code/uri, and skips the stack, the `ex-data` dump and the last-events list. It is total: if formatting fails it returns a minimal fallback string instead of nil, so an already reserved emission is never dropped.
|
||||
- `flash` runs its whole body (report pipeline first, toast after) inside a single `ts/schedule` callback: nothing executes synchronously on the error handler's stack. The report is reserved before being generated, so suppressed occurrences do not pay the `generate-report` cost; a reporting or notification failure is logged to the console and never propagates, and the toast is still attempted. `flash` returns a total promise (never rejects) resolving with the generated report, or nil when nothing is emitted, once the callback completes; production callers ignore it, tests await it. `flash` derives only the payload format from the cause (`environment-error?` → `:compact`); the audit event name is the canonical one requested by `:type` (`handled-exception`/`unhandled-exception`) and is never reclassified, because external tools filter on those names. `exception-section*` picks `handled-exception`/`exception-page` explicitly per cause; `flash-persistence` only adds the toast hint.
|
||||
- `flash` accepts a `:links` vector of `{:label :callback}` actions, appended after the download link that `:report-link?` produces. `flash-persistence` passes a reload link, so a terminal save failure hands the user both the report and the only action that restarts persistence for the session. `labels.reload-page` plus `js/location.reload` is the established full-restart pattern; the link cannot be invoked under the test runner because `js/location` does not exist there, so it is covered by its label and by being callable.
|
||||
- `flash-persistence` only delegates to another handler for `:authentication`, `:not-found` and `:code :vern-conflict`. Everything else it reports itself, and the report type is derived from the cause: `#{:validation :server-error :internal}` are application defects and report as `unhandled-exception` so they reach the internal reports and the alerts; the rest stay `handled-exception`. `:cause-type` wins over `:type` when classifying, because `persistence-failed` wraps the original cause under `:type :persistence`. Environment failures are deliberately kept handled: they land here after the retry budget is spent and the user's connection is not our bug. `:assertion` is also kept handled, matching its own handler.
|
||||
- The report governor is global and stateful across tests: two reports with the same fingerprint inside `report-window-ms` collapse. Call `errors/reset-report-governor!` between assertions that expect an emission.
|
||||
- Error messages are bounded at the source: `app.common.exceptions/get-hint` clamps to `max-message-length` (1000 chars) and the CLJS `format-throwable` clamps the message line of the stack trace and honors `:trace-length`. A message can embed a whole payload (a serialized file, for example) and reach megabytes; the bound keeps the audit `:hint` prop and the `:report` string small. The `Context: Hint:` header in `generate-report` prints `get-hint` (not the raw `:hint` from `ex-data`) for the same reason.
|
||||
- A team scoped navigation carries a team whenever any of the four tiers exists, and `app.main.data.common/resolve-team-id` decides it for every team scoped `go-to-*` helper of that namespace: the UUID the caller passes, `:current-team-id`, the team of the route already on screen (`?team-id`), then the profile `:default-team-id`. `go-to-feedback` and `go-to-viewer` are not team scoped and do not go through it, and `:team-id :default` keeps meaning the profile default, resolved before the rest. The route goes before the profile default because an emitter that runs from a team screen knows which team the user is looking at, and the personal team would open their file under another team. Two `rt/nav` emitters outside that namespace still decide their own id and can still emit nil, and they are the residual: `app.main.ui.nitrate.entry/nitrate-entry*` (the profile default) and the root branch of `app.main.ui.routes/on-query-navigate` (`dtm/resolve-login-team-id`, which answers nil when the profile has no default team). When none of the tiers exists the helper still fires the navigation with a nil id, so the not-found page appears instead of the click doing nothing.
|
||||
- `app.main.ui/team-container*` raises `:not-found :invalid-team-id` for a dashboard or workspace route without a valid `team-id`; the raise is what keeps a broken URL from painting a blank shell, so it stays after the hook fix of #12728. `exception-section*` skips `errors/submit-report` for `:not-found`, so this failure never reaches PostHog and cannot be measured from the error dashboard. The exit from that page is the `error-container*` header (logo plus `not-found.no-permission.go-dashboard`), which emits `go-to-dashboard-recent` with the profile default and falls back to `rt/nav-root`; every not-found and authentication page already carries it, so there is no button to add there.
|
||||
- A click cannot reach a team screen before its team is resolved: `team-container*` paints its children only when the route id matches the store team, and `refs/team` derives from `:current-team-id`, so with that key empty the dashboard and the workspace paint nothing clickable. The nil-id emissions come from events that run on their own (login, invitation acceptance, membership change, the sidebar logo, the workspace shortcuts) and from typed or bookmarked URLs.
|
||||
|
||||
## Store and websocket
|
||||
|
||||
For general store mechanics such as `emit!`, `last-events`, persistence, and undo, read `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
|
||||
- Websocket initialization uses `cf/public-uri` joined with `ws/notifications`, converting `http/https` to `ws/wss`, and includes the current `session-id` as query param.
|
||||
- Reinitializing or finalizing websocket stops the previous receive stream. Incoming websocket payloads become Potok data events under `app.main.data.websocket/message`.
|
||||
- A job the client created is followed with `app.main.data.jobs/watch-job`: it emits the `:job-event` messages of that job (filtered by `:job-id`) and one final outcome read from the row with `get-job`, which is read when the stream starts and again on every `opened` of the websocket, so a job that ended before the client started following it, or while the socket was down, still answers. The stream ends after that outcome, and a read that fails reaches the caller: the repo retries the transient transport errors of a GET, and anything else is a real failure the flow has to show. The `:stage` of a progress event is a stable key of the vocabulary of the worker, never a display string: `app.main.ui.jobs.progress` resolves it with a `case` of literal `tr` calls, falls back to a generic label for a stage it does not know, and the counter of the activity is named after its own stage (the counter of `:files` is the outer context).
|
||||
- Start at `app.main.ui.routes`, `app.main.router` and `app.util.browser-history`. The token is `location.search`, not a store field; preserve the configured `public-uri` origin and subpath. The route table and legacy hash compatibility live in `app.main.ui.routes`.
|
||||
- Push of the current token does not write or notify; replace always writes and notifies, even for the same token, so URL corrections reach the router. `app.util.dom/replace-history-state!` intentionally rewrites without routing; do not substitute a notifying replace.
|
||||
- Route data uses query params. A repeated param can decode as a vector; use `rt/get-query-param` for a scalar. Use `rt/token->query-string` at the SSO boundary: the server owns the destination origin. Use `rt/token->url` for a client-side absolute URL; do not require `screen`, since root flows can carry params such as a template without a route name. See `mem:backend/auth-permissions-product-domains`.
|
||||
- `rt/nav-raw` exits the router; tests observe its destination by dereferencing the event, not by looking for an app listener. Unknown or empty routes verify the profile and teams before redirecting so root and invitation flows do not race. See `mem:frontend/auth-events` for login and invitations.
|
||||
- Use the team-scoped navigation helpers in `app.main.data.common` rather than building the route at the call site. Their private `resolve-team-id` considers the team already on screen before the profile default, so the user's personal team does not replace the current team. An invalid team route fails explicitly rather than rendering a blank shell.
|
||||
- For store exceptions, React boundaries and report limits/classification see `mem:frontend/error-reporting`. For the client reaction to lost membership and job events see `mem:frontend/websocket-notifications`.
|
||||
|
||||
7
.serena/memories/frontend/testing-playwright.md
Normal file
7
.serena/memories/frontend/testing-playwright.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Frontend Playwright integration tests
|
||||
|
||||
- Add, edit or run `frontend/playwright` integration specs only on explicit request. Test runner scripts and project names live in `frontend/package.json` and `frontend/playwright.config.js`; size workers to available CPU and browser memory.
|
||||
- The web server serves the release bundle in `frontend/resources/public`, not live sources. Rebuild from `frontend/` with `./scripts/build` after product edits or a branch switch with different sources/assets; a spec-only edit does not require that rebuild. A stale bundle that fails at boot says nothing about the spec.
|
||||
- Mock the RPC and socket traffic your page needs; the integration suite does not exercise live backend behavior. `BasePage.mockRPC` expects a command name, not the full RPC URL. Set up `BaseWebSocketPage` mocks before workspace initialization subscribes.
|
||||
- Prefer user-facing locators. Layer rows are an exception: selection can add hide/lock titles to their accessible name. Use `WorkspacePage.layerRow`/`layerRows` and `selectRow`/`selectLayer` rather than matching the entire role name or clicking twice.
|
||||
- For build-once CI and stable check names see `mem:frontend/e2e-ci-workflow`. For targeted live pointer and keyboard input see `mem:frontend/playwright-gestures`.
|
||||
11
.serena/memories/frontend/testing-unit.md
Normal file
11
.serena/memories/frontend/testing-unit.md
Normal file
@ -0,0 +1,11 @@
|
||||
# Frontend CLJS unit tests
|
||||
|
||||
- Start in `frontend/test/frontend_tests/`; add new namespaces to `frontend_tests/runner.cljs`. From `frontend/`, use `pnpm run test:quiet -- --focus <namespace-or-var>` to compile and run a narrow test; the compiled runner alone does not rebuild after edits.
|
||||
- Reproduce async behavior in async tests. `^:async` needs map-style fixtures, and promises from async helpers, fixtures and nested mock scopes must be awaited. Legacy `t/async` terminates through `done`, not the body promise. Missing awaits can leave a passing test with no assertions.
|
||||
- Prefer `mock/with-mocks*` with an awaited body; use scoped mutable stubs so mocks survive `await`. Dynamic bindings do not. Close mocks and subscriptions after the terminal continuation, not just after sending the first event. Use `frontend-tests.helpers.async` and `frontend-tests.helpers.mock` for the available helpers.
|
||||
- Subscribe before pushing to a hot stream. Use `await-response` for subscribe→push→await and observe terminal completion when asserting a sequence. When a state change can precede the last RPC, wait for the RPC through the mock; otherwise an in-flight call may hit real HTTP after teardown. Use a signal for a state-dependent wait when available; use explicit settling for ordering that has no signal.
|
||||
- Mutable mocks are shared with background flows. Filter unrelated traffic when counting calls or releasing a wait. For variadic vs fixed arity stubs, use the correct helper: compiled `:esm` invocation can bypass a replacement aimed at the wrong arity. Use an empty stream for “completes without a value”; use a quiet subject for “stays open”.
|
||||
- Treat `:fn-arity` as a defect: a compiled single-arity or variadic function can receive `undefined` rather than fail loudly. Incremental compilation only prints warnings when it rebuilds a namespace; see `mem:frontend/compile-diagnostics`.
|
||||
- For `:infer-warning` in JS interop inside `set!`, hint the bound target symbol, not an inline expression. Put the return hint on the helper name when the helper returns a JS object and multiple callers need it.
|
||||
- Non-obvious runtime boundaries: the `:esm` test target cannot load the CommonJS parser behind `tubax`; mock both SVG validation and conversion. For hook-order regressions, capture `console.error` as well as boundary callbacks; test the render direction where hooks are added (`frontend-tests.ui.team-container-test`). Scope suppression of expected noisy errors to the test.
|
||||
- Coverage is over loaded namespaces; `unloaded.txt` is reported separately. Prefer line coverage to generated-JS branch percentages. The converter must read source text to handle CLJS source-map ranges; do not pass `ignoreSourceCode`. See `frontend/scripts/coverage.js` and `mem:scripts/coverage-reporting`.
|
||||
@ -1,91 +1,6 @@
|
||||
# Frontend Testing and Live Verification
|
||||
# Frontend testing
|
||||
|
||||
Frontend validation: CLJS + React/Rumext + RxJS/Potok; SCSS modules; shared CLJC from `common/`.
|
||||
|
||||
## Unit tests
|
||||
|
||||
READ `mem:testing` FIRST — it defines the execution discipline (no piping, tee to file, preferred commands) that applies to all CLJS/JS test runs.
|
||||
|
||||
Frontend unit tests live under `frontend/test/frontend_tests/` and use `cljs.test`. They should be deterministic, avoid DOM/UI integration where possible, and mock side effects such as RPC, storage, timers, or network access.
|
||||
|
||||
### Async-first stance
|
||||
|
||||
Frontend testing is async-first: everything essentially asynchronous is modeled with a test reproducing the asynchrony, even when the test could be written "synchronously". Sync-passing tests prove nothing about async behavior and rot as soon as an async boundary appears downstream. Consequences: mock through `frontend-tests.helpers.mock`, never `with-redefs`, except unit tests of purely synchronous functions; transport doubles deliver asynchronously (`observe-on :async`) while the test keeps scenario timing (explicit pushes); assertions always follow quiescence (`wait-for` on presence, bare `settle` tick for absence-only blocks), never a trigger.
|
||||
|
||||
### Primitives
|
||||
|
||||
- `mock/with-mocks` (callback style, legacy compat): installs with `set!` so mocks survive async boundaries; bodies run deferred past the current tick via `asap`, so only done-chained (`t/async`) contexts are allowed; `done'` restores and completes exactly once (twice only warns; never calling it stalls the run and leaks the mocks). Prefer `mock/with-mocks*` for new tests.
|
||||
- `mock/with-mocks*` (direction): body forms wrapped in a generated `^:async` fn, evaluates to a promise — `await` it, `await` nested scopes too, no `done` in test code. Rejections and non-promise returns report as `:error` via `run-mocked`.
|
||||
- `mock/stub` wraps fns for arities 0-6 (the `:esm` test build dispatches multi-arity vars as `cljs$core$IFn$_invoke$arity$N`); when the mocked var is variadic-defined (or called with more than 6 args), the call compiles to variadic dispatch, so use a plain variadic `fn` — the stub does not forward variadic. A mock must not call the mocked var again (self-delegation inside a multi-arity function recurses).
|
||||
- Helpers in `frontend-tests.helpers.async`: `->promise` (single-value observable → promise; beicon has no `to-promise`), `await-response` (subscribe→push→await, atomic), `settle`, `wait-for`, `wait-for-store`, `observe` (stream → termination promise; asserts provided, timeout rejects).
|
||||
- `wait-for` waits on a **signal**, not on turns: `:signal` (an observable) re-checks the predicate on every emission and resolves on the event that changes the state; `:timeout-ms` (default 5000) only bounds failure then. Without a signal it polls against a real-time deadline — 50 turns were ~54 ms idle, and turns are not a unit of time. `wait-for-store` passes `ptk/input-stream` as the signal (the store notifies after applying the update, so the predicate sees the new state); the persistence fixture exposes `requests$` for `(= N (count @requests))`. A wait that resolves on an event consumes no turn. The waits with nothing to listen to stay on the poll: test atoms filled outside the store (`@cycles`, `@reports`, `@done`), `@failures`, and predicates over JS objects or closures.
|
||||
- Fixtures return promises (`with-watchdog`, `with-persistence`); `await` them from `^:async` tests. `main_errors` and `fonts` are fully migrated (no legacy `with-mocks` left).
|
||||
- Valid `^:async` placements: `mem:clojure/idioms`.
|
||||
|
||||
### Observing event streams
|
||||
|
||||
To assert over emitted event sequences, observe termination: subscribe through `observe` (async delivery forced even for sync sources), `await` its promise, then assert the collected values. Never branch on nil (`when-let` skipping observation lets setup bugs pass as "empty"): producers answer refusals with empty streams, never nil, so every path subscribes uniformly. Observed termination is exact quiescence — no manual `settle` after it. Errors reject unless `:on-error` handles them.
|
||||
|
||||
### Runner and library facts (verified: CLJS 1.12.145, beicon2 `df7058a`)
|
||||
|
||||
- `cljs.test` keeps its env in a `set!` var: assertions inside deferred ticks count. `run-block`: double `done` only warns; missing `done` stalls.
|
||||
- `t/async` discards the body promise — completion signals ONLY via `done`. `t/deftest ^:async` adds auto async-context + auto `done`, but awaiting stays the author's job; without it the test passes empty.
|
||||
- `take 1` is per-subscription on a hot subject: subscribe-before-push or hang. `end!`/`.error` with pending takes only forwards valueless completion.
|
||||
- Single-arity and variadic `defn`s compile to JS functions with no argument-count check (any target), so missing required args arrive as `undefined` instead of throwing; the analyzer
|
||||
`:fn-arity` warning is the only signal. Treat `:fn-arity` in `compile test` as a defect, never as noise.
|
||||
- `:infer-warning` on a JS interop fixes with `^js` on the target (`(.-foo ^js x)`, `(.method ^js x ...)`). Inside `set!` the hint must sit on a symbol: `(set! (.-foo ^js (f x)) v)` still warns, so bind `(let [^js y (f x)] (set! (.-foo y) v))`.
|
||||
- A helper that returns a JS object carries the hint on its name (`(defn- ^js catalog [id] ...)`), and call sites then need no hint at all — `(.method (catalog id))` and `(.-prop (catalog id))` stop warning. This is the cheapest way to keep interop out of the test bodies; `^js` on the arglist instead of the name does not work.
|
||||
|
||||
### Traps that bit
|
||||
|
||||
- `^:async` tests require map-style fixtures (`(t/use-fixtures :each {:before f})`): function-style fixtures abort the whole run ("Async tests require fixtures to be specified as maps").
|
||||
- `st/emit!` doubles collect heterogeneous events: audit `DataEvent`s deref, toast reify-objects do not — discriminate with `ptk/type` (total, never throws), never blind `deref`.
|
||||
- Subscription order decides delivery order: never resolve settlement from a pre-subscribed branch racing the pipeline.
|
||||
- Auto-answering mocks lose deadline expressiveness (can't time answers), need teardown timer-cancellation, and post-teardown deliveries hit real implementations — explicit pushes + async delivery + `wait-for` won on every axis.
|
||||
- A wait that observes an effect the test asserts takes a signal. A wait that means "the side effect advanced before the next emit" has no event to listen to: keep the poll (or an explicit `settle`) and say so, because a signal would resolve inside the same `emit!` and the next step would overtake the pipeline (`persistence-rollback-test` drove its four emits this way).
|
||||
- With `rp/cmd!` mocked, a store-state wait can resolve before the flow that changes it ends, and the mock scope then closes in flight: the next call hits the real HTTP layer (malformed URL from a nil `cf/public-uri`) and the error is reported on a later test. `unlink-file-from-library` dissocs the library before its async chain, so the only proof the chain ran inside the mock is its second RPC call; wait for that, through the mock.
|
||||
- Teardown belongs to the terminal continuation, never to `finally`-around-triggers (it would dispose in-flight flows).
|
||||
- A body that awaits must be `(^:async fn …)` even if the rest is sync; sync sequences are atomic vs the event loop.
|
||||
- `app.main.errors` prints every handled cause with `ex/print-throwable` before notifying, and the app logger does not gate it. A test that runs a real handler end to end stubs that var (`main-errors-test/quiet-throwable`): without it, the 10 000-error governor test alone wrote 190 k of the 192 k lines of a run log (13,8 MB), and GitHub truncates a step log past ~4 MB, cutting the summary and any failing assertion. Same for a production `console.error` a test provokes on purpose: `code-gen-markup-svg-wasm-test` silences `(.-error js/console)` in a `try/finally` while two WASM panics go through `get-svg-markup` (2 blocks, 70 lines, and the exception dumps its own `data`/`arr`).
|
||||
- The `:esm` test build cannot load the CommonJS `sax` module behind `tubax`, so SVG parsing fails in tests (`dwm/valid-svg-string?` answers false, `dwm/svg->clj` errors): mock both with the parsed data.
|
||||
- A hook-order violation in a mounted component reaches neither the root's `onUncaughtError`/`onCaughtError`/`onRecoverableError` nor the markup: React logs an internal error to `console.error` and recovers, so the callbacks stay empty and the tree repaints. Assert on a captured `console.error` too. It only fires when a render *adds* hooks (nil → uuid); a render that calls none at all slips through React's bookkeeping, so the regression test needs the "hooks arrive" direction. `frontend-tests.ui.team-container-test` does both, with a jsdom document.
|
||||
- `beicon.v2.core` has no `never`. A stream that must **not emit** is `(rx/empty)`: it completes at once, which is enough for `merge`, `filter` and `take` where only the emission matters. A stream that must **stay open** is a `(rx/subject)` nobody pushes to; `rx/empty` would complete the flow behind it. An undeclared `rx/never` compiles to an undefined var and the test dies as a rejected body, which `cljs.test` reports as a test with zero assertions instead of a failure.
|
||||
- `set!` mocks are global and outlive the fixture, so a flow another module left running (a store's pending timer) can still reach the mocked transport mid-test; `with-persistence` records every command for that reason. Filter to the commands your layer issues — persistence only sends `update-file` — before counting or asserting emptiness, and never let a stray call release a `wait-for` on one.
|
||||
|
||||
From `frontend/`:
|
||||
- Full unit test run (always builds, suppressed output): `pnpm run test:quiet`.
|
||||
- Full unit test run (always builds, build output visible): `pnpm run test`.
|
||||
- Focus a frontend CLJS test namespace: `pnpm run test:quiet -- --focus frontend-tests.logic.components-and-tokens`.
|
||||
- Focus one frontend CLJS test var: `pnpm run test:quiet -- --focus frontend-tests.logic.components-and-tokens/change-spacing-token-in-main-updates-copy-layout`.
|
||||
- Quiet `app.*` logging during a run: append `--log-level warn` (or `trace|debug|info|warn|error`).
|
||||
- Build test target only (no run): `pnpm run build:test`.
|
||||
- After `build:test` has been run, run the compiled runner directly: `node target/tests/test.js [--focus ...] [--log-level ...]`.
|
||||
- Watch tests: `pnpm run watch:test`.
|
||||
- Coverage: `pnpm run test:coverage` (builds, runs the suite under `NODE_V8_COVERAGE`, keeps its exit code). `scripts/coverage.js` maps V8 data back to `.cljs`/`.cljc` through the test build's source maps (`ast-v8-to-istanbul` + acorn) and writes `coverage/` (`lcov.info`, `coverage-summary.json`, `html/`, `unloaded.txt`); `tests-frontend.yml` renders the step summary with `scripts/coverage-summary.mjs` and uploads `coverage/` as the `frontend-coverage` artifact. `scripts/test` (CI) runs `test:coverage`, not `test`. Scope: `frontend/src/app/**` minus `app/main/ui/` (`EXCLUDED_DIRS`); namespaces no test loads are listed apart, never counted. Never pass `ignoreSourceCode` to `convert`: CLJS maps point past source lines and it throws. Trust line % over branch % (branches are of the generated JS).
|
||||
|
||||
New frontend test namespaces must be required/listed in `frontend_tests/runner.cljs`; new vars in existing namespaces need no runner change.
|
||||
|
||||
## Playwright integration tests
|
||||
|
||||
Do not add, modify, or run Playwright integration tests under `frontend/playwright` unless explicitly asked. When explicitly asked, run the whole suite with a worker count sized to the machine: `pnpm run test:e2e --workers=N` from `frontend/`, about one worker per two hardware threads, because each keeps two or three busy and holds about 2 GB of browser memory. The config's default of one worker leaves it slow; four take a 16-thread host from 48 minutes to 35 and fit a 64 GB machine beside a watching devenv, while a 32 GB machine takes two, or four with a slim devenv. `--grep "pattern"` narrows the run. Ensure dependencies are installed through `./scripts/setup` if the environment is not prepared.
|
||||
|
||||
The suite runs against the release bundle in `frontend/resources/public`, not against the sources: the app under test is that build. Rebuild it with `./scripts/build` from `frontend/` (the CI build-bundle step) whenever the product source state changes — a branch switch that brings different CLJS/CLJC, SCSS, assets or packages, or any product edit. Spec-only edits need no rebuild: Playwright reads `frontend/playwright` at run time. A stale bundle is still served by the config's `webServer` (`scripts/e2e-server.js`) and makes the app fail at boot; that failure says nothing about the specs.
|
||||
|
||||
Integration tests fake backend behavior by intercepting network/websocket traffic, so every RPC or websocket the page needs must be mocked. Use existing Page Object Models:
|
||||
- `BasePage.mockRPC` intercepts RPC calls and already prefixes `/api/rpc/command/`; pass command names such as `get-profile`, not full URLs.
|
||||
- Workspace or other websocket-using pages should extend/use `BaseWebSocketPage`, initialize websocket mocks before each test, and mock `/ws/notifications` with the provided helpers.
|
||||
- Prefer common locators/actions in POMs; ad-hoc locators can stay in a single test.
|
||||
|
||||
Locator priority should follow user-facing semantics: `getByRole`, `getByLabel`, `getByPlaceholder`, `getByText`, then semantic alternatives such as alt/title, with `getByTestId` as the last resort. Name tests from the user's perspective and prefer positive, single-purpose assertions.
|
||||
|
||||
Layer rows are the exception: a selected row's hide and lock button titles join its accessible name, so role-plus-name matching breaks on selected rows. Use `WorkspacePage.layerRow`/`layerRows` (anchored text on the `layer-row` test id) and `selectRow`/`selectLayer`, which click once and wait for `aria-checked`.
|
||||
|
||||
## CI (E2E)
|
||||
|
||||
`.github/workflows/tests-e2e.yml` runs the integration specs, the composable component suite, and the mocked Plugin API suite from one workflow that builds the frontend bundle once per SHA. Before adding a job that needs the bundle, read `mem:frontend/e2e-ci-workflow` (build-once contract, cache key, stable check names).
|
||||
|
||||
## Live browser verification
|
||||
|
||||
Because CLJC compiles to both JVM and CLJS, JVM/common tests can miss frontend-only state caused by browser runtime, WASM modifier math, or real pointer events. Use `mem:frontend/cljs-repl` to inspect live app state and `mem:frontend/playwright-gestures` when real input is needed.
|
||||
|
||||
For stale hot reload or failed CLJ/CLJC/CLJS source builds, read `mem:frontend/compile-diagnostics`. For Internal Error pages or delayed runtime crashes after automation/API actions, read `mem:frontend/handling-crashes`. Translation `.po` changes are bundled into `index.html` and require a browser refresh.
|
||||
- Start with `mem:testing` for test design and output discipline. For lint, unit tests and format together, run `./scripts/ci frontend` from the repo root; see `mem:scripts/ci`.
|
||||
- Testing CLJS events, helpers or UI logic against mocks: `mem:frontend/testing-unit`. Testing component behavior through composable commands: `mem:frontend/composable-component-tests`.
|
||||
- Running or editing integration specs with a release bundle: `mem:frontend/testing-playwright` (only on explicit request). For CI jobs that consume that bundle, see `mem:frontend/e2e-ci-workflow`.
|
||||
- JVM tests alone do not exercise frontend state, the WASM bridge or browser gestures. For a live check use `mem:frontend/cljs-repl` or `mem:frontend/playwright-gestures`. For failed compile or hot reload use `mem:frontend/compile-diagnostics`; a runtime crash is `mem:frontend/handling-crashes`.
|
||||
|
||||
7
.serena/memories/frontend/websocket-notifications.md
Normal file
7
.serena/memories/frontend/websocket-notifications.md
Normal file
@ -0,0 +1,7 @@
|
||||
# Frontend WebSocket notifications
|
||||
|
||||
- Start at `app.main.data.websocket` for the notification stream and subscription lifetime, and `app.main.data.jobs/watch-job` for jobs. Preserve the configured public subpath and session identity; reinitializing or finalizing must dispose the previous receive stream.
|
||||
- A newer workspace notification initialization stops the old handler even on same-file reload. Do not send a late unsubscribe for the same file: the server keeps one file subscription per connection, so it would also remove the new subscription.
|
||||
- Lost membership already has a client path: the `team-membership-change` notification updates access and navigates away. The server must revoke the subscription even if the client fails to navigate; see `mem:backend/websocket-subscriptions`.
|
||||
- A job's progress comes from socket events; its outcome is durable in `get-job`. Read the row on a terminal event, at startup and on socket reopen so completion before subscription or during a disconnect is visible. End after the durable outcome and let a failed read reach the caller after repo retry handling. See `mem:backend/jobs`.
|
||||
- Worker progress stages are stable keys, not display strings. Translate known stages in `app.main.ui.jobs.progress` and keep a generic fallback for stages from a newer worker.
|
||||
8
.serena/memories/frontend/workspace-commits.md
Normal file
8
.serena/memories/frontend/workspace-commits.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Workspace commits, rebase and undo
|
||||
|
||||
- Start at `app.main.data.changes`, `app.main.data.persistence.commits` and `app.main.data.workspace.undo`. For the shared change vocabulary see `mem:common/changes-architecture`; for save ordering see `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
- `commit-changes` requires edit permission, no historical preview and no save-failure lock. Its refusal completes an empty stream, not nil. `:ignore-save-lock` is for rollback compensation and information derived from existing commits (position data, component touch), not user edits or an origin allowlist. Remote changes apply through `commit`, outside this local gate.
|
||||
- When a peer commit arrives, undo pending edits for that file, apply the remote change and replay local redo. Read pending edits from both the save queue **and** the unflushed buffer; otherwise the local and server order can disagree. Isolate files and versions, and keep index updates for all replay legs.
|
||||
- An undo group is one user action even if it spans several files; dependent commits such as component sync must inherit it. Persistence uses this same group for rollback. A stacked commit that records undo may inherit the current history entry's group; a repair that records no undo must not inherit it or failure could roll back the previous user action. Let an open nonempty transaction keep its grouping.
|
||||
- Do not move the undo index when an active editor interaction or save lock blocks the corresponding commit; grid editing has its own allowed path. Preserve the pure-translation flag when replaying an undo entry or building one in a test harness. Combining entries keeps that flag only when every entry is a translation, so replay skips the same component and thumbnail work as the original.
|
||||
- Local commits feed independent undo, persistence and render consumers. The WASM-derived text-position commit excludes its own tag from the watcher to avoid a loop.
|
||||
File diff suppressed because one or more lines are too long
8
.serena/memories/frontend/workspace-store.md
Normal file
8
.serena/memories/frontend/workspace-store.md
Normal file
@ -0,0 +1,8 @@
|
||||
# Workspace store and refs
|
||||
|
||||
- `app.main.store` owns the Potok store; `app.main.refs` provides derived refs. `emit!` dispatches and returns nil, not the result of a watch. To inspect a live stream, use `mem:frontend/cljs-repl`.
|
||||
- `app.main.streams` keeps high-frequency WASM modifier and selection-rectangle previews out of the normal store to avoid ref churn; do not treat those previews as committed shape data. See `mem:frontend/workspace-transform-subtleties`.
|
||||
- Preserve page-object map identity when possible: `refs/workspace-page-objects` compares with `identical?`. Keep the selection input equality check before processing selected shapes. Prefer selecting libraries from `refs/files` with component memoization over the broad deprecated `refs/libraries`.
|
||||
- Keyboard modifier state must clear on window blur. Focus mode tracks added and removed objects as the page changes; exit when none remain and restore the surviving pre-focus selection. Otherwise a later draw can re-arm a mode the user already left.
|
||||
- Reloading a workspace initializes again without finalizing the existing one; finalizing would drop transient state. Consumers started by initialization must stop on a newer initialization, not just on exit, or reload doubles undo and other side effects.
|
||||
- Undo and remote rebase: `mem:frontend/workspace-commits`. Save queue and unload guard: `mem:frontend/workspace-state-persistence-subtleties`.
|
||||
@ -1,35 +1,16 @@
|
||||
# Memory Maintenance
|
||||
|
||||
## Discovery Model
|
||||
## Discovery
|
||||
|
||||
- Core principle: progressive discovery through references, building a graph of memories.
|
||||
- Initially, agents are provided with the list of all memories (names only).
|
||||
- Agents should read `mem:critical-info` as the top-level entry point (graph root).
|
||||
This memory should contain references to other memories covering major project domains.
|
||||
The referenced memories shall, in turn, shall contain references to even more specific memories, and so on.
|
||||
The depth of the graph shall depend on the project complexity.
|
||||
- Use topics/folders to group related memories in order to make the content structure explicit.
|
||||
Folders can mirror project structure (e.g. modules like frontend/backend) or topics like debugging, architecture, etc.
|
||||
- Memory references must use a mem: prefix inside backticks, e.g. `mem:frontend/core`.
|
||||
The surrounding text should clearly indicate when to read the memory/which content to expect.
|
||||
The text should provide more precise guidance than the memory name alone,
|
||||
i.e. avoid a reference like "frontend debugging and error handling: `mem:frontend/handling-errors-and-debugging` and instead make clear which concrete aspects are covered in the memory.
|
||||
- Memories themselves should not contain information about when to read them; this is the responsibility of the referring memory.
|
||||
- Start at `mem:critical-info`, then follow the relevant section's `core` and focused references. Group notes by project module or topic.
|
||||
- Use backticked `mem:` references. The caller explains when to read the destination and why (e.g. failed shadow-cljs build or stale hot reload → `mem:frontend/compile-diagnostics`). Don't repeat that routing rule inside the destination.
|
||||
|
||||
## Style
|
||||
## Content and format
|
||||
|
||||
Dense agent notes, not prose docs. Prefer invariants, terse bullets.
|
||||
Avoid obvious context, rationale, and examples unless they prevent likely mistakes.
|
||||
Keep guidance durable and generalizable, not task-local.
|
||||
**No manual line wrapping**, in new and edited memories alike: one line per bullet or paragraph, however long. Memories render adapting to the viewport; hard-wrapped lines degrade rendering and diffs. When you touch a memory that is hard-wrapped, unwrap the whole file in the same change (join each paragraph and each bullet's continuation lines with a single space), so the wrapping does not survive merely because nobody rewrote the file.
|
||||
- Keep stable, non-obvious guidance: decisions and reasons, cross-file invariants, ordering constraints, and environment or tool traps. Point to code or docs for details already evident there, including comments.
|
||||
- Prefer terse bullets. Skip generic advice, one-off task notes, line-level facts and examples that don't prevent a likely mistake.
|
||||
- No manual line wrapping: one line per bullet or paragraph. When editing a hard-wrapped memory, unwrap the whole file.
|
||||
|
||||
## Add/update threshold
|
||||
## Maintenance
|
||||
|
||||
Add or update memories only with stable, non-obvious project conventions that avoid complex rediscovery in the future.
|
||||
Do not restate what the code already says (comments included): keep only what code cannot represent — decisions and their reasons, cross-file invariants, ordering constraints, environment and tool behavior, and traps that break builds.
|
||||
Do not add: quick-read facts; generic language/framework knowledge; one-off task notes; volatile line-level details; behavior likely to change soon.
|
||||
|
||||
## Maintenance Actions
|
||||
|
||||
- Renaming memories: References are updated automatically if handled via Serena's memory rename tool.
|
||||
- Checking for stale memories (e.g. after deletion): Call `serena memories check` for a report.
|
||||
- Serena's memory rename tool updates references. After moving or deleting a note, check incoming links and run `serena memories check` when available.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user