skillhub/docs/frontend-analytics.md
千乘妍 (Xiaoyaner) 66c1dcf64c fix(web): keep docs integration test outside production build inputs
Move the collector example test alongside existing root-level web tests so the web-only Docker context does not require repository documentation. Preserve all assertions and default Vitest discovery; document the boundary.

Verified 1217 tests, focused 12 tests, typecheck, lint, build and a fresh web-only build without repository docs. Original snapshot reproduced TS2307. Independent review passed. Full local image build was blocked by an uncached pnpm download with network disabled; remote image CI remains authoritative.

Signed-off-by: 千乘妍 (Xiaoyaner) <258399167+xiaoyaner0201@users.noreply.github.com>
2026-10-23 04:28:14 +08:00

15 KiB

Passive frontend analytics attributes

SkillHub exposes semantic HTML attributes for separately maintained, optional collectors. It does not collect or send analytics by default. There is no SDK, DataFinder dependency, vendor token, network reporter, app script loader or telemetry configuration switch. The application entrypoint and production Nginx configuration are unchanged. Deployment owners control consent, script delivery, retention, transport and compliance; this is not an official vendor integration or a durable business-event feed.

Contract and scope

data-analytics-id identifies an observable action intent, not its result. Lowercase dotted names are independent of language, visible text and layout. Literal conditional branches distinguish finite business actions (for example, namespace freeze/unfreeze/archive/restore/delete and each confirmation/cancel). No resource, slug, version, user, provider, role, label instance or backend string is interpolated into attributes. Fixed navigation metadata is source-owned. data-analytics-event, where present, describes a native observation boundary; it is a hint for a deployment collector, not an application event dispatcher.

The source inventory covers these domains:

  • Landing/catalog/search: queries, sorting, filters, results, pagination and links.
  • Skills: detail structure, tabs/versions/comparison, documentation and files, acquisition/copy, social actions, labels, visibility and lifecycle confirmations.
  • Publishing: package/folder selection, preview/retry, submission/warnings and avatar editing, staging, retries and cancellation.
  • Suites: catalog/detail, members/versions, editor/import, publishing tasks, lifecycle and destructive actions.
  • Reviews, promotions, reports and governance: queues, detail inspection, dispositions, layered confirmations, rejection editing, cancellation and retry.
  • Namespaces: management, membership/import, invitations, ownership and lifecycle.
  • GitHub: collection/settings, discovery, credentials, scheduling/admission, repositories/sources/runs, conflicts and review inspection.
  • Notifications/preferences, account/profile/security/token flows, login, registration/reset/device/CLI authorization, administration and global navigation.

The generated manifest is the authoritative source index: registered routes and their implementations, literal JSX sites, conditional values, static navigation definitions and forwarding sites. Counts are recomputed from the TypeScript AST; they are not quotas. Unique IDs are semantic categories, JSX sites are source declarations, and forwarding sites may have no literal ID until a caller opts in. A wrapper prop is not itself a DOM element. Repeated resources/pages, desktop/mobile navigation and portal instances can share an ID; neither IDs nor source sites count runtime elements, unique users, pageviews, successful operations or exhaustive business coverage.

Development checks (from the repository root with web dependencies installed):

node web/scripts/analytics-manifest.mjs
# After reviewing intentional source changes:
node web/scripts/analytics-manifest.mjs --write
pnpm -C web test src/app/analytics-manifest.test.ts

Do not ship the manifest as a runtime closed enum. A deployment collector should have its own small, explicit event/ID allowlist and update it deliberately.

Original eight compatibility meanings

ID Meaning
search.query.submit Search form submit; button and Enter converge here.
skill.card.open Existing card activation; click or its direct Enter/Space handler.
skill.detail.render Structural detail root after loading/error/missing/deleted guards; not a unique pageview or success.
skill.download.request Package download attempt; authentication/guards may reject it.
skill.command.copy Command-copy attempt for the displayed installation method; not clipboard or installation success.
skill.prompt.copy Agent-prompt-copy attempt; not execution or installation.
skill.publish.request Publish/update/resubmit attempt, never avatar-only save.
skill.publish.confirm Explicit publish warning continuation, never all generic dialogs or avatar-only save.

Installation method tabs distinguish SkillHub and ClawHub; the original command copy ID remains compatible. Public/namespace/private choices and business modes use static categories, not data fetched from the selected object.

Native observation policy and limits

Attributes alone never create events. Choose the native event per host, and count one semantic target per event rather than every marked ancestor:

  • Forms: observe submit, not both submit-button click and submit. Enter and native validation follow existing app behavior. Rejected validation may produce no submit. Search typing/clear is not a search submission.
  • Buttons/links: observe click, including browser-generated keyboard click. Ignore disabled, aria-disabled and data-disabled controls. An enabled click can still fail app guards; busy/authorization semantics remain the application's.
  • Custom DIV cards with existing Enter/Space handlers need that keydown in addition to click. Native buttons must not count both. Tabs generate click from navigation keys; do not count Arrow/Home/End keydown again. Do not invent keyboard handlers for existing mouse-only rows or directories.
  • Native select: observe change. Where the static marker is on an option, read only selectedOptions[0].getAttribute('data-analytics-id'), never option value/text. A select marker describes its context, not the raw choice. Avoid click/change double counting. Checkbox/radio change is an intent, not saved server state.
  • Radix Select items are actual option DOM, sometimes in a portal. Pointerup or Enter/Space on an item is selection intent, not proof that onValueChange committed a new value. Opening the trigger and navigation/highlight are not committed selections. A click-only collector is insufficient. Validate event order with the deployed component/browser version rather than manufacturing app hooks. Trigger *.interact markers cover observable activation/keydown intent, including closed-trigger typeahead; never capture the typed key, infer the chosen value, or call that interaction a committed selection. Typeahead can change selection without opening an item. Keep trigger interaction and item selection-intent metrics separate instead of counting both as the same selection.
  • File inputs: change means a selection was offered, not upload success. Drop is offered files, not accepted/validated files. Picker-opening click differs from change; ignore programmatic input clicks as additional user intent. Never read filenames, paths or file metadata. Picker cancellation is not observed.
  • Crop surface pointer/keyboard interaction is adjustment intent, not proof the crop changed or an image upload succeeded; no coordinates or image data may leave.
  • Explicit cancel/close buttons, including X, preserve workflow-specific meaning. Escape, overlay dismissal, route teardown, browser Back, automatic close and native picker cancel are not reliably observable through these static attrs. Closing an editor is not proof an in-flight request was aborted.

Use document-level delegation for portals; React ancestry is not DOM ancestry. Wrapper forwarding is caller-scoped, including confirmation/cancel and close X; generic UI primitives do not guess business IDs. Keep the nearest semantic target and reject nested unmarked interactive controls rather than attributing them to an ancestor card/form. Synthetic clicks (including temporary download anchors) are not new successful user actions. Do not block or change default behavior, propagation, focus, route history, permissions or app handlers.

skill.detail.render is not an automatic pageview event. SPA route classification, render retries, consent transitions, duplicate initialization and view deduplication are separate collector policies. Never derive these from full URLs/query strings.

Privacy and integration modes

The recommended output allowlist is only { id, event }, each validated against operator-owned static categories. Do not collect textContent/innerHTML, input or option values, clipboard contents, href/full URLs/query/fragment, cookies, storage, identity/account IDs, device codes, tokens, invitation links, private coordinates, filenames/paths, review/report reasons or crop data. Do not scrape arbitrary DOM attributes or reuse test IDs (some intentionally contain resource identifiers).

Disabled integration means no injected script and zero analytics collection. Enabled delivery does not itself authorize collection: initialize only after applicable consent/policy approval, stop on withdrawal, and separately review any outbound adapter and CSP connect destinations. External JS has page privileges; serve reviewed versioned code, restrict access and treat compromise as a security incident. Vendor credentials and ingestion endpoints belong outside core.

The docs-only example exports observeSkillhubIntents({ root, onIntent }). Importing it does not start collection; without an explicit callback it installs no listeners. It has no network, identity, route patching or default output. Its intentionally small allowlist demonstrates click/submit/custom-card keydown only, not every manifest action, Select, crop, file change/drop or pageviews. The callback receives only ID and event kind; it must not enrich them with sensitive context. Initialization is idempotent per root, and the returned function removes listeners. It catches callback errors and never calls preventDefault/stopPropagation. Tests use synthetic data and are not browser or deployment acceptance.

The repository-integration test lives at web/analytics-example.test.ts, alongside the existing root-level web tests. Vitest discovers it with pnpm -C web test; run it alone with pnpm -C web test analytics-example.test.ts. It stays outside the production TypeScript project's src/test inputs because the docs-only example is not present in the web/ Docker build context.

Optional deployment-owned Nginx injection

Prefer a separately maintained same-origin HTTPS module, optionally inserted by Nginx sub_filter, not an app entrypoint modification. Start with the opt-in edge example. It is not loaded by the product. Its loopback HTTP ports and filesystem path are examples behind your existing HTTPS terminator; adapt upstream/listener/file path in isolation first. The operator must supply skillhub-observer.v1.mjs, which may import the example helper and call it with an explicit callback after consent. Delivering only the helper intentionally collects nothing. Do not place either script in the app bundle.

The sample filters only the UI fallback's default text/html type, once per response, inserting a module before </head>. Module loading is deferred and no application code depends on it; missing/failed JS must not stop SkillHub. The exact script location overrides SPA fallback, sets JavaScript MIME and nosniff, and returns 404 if absent. Never return index.html for missing collector/imports. Keep static code versioned and immutable; change the filename when bytes change.

Deployment checklist:

  1. Check nginx -V for http_sub_module (built with --with-http_sub_module or an equivalent loaded module), then nginx -t. Module absence is a blocker, not an invitation to weaken security. Review actual final config with nginx -T.
  2. Upstream Accept-Encoding "" requests uncompressed HTML. Ensure upstream gzip_static/Brotli/CDN compression cannot still send encoded bytes. Filtering compressed input does not work; downstream compression may run after filtering. Leave API, auth, download, asset and runtime-config locations unmodified.
  3. Filtered HTML must not reuse unfiltered validators or cached 304 responses. The example removes upstream ETag/Last-Modified/Content-MD5 and cache headers, suppresses conditional requests and disables proxy cache, serving no-store HTML. Purge old edge/CDN HTML on enable/rollback; test GET/HEAD, conditional headers, existing browser caches and 200/304 behavior. Do not cache injected HTML under the old unfiltered entity validator. API and immutable assets retain their policy.
  4. Preserve existing CSP and all security headers. The script must satisfy the current script-src policy (same-origin alone does not satisfy nonce-only or strict-dynamic policies). A per-response nonce or approved external hash/SRI policy needs deployment-specific coordination; otherwise do not enable injection. Never add unsafe-inline/unsafe-eval or broad wildcards. Any reporter needs an explicitly permitted connect-src endpoint; no reporter exists in core/example. Nginx add_header inheritance is location-sensitive: merge/repeat existing edge security headers as necessary; do not drop or hide upstream CSP to make it work.
  5. Test actual built SkillHub HTML, not just a synthetic HTML fixture: exactly one script for UI routes, none for APIs/assets/downloads/auth endpoints; script MIME, missing-script 404, root/deep links, compression, CSP, disabled delivery and collector failure. Then browser-check native events, portals, guards and consent. A fixture filter probe is not final-config, SkillHub or production acceptance.

Supported sub-path mapping

The sample is root deployment. For a supported /skillhub/ deployment, keep that prefix on the edge-to-app proxy URI (proxy_pass without a trailing slash), and configure the app normally with SKILLHUB_WEB_BASE_PATH=/skillhub/ and matching same-origin API base. Its existing container entrypoint owns internal prefix rewriting; do not rewrite it a second time at the edge.

Adapt the sample's UI location / to location /skillhub/; add an exact /skillhub redirect to /skillhub/; scope the bypass regex to ^/skillhub/(api/|oauth2/|login/oauth2/|\.well-known/|assets/|registry/|runtime-config\.js$|nginx-health). Change BOTH the exact script location and injected src to /skillhub/_skillhub-observe/skillhub-observer.v1.mjs, plus the matching 404 prefix. The alias filesystem path does not gain the URL prefix. Keep other site locations unchanged; do not put sub_filter at http/server scope. Use any supported validated base path consistently, preserving original request URIs. HTTPS/public registry, OAuth callbacks and generated asset URLs still need the normal deployment setup.

Rollback: remove the sub_filter directives/injection location customization, test configuration, reload through the normal deployment procedure, and purge cached HTML. Existing cached versioned JS can remain temporarily but must not be referenced or initialized. Verify new HTML has no script, no callback/reporting occurs and SkillHub remains usable. This document does not authorize production changes.