Skip to content

AI-native design editor. Open-source Figma alternative.

feat: report errors and problems to PostHog error tracking (#1705)

Danila Poyarkovcb2ddde5cc76
diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml
index 76101dea4..219adeba2 100644
--- a/.github/workflows/app.yml
+++ b/.github/workflows/app.yml
@@ -32,6 +32,13 @@ jobs:
# Official releases only: lets the app send its daily ping and, with consent, usage stats.
VITE_OPENPENCIL_FEEDBACK: "on"
+ - name: Upload source maps for error reports
+ env:
+ POSTHOG_CLI_API_KEY: ${{ secrets.POSTHOG_CLI_API_KEY }}
+ POSTHOG_CLI_PROJECT_ID: "267806"
+ POSTHOG_CLI_HOST: https://eu.posthog.com
+ run: bun tools/release/release-packages/src/sourcemaps/publish.ts
+
- uses: cloudflare/wrangler-action@v4
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 64d9bcd49..87309ae14 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -75,6 +75,12 @@ jobs:
bun run generate:icons --target desktop
bun run generate:tauri-menu
bun run build
+ - name: Upload source maps for error reports
+ env:
+ POSTHOG_CLI_API_KEY: ${{ secrets.POSTHOG_CLI_API_KEY }}
+ POSTHOG_CLI_PROJECT_ID: "267806"
+ POSTHOG_CLI_HOST: https://eu.posthog.com
+ run: bun .pipeline/tools/release/release-packages/src/sourcemaps/publish.ts --archive
- name: Prepare and validate npm tarballs
run: |
bun .pipeline/tools/release/release-packages/src/cli.ts prepare
@@ -94,6 +100,7 @@ jobs:
path: |
frontend.tar
release-notes.md
+ OpenPencil_*_sourcemaps.tar.gz
if-no-files-found: error
compression-level: 0
- uses: actions/upload-artifact@v7
diff --git a/bun.lock b/bun.lock
index a5050f54c..b1e3778c1 100644
--- a/bun.lock
+++ b/bun.lock
@@ -45,6 +45,7 @@
"@open-pencil/scene-graph": "workspace:*",
"@open-pencil/vue": "workspace:*",
"@openrouter/ai-sdk-provider": "^3.1.0",
+ "@posthog/core": "1.59.1",
"@smithy/fetch-http-handler": "^5.8.0",
"@stream-markdown/code": "2.0.0-beta.5",
"@tailwindcss/vite": "^4.3.3",
@@ -884,6 +885,7 @@
"dependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
"@open-pencil/package-quality-tools": "workspace:*",
+ "@posthog/cli": "0.18.12",
"@sigstore/bundle": "^5.0.0",
"citty": "^0.1.6",
"es-toolkit": "^1.52.0",
@@ -1993,6 +1995,12 @@
"@poppinss/exception": ["@poppinss/[email protected]", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="],
+ "@posthog/cli": ["@posthog/[email protected]", "", { "dependencies": { "detect-libc": "^2.1.2" }, "bin": { "posthog-cli": "run-posthog-cli.js" } }, "sha512-/eT9riWOkBb9uwsdOxQgW3fan/T3hwT8rvwZCzPl3DAgSBEhzpP59usD0fyFS++X2967E5AQe74nrBw1rywf6A=="],
+
+ "@posthog/core": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/types": "^1.416.0" } }, "sha512-P39YgzQVDh6oz6wAzQXEnoHgTYpM7gifonmVKq1scAJco79h31XmmNVurRq9tTmmyIrr1uX8FHT0riCsyfV9AQ=="],
+
+ "@posthog/types": ["@posthog/[email protected]", "", {}, "sha512-XX7zRYt/vK8AzaD6V+oDquAzacZf5exJv971dja9En8Qf6g84Qvc3rpT0w6hDYYLWrjaSSkdjFfvvoXI0ouJDg=="],
+
"@promptbook/utils": ["@promptbook/[email protected]", "", { "dependencies": { "spacetrim": "0.11.59" } }, "sha512-xm5Ti/Hp3o4xHrsK9Yy3MS6KbDxYbq485hDsFvxqaNA7equHLPdo8H8faTitTeb14QCDfLW4iwCxdVYu5sn6YQ=="],
"@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
diff --git a/changes/1705/added.md b/changes/1705/added.md
new file mode 100644
index 000000000..eef2fa745
--- /dev/null
+++ b/changes/1705/added.md
@@ -0,0 +1 @@
+- Official builds offer to report an unexpected error, or a problem you describe from **File → Report a Problem…**, to the OpenPencil team, optionally with recent diagnostics and the open document; nothing is sent until you choose **Send report**, and the next launch offers the error that ended a crashed session.
diff --git a/desktop/AGENTS.md b/desktop/AGENTS.md
index 98cce1e6c..769b1acf6 100644
--- a/desktop/AGENTS.md
+++ b/desktop/AGENTS.md
@@ -21,3 +21,4 @@ Check `desktop/Cargo.toml`, `desktop/capabilities/**`, and `desktop/tauri.conf.j
- `openpencil://` links are parsed in `desktop/src/launch/links.rs` and queued in `desktop/src/launch/mod.rs`: `open` queues files through `take_pending_open`, `join` queues validated room IDs through `take_pending_rooms`, `cloud` queues Cloud invitations and shared links (UUID, hex secret, `http(s)` server) through `take_pending_cloud_links`; second launches forward their link arguments through the single-instance handler (`launch::links` unit tests).
- On Linux, `run()` sets `__NV_DISABLE_EXPLICIT_SYNC=1` before the Tauri builder only on Wayland, with the NVIDIA driver loaded, under a WebKitGTK older than 2.54.2, and when the variable is unset: those versions commit a frame without an acquire point and the compositor disconnects the app (WebKit bug 324551). Do not add DMABUF or shared-memory overrides; they cost every NVIDIA user rendering speed for a crash this one avoids (`explicit_sync` unit tests).
- SF Symbols are drawn by SwiftUI through the Swift package `desktop/swift/sf-symbols`, linked by `build.rs` on macOS; they are never bundled, served, or read from Apple's font files. `sf_symbols_render` stays a synchronous command so Tauri runs it on the main thread SwiftUI needs, and both commands answer null below macOS 14, which lacks the path operations that cut badge knockouts (`packages/core/tests/icons/sf-symbols/provider.test.ts`).
+- A panic hook installed in `setup` writes the last Rust panic to `last-panic.json` in the app data folder, and `take_last_panic` hands it to the next launch once, which offers it as a report in official builds; the hook calls the default hook first and never panics itself (`desktop/src/system/crash.rs`, `src/app/reports/crash.ts`).
diff --git a/desktop/generated/menu.json b/desktop/generated/menu.json
index 184a38633..4f76f3f33 100644
--- a/desktop/generated/menu.json
+++ b/desktop/generated/menu.json
@@ -29,6 +29,11 @@
"id": "diagnostics",
"label": "Diagnostics…"
},
+ {
+ "id": "report-problem",
+ "label": "Report a Problem…",
+ "feature": "reports"
+ },
{
"type": "separator"
},
diff --git a/desktop/src/lib.rs b/desktop/src/lib.rs
index 518a90a57..6fb705c91 100644
--- a/desktop/src/lib.rs
+++ b/desktop/src/lib.rs
@@ -106,6 +106,7 @@ pub fn run() {
launch::take_pending_open,
launch::take_pending_rooms,
system::env::sharing_disabled_by_env,
+ system::crash::take_last_panic,
launch::take_pending_cloud_links,
system::env::webview_version
])
@@ -122,6 +123,14 @@ pub fn run() {
handle_menu_event(app, event.id().0.as_str());
})
.setup(|app| {
+ // Panics from here on are kept for the next launch to offer as a report.
+ if let Ok(directory) = app.path().app_data_dir() {
+ system::crash::install_panic_hook(
+ directory,
+ app.package_info().version.to_string(),
+ );
+ }
+
// The main window is built here rather than from the config alone, so that pages it
// opens with `window.open` reach the system browser.
let main = app
diff --git a/desktop/src/system/crash.rs b/desktop/src/system/crash.rs
new file mode 100644
index 000000000..1fdeb842c
--- /dev/null
+++ b/desktop/src/system/crash.rs
@@ -0,0 +1,95 @@
+//! The last Rust panic, kept on disk so the next launch can offer to report it.
+
+use std::fs;
+use std::panic::PanicHookInfo;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use tauri::Manager;
+
+const FILE_NAME: &str = "last-panic.json";
+const MAX_MESSAGE_CHARS: usize = 2000;
+
+/// A panic as the frontend reports it: its message and where in the source it happened.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PanicRecord {
+ pub message: String,
+ pub location: Option<String>,
+ pub version: String,
+}
+
+fn panic_message(info: &PanicHookInfo<'_>) -> String {
+ let payload = info.payload();
+ let message = payload
+ .downcast_ref::<&str>()
+ .map(|text| (*text).to_string())
+ .or_else(|| payload.downcast_ref::<String>().cloned())
+ .unwrap_or_else(|| "panic".to_string());
+ message.chars().take(MAX_MESSAGE_CHARS).collect()
+}
+
+fn write_record(directory: &Path, record: &PanicRecord) {
+ let Ok(json) = serde_json::to_vec(record) else {
+ return;
+ };
+ // Best effort: a panic hook must never panic itself.
+ let _ = fs::create_dir_all(directory);
+ let _ = fs::write(directory.join(FILE_NAME), json);
+}
+
+/// Reads and removes the record, so each panic is offered once. A record that cannot be removed
+/// is not offered, as every later launch would offer it again.
+fn take_record(directory: &Path) -> Option<PanicRecord> {
+ let path = directory.join(FILE_NAME);
+ let bytes = fs::read(&path).ok()?;
+ fs::remove_file(&path).ok()?;
+ serde_json::from_slice(&bytes).ok()
+}
+
+/// Records every panic in the app's data folder, after the default hook has printed it.
+pub fn install_panic_hook(directory: PathBuf, version: String) {
+ let previous = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ previous(info);
+ let record = PanicRecord {
+ message: panic_message(info),
+ location: info.location().map(|location| {
+ format!(
+ "{}:{}:{}",
+ location.file(),
+ location.line(),
+ location.column()
+ )
+ }),
+ version: version.clone(),
+ };
+ write_record(&directory, &record);
+ }));
+}
+
+/// The panic the last run recorded, if any; it is removed once read.
+#[tauri::command]
+pub fn take_last_panic(app: tauri::AppHandle) -> Option<PanicRecord> {
+ take_record(&app.path().app_data_dir().ok()?)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_recorded_panic_is_taken_once() {
+ let directory =
+ std::env::temp_dir().join(format!("openpencil-crash-{}", std::process::id()));
+ let record = PanicRecord {
+ message: "index out of bounds".into(),
+ location: Some("src/menu/mod.rs:12:5".into()),
+ version: "0.17.0".into(),
+ };
+ write_record(&directory, &record);
+
+ assert_eq!(take_record(&directory), Some(record));
+ assert_eq!(take_record(&directory), None);
+ let _ = fs::remove_dir_all(directory);
+ }
+}
diff --git a/desktop/src/system/mod.rs b/desktop/src/system/mod.rs
index 77d882b8c..c88f56a70 100644
--- a/desktop/src/system/mod.rs
+++ b/desktop/src/system/mod.rs
@@ -1,6 +1,7 @@
//! The operating system around the editor window: its WebView, environment, browser, and
//! window.
+pub mod crash;
pub mod env;
pub mod opener;
#[cfg(target_os = "macos")]
diff --git a/package.json b/package.json
index 5f4dbaa79..60f361fd3 100644
--- a/package.json
+++ b/package.json
@@ -164,6 +164,7 @@
"@open-pencil/scene-graph": "workspace:*",
"@open-pencil/vue": "workspace:*",
"@openrouter/ai-sdk-provider": "^3.1.0",
+ "@posthog/core": "1.59.1",
"@smithy/fetch-http-handler": "^5.8.0",
"@stream-markdown/code": "2.0.0-beta.5",
"@tailwindcss/vite": "^4.3.3",
diff --git a/packages/docs/overview/privacy.md b/packages/docs/overview/privacy.md
index 375326d11..24ca5d9da 100644
--- a/packages/docs/overview/privacy.md
+++ b/packages/docs/overview/privacy.md
@@ -4,18 +4,23 @@ description: What OpenPencil sends over the network, why it sends anonymous usag
---
<script setup>
-import { describeBuildFields, describePingFields, describeUsageEvents } from '@open-pencil/feedback/contract'
+import {
+ describeBuildFields,
+ describePingFields,
+ describeReportFields,
+ describeUsageEvents
+} from '@open-pencil/feedback/contract'
const columns = [
{ key: 'name', label: 'Field', kind: 'code' },
{ key: 'values', label: 'Values', kind: 'description' }
]
-function rows(fields) {
+function rows(fields, freeForm = 'A version number') {
return fields.map((field) => ({
name: field.name,
description: field.description,
- values: field.values.length > 0 ? field.values.join(', ') : 'A version number'
+ values: field.values.length > 0 ? field.values.join(', ') : freeForm
}))
}
@@ -24,11 +29,12 @@ const buildFields = describeBuildFields()
.map((field) => field.name)
.join(', ')
const events = describeUsageEvents()
+const reportRows = rows(describeReportFields(), 'Free-form')
</script>
# Privacy and Usage Stats
-- Your designs, file names, layer names, text, prompts, and keys never leave your device unless you share or sync them yourself.
+- Your designs, file names, layer names, text, prompts, and keys never leave your device unless you share or sync them yourself, or attach a design to a report you send.
- Official builds send one anonymous ping a day, with no ID. You can turn it off.
- Detailed usage stats are sent only if you say yes when asked, and you can stop at any time.
@@ -68,6 +74,22 @@ These are all the events the app can send. The service at `feedback.openpencil.d
Accepted events go to [PostHog](https://posthog.com), a product analytics service, on its EU cloud. The request comes from our server, not your device, so PostHog never sees your address. Events create no person profiles and skip location lookups. We keep usage stats for 12 months.
+## Error and problem reports
+
+When OpenPencil's own code throws an unexpected error, an official build adds **Report…** to the error notice; errors from browser extensions or without a stack trace get none. If OpenPencil closed unexpectedly after an error, or the desktop app hit an internal error, the next launch offers the same, once. **File → Report a problem…** is always there. Both open a form, and nothing is sent until you choose **Send report**. **What will be sent** shows the exact report before it goes. It has:
+
+- For an error: its type and message, scrubbed of keys, tokens, email addresses, and your user name in folder paths, and where in OpenPencil's code it happened. Errors from AI providers, which can quote your prompts, are sent without a message.
+- What you write, and an email address if you give one so we can reply.
+- The build fields above (<code>{{ buildFields }}</code>), and your install ID if you share usage stats.
+- If you leave **Include recent activity** on: the last 50 events from **Settings → Diagnostics**, such as errors, timings, and file formats. They never include chat messages or tool output.
+- If you turn on **Attach this document**: the open design as a `.fig` file.
+
+Besides the build fields, a report has these fields:
+
+<SdkDataTable :columns="columns" :rows="reportRows" />
+
+Reports go to `feedback.openpencil.dev`, which passes them to PostHog's error tracking on its EU cloud, without your address, a person profile, or a location lookup, and keeps nothing of them itself. An attached design is stored in Cloudflare R2 in the EU, only the OpenPencil team can open it, and it is deleted after 90 days.
+
## Turning it all off
- **Settings → Privacy** has a switch for the ping and one for usage stats.
diff --git a/packages/feedback/.dev.vars.example b/packages/feedback/.dev.vars.example
index c6b4cff2a..30c6c0ed0 100644
--- a/packages/feedback/.dev.vars.example
+++ b/packages/feedback/.dev.vars.example
@@ -5,3 +5,5 @@ TURNSTILE_HOSTNAMES=example.com
# The metrics snapshot's tokens; without real ones its requests fail and nothing is recorded.
GITHUB_TOKEN=github_development
CLOUDFLARE_ANALYTICS_TOKEN=cloudflare_development
+# Signs report upload tokens; any string works locally.
+REPORT_UPLOAD_SECRET=report-upload-development
diff --git a/packages/feedback/AGENTS.md b/packages/feedback/AGENTS.md
index aa682919a..32fbcd7ad 100644
--- a/packages/feedback/AGENTS.md
+++ b/packages/feedback/AGENTS.md
@@ -1,6 +1,6 @@
# Feedback service
-Cloudflare Worker for pings, opt-in usage stats, and the Cloud waitlist; overview and setup in `README.md`.
+Cloudflare Worker for pings, opt-in usage stats, error and problem reports, and the Cloud waitlist; overview and setup in `README.md`.
- Every field the app may send is a closed Valibot list in `src/contract/schema.ts`, with its plain-language meaning in `src/contract/describe.ts`; the privacy page renders both. Add an event or property in both files and update `packages/docs/overview/privacy.md` prose if what is collected changes (`tests/contract.test.ts`).
- The Worker never stores or forwards a client address: rate limits key on it in memory, PostHog requests are new requests from the Worker, and Turnstile is verified without `remoteip` (`tests/ingest.test.ts`). Pings count the sender's network only as Cloudflare's AS number and operator name (`tests/ping.test.ts`).
@@ -11,3 +11,4 @@ Cloudflare Worker for pings, opt-in usage stats, and the Cloud waitlist; overvie
- Outside services (`fetch`, the clock) come through `FeedbackServices`, and bindings through `Env`, so tests run the real app against a local D1 under `bun test` (`tests/harness.ts`).
- The metrics snapshot (`src/snapshot/`) keys every table on the UTC day it describes and replaces whole days in one D1 batch (`replaceDays`), so a rerun corrects a day and a failed write keeps the old rows; it writes the table it resumes from (`site_visits`) last, runs each source on its own, and parses every answer with Valibot before writing (`tests/snapshot.test.ts`). Issues and pull requests are the exception: `repo_items` mirrors each one by number and resumes from its newest update, and the admin API derives daily counts from it.
- Everything under `/admin` passes `requireAccess` (`src/admin/access.ts`), which verifies Cloudflare Access's signed token against the team's keys and the application's audience even though Access already blocks others at the edge; admin answers are `private, no-store` and carry waitlist domains, never addresses (`tests/admin.test.ts`).
+- Reports (`src/reports/`) are forwarded to PostHog and never stored; only the files they declare are kept, in R2 under `reports/<id>/<name>` with fixed names such as `document.fig`, uploaded with an HS256 token bound to the report, each file's name, and its size, and deleted by retention after `REPORT_FILE_RETENTION_DAYS` (`tests/reports.test.ts`).
diff --git a/packages/feedback/README.md b/packages/feedback/README.md
index 3cc1fad42..5434ec4fe 100644
--- a/packages/feedback/README.md
+++ b/packages/feedback/README.md
@@ -6,11 +6,14 @@ The Cloudflare Worker behind `feedback.openpencil.dev`. It is operated by the Op
| --- | --- | --- |
| `POST /ping` | The daily anonymous ping. | One counter per day and build (version, OS, architecture, desktop or web, browser family), and one per day, app, platform, and network (Cloudflare's AS number and operator name). Nothing per install, no addresses. |
| `POST /ingest` | Opt-in usage stats, forwarded to PostHog EU. Refuses any event or property not in `src/contract`. | Nothing. PostHog gets no client address, person profile, or GeoIP. |
+| `POST /reports` | Error and problem reports a person chose to send from the app, forwarded to PostHog EU: errors as `$exception` events for error tracking, which symbolicates their stacks with the source maps each release uploads; problems as `problem_reported`. Answers with the report's ID and, when it declared files, a one-hour upload token. | Nothing. PostHog gets no client address, person profile, or GeoIP. |
+| `PUT /reports/:id/files/:name` | Uploads one file the report declared, at its declared size, with the report's upload token. | The file in the EU R2 bucket `openpencil-reports`, deleted after 90 days. |
+| `GET /admin/reports/:id/files/:name` | Downloads a report's file, behind Cloudflare Access; the PostHog event links to it. | Nothing. |
| `GET /admin/` | The team's metrics dashboard, built from the app's `metrics.html` (`bun run build:metrics` writes `dist-metrics/`, which Wrangler uploads as the Worker's assets), behind Cloudflare Access. | Nothing. |
| `GET /admin/api/snapshot?start&end` | The metrics dashboard's data for a range of UTC days, behind Cloudflare Access. | Nothing; it reads pings, snapshots, and the waitlist from D1 (email domains only) and asks PostHog for usage. |
| `POST /waitlist` | OpenPencil Cloud waitlist sign-ups from the website and the web app's Settings, checked by Turnstile and confirmed by email. | The address and optional note; unconfirmed sign-ups are removed after seven days. |
-Two daily cron jobs run besides the routes. Just after midnight UTC the metrics snapshot records the day that ended for the team's metrics dashboard: GitHub stars and forks, running download totals per release and kind of file (installers, macOS updates, and `latest.json` update checks), repository views, clones, and referrers, and Cloudflare's visits to `openpencil.dev` and `app.openpencil.dev` with the website's top pages and countries. It also mirrors the repository's issues and pull requests (author association, opening, closing, and merge times), syncing only what changed since the last run, so open counts per day go back to the repository's start. GitHub keeps traffic for 14 days and Cloudflare's Free plan keeps visits for 31, so these tables are the only lasting history; each run also fetches again the last few days Cloudflare may still have been counting, and fills any missing days it still can. At 03:17 UTC, retention deletes unconfirmed waitlist sign-ups.
+Two daily cron jobs run besides the routes. Just after midnight UTC the metrics snapshot records the day that ended for the team's metrics dashboard: GitHub stars and forks, running download totals per release and kind of file (installers, macOS updates, and `latest.json` update checks), repository views, clones, and referrers, and Cloudflare's visits to `openpencil.dev` and `app.openpencil.dev` with the website's top pages and countries. It also mirrors the repository's issues and pull requests (author association, opening, closing, and merge times), syncing only what changed since the last run, so open counts per day go back to the repository's start. GitHub keeps traffic for 14 days and Cloudflare's Free plan keeps visits for 31, so these tables are the only lasting history; each run also fetches again the last few days Cloudflare may still have been counting, and fills any missing days it still can. At 03:17 UTC, retention deletes unconfirmed waitlist sign-ups and report files older than 90 days.
`@open-pencil/feedback/contract` holds the request schemas and the event list, and `@open-pencil/feedback/client` is a client typed by the Worker's routes (`hc<FeedbackAPI>`). The app sends through that client and the privacy page renders its tables from the contract, so the documented, sent, and accepted data cannot drift apart.
@@ -39,3 +42,4 @@ Done once on the Cloudflare account; `.github/workflows/feedback.yml` deploys ev
5. For the metrics snapshot, `bunx wrangler secret put GITHUB_TOKEN` with a fine-grained token for the repository in `GITHUB_REPOSITORY` that has read-only **Administration** access, which the traffic API requires (every token can already read the public repository's releases, issues, and pull requests), and `bunx wrangler secret put CLOUDFLARE_ANALYTICS_TOKEN` with an account API token that has **Zone → Analytics → Read** on the zone in `SITE_ZONE_ID`.
6. For the dashboard's API, create a Cloudflare Access self-hosted application for `feedback.openpencil.dev/admin/*` that allows the team's addresses (add the One-time PIN login method for people without a Cloudflare account), then `bunx wrangler secret put ACCESS_TEAM_DOMAIN` with `https://<team>.cloudflareaccess.com` and `bunx wrangler secret put ACCESS_AUD` with the application's audience tag. Until both are set, `/admin` refuses every request.
7. Create a PostHog personal API key scoped to the project in `POSTHOG_PROJECT_ID` with only **Query: Read**, then `bunx wrangler secret put POSTHOG_PERSONAL_KEY`.
+8. For reports, `bunx wrangler r2 bucket create openpencil-reports --jurisdiction eu`, then `bunx wrangler secret put REPORT_UPLOAD_SECRET` with a long random string (`openssl rand -hex 32`), which signs upload tokens.
diff --git a/packages/feedback/package.json b/packages/feedback/package.json
index 635c3de1f..2ce1797fe 100644
--- a/packages/feedback/package.json
+++ b/packages/feedback/package.json
@@ -3,7 +3,7 @@
"version": "0.17.0-beta.1",
"private": true,
"license": "MIT",
- "description": "The OpenPencil feedback service on Cloudflare Workers: usage pings, opt-in usage stats, the Cloud waitlist, and the daily metrics snapshot.",
+ "description": "The OpenPencil feedback service on Cloudflare Workers: usage pings, opt-in usage stats, error and problem reports, the Cloud waitlist, and the daily metrics snapshot.",
"type": "module",
"imports": {
"#feedback/*": "./src/*",
diff --git a/packages/feedback/src/admin/route.ts b/packages/feedback/src/admin/route.ts
index 2c8c3da85..e3a7ec7b0 100644
--- a/packages/feedback/src/admin/route.ts
+++ b/packages/feedback/src/admin/route.ts
@@ -1,11 +1,18 @@
-import { metricsQuerySchema } from '#feedback/contract'
+import { metricsQuerySchema, reportFileNameSchema } from '#feedback/contract'
import type { FeedbackEnv, FeedbackServices } from '#feedback/env'
import { validatedQuery } from '#feedback/http/request'
+import { reportFileKey } from '#feedback/reports/files'
import { Hono } from 'hono'
+import * as v from 'valibot'
import { requireAccess } from './access'
import { buildSnapshot } from './snapshot'
+const reportFileParamsSchema = v.object({
+ reportId: v.pipe(v.string(), v.uuid()),
+ name: reportFileNameSchema
+})
+
/**
* The metrics dashboard's page and API, behind Cloudflare Access. Answers are for one signed-in
* person, so nothing between here and the browser may keep a copy.
@@ -20,6 +27,19 @@ export function adminRoutes(services: FeedbackServices) {
c.header('Cache-Control', 'private, no-store')
return c.json(await buildSnapshot(c.env, services, c.req.valid('query')), 200)
})
+ // A file attached to a report, linked from its PostHog event; always a download, never rendered.
+ .get('/admin/reports/:reportId/files/:name', async (c) => {
+ const params = v.safeParse(reportFileParamsSchema, c.req.param())
+ if (!params.success) return c.notFound()
+ const { reportId, name } = params.output
+ const object = await c.env.REPORTS.get(reportFileKey(reportId, name))
+ if (!object) return c.notFound()
+ return c.body(await object.arrayBuffer(), 200, {
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Disposition': `attachment; filename="${reportId}-${name}"`,
+ 'Cache-Control': 'private, no-store'
+ })
+ })
.get('/admin', (c) => c.redirect('/admin/'))
// The page and its files, from the Worker's static assets once Access has let the request in.
.get('/admin/*', async (c) => {
diff --git a/packages/feedback/src/app.ts b/packages/feedback/src/app.ts
index af7364fd7..c9b08415d 100644
--- a/packages/feedback/src/app.ts
+++ b/packages/feedback/src/app.ts
@@ -6,11 +6,13 @@ import type { FeedbackEnv, FeedbackServices } from './env'
import { allowOpenPencilOrigins } from './http/cors'
import { ingestRoutes } from './ingest/route'
import { pingRoutes } from './ping/route'
+import { reportRoutes } from './reports/route'
import { waitlistRoutes } from './waitlist/route'
export type { FeedbackBindings, FeedbackEnv, FeedbackServices } from './env'
const MAX_BODY_BYTES = 16 * 1024
+const limitBody = bodyLimit({ maxSize: MAX_BODY_BYTES })
/** The real outside world; tests pass their own. */
export const defaultServices: FeedbackServices = {
@@ -19,13 +21,17 @@ export const defaultServices: FeedbackServices = {
}
export function createFeedbackApp(services: FeedbackServices = defaultServices) {
- return new Hono<FeedbackEnv>()
- .use('*', allowOpenPencilOrigins)
- .use('*', bodyLimit({ maxSize: MAX_BODY_BYTES }))
- .route('/', pingRoutes(services))
- .route('/', ingestRoutes(services))
- .route('/', waitlistRoutes(services))
- .route('/', adminRoutes(services))
+ return (
+ new Hono<FeedbackEnv>()
+ .use('*', allowOpenPencilOrigins)
+ // Reports set their own limits: a report's body is larger, and an attached file far larger.
+ .use('*', (c, next) => (c.req.path.startsWith('/reports') ? next() : limitBody(c, next)))
+ .route('/', pingRoutes(services))
+ .route('/', reportRoutes(services))
+ .route('/', ingestRoutes(services))
+ .route('/', waitlistRoutes(services))
+ .route('/', adminRoutes(services))
+ )
}
/** The service's routes and request bodies, for `hc<FeedbackAPI>` clients. */
diff --git a/packages/feedback/src/contract/describe.ts b/packages/feedback/src/contract/describe.ts
index 5d2b83a4d..9cb920863 100644
--- a/packages/feedback/src/contract/describe.ts
+++ b/packages/feedback/src/contract/describe.ts
@@ -1,4 +1,11 @@
-import { pingSchema, usageEventSchema, type UsageEvent } from './schema'
+import {
+ pingSchema,
+ REPORT_FILE_NAMES,
+ reportSchema,
+ usageEventSchema,
+ type Report,
+ type UsageEvent
+} from './schema'
export interface FieldDescription {
name: string
@@ -104,3 +111,46 @@ export function describeUsageEvents(): UsageEventDescription[] {
}
})
}
+
+/** A key of any kind of report, not only the keys every kind shares. */
+type ReportKey<R = Report> = R extends unknown ? keyof R : never
+type ReportField = Exclude<ReportKey, (typeof BUILD_FIELDS)[number]>
+
+/** Plain-language meaning of each report field besides the build; the privacy page renders these. */
+const REPORT_DESCRIPTIONS: Record<ReportField, string> = {
+ kind: 'An error the app caught, or a problem you describe.',
+ exceptions:
+ 'For an error: each error in its chain, with its type, its scrubbed message, whether the app handled it, where it was raised, and the code locations it passed through.',
+ installId: 'Your install ID, only while you share usage stats.',
+ release: 'Which release the app’s code came from, so the code locations can be read.',
+ note: 'What you wrote.',
+ email: 'The email address you gave, if any, so we can reply.',
+ steps:
+ 'If you include recent activity: the latest diagnostics events, each with its name, category, level, time, and scrubbed details.',
+ files: 'If you attach the open document: the name it is sent under and its size.'
+}
+
+const REPORT_FIELDS = [
+ 'kind',
+ 'exceptions',
+ 'installId',
+ 'release',
+ 'note',
+ 'email',
+ 'steps',
+ 'files'
+] as const satisfies readonly ReportField[]
+
+const REPORT_VALUES: Partial<Record<ReportField, readonly string[]>> = {
+ kind: reportSchema.options.map((option) => option.entries.kind.literal),
+ files: REPORT_FILE_NAMES
+}
+
+/** Every field a report may carry besides the build fields. */
+export function describeReportFields(): FieldDescription[] {
+ return REPORT_FIELDS.map((name) => ({
+ name,
+ description: REPORT_DESCRIPTIONS[name],
+ values: REPORT_VALUES[name] ?? []
+ }))
+}
diff --git a/packages/feedback/src/contract/index.ts b/packages/feedback/src/contract/index.ts
index 7274ec306..ce7caa993 100644
--- a/packages/feedback/src/contract/index.ts
+++ b/packages/feedback/src/contract/index.ts
@@ -1,3 +1,8 @@
export * from './schema'
-export { describeBuildFields, describePingFields, describeUsageEvents } from './describe'
+export {
+ describeBuildFields,
+ describePingFields,
+ describeReportFields,
+ describeUsageEvents
+} from './describe'
export type { FieldDescription, UsageEventDescription } from './describe'
diff --git a/packages/feedback/src/contract/schema.ts b/packages/feedback/src/contract/schema.ts
index 8d7f7673a..967a897aa 100644
--- a/packages/feedback/src/contract/schema.ts
+++ b/packages/feedback/src/contract/schema.ts
@@ -126,11 +126,13 @@ export type UsageEventName = UsageEvent['name']
export const USAGE_BATCH_LIMIT = 50
+/** A random ID made on the device when its user agreed to usage stats; it names no person or account. */
+export const installIdSchema = v.pipe(v.string(), v.regex(/^[0-9a-f]{32}$/))
+
/** A batch of usage events from one install that agreed to share them. */
export const usageBatchSchema = v.strictObject({
...buildEntries,
- /** A random ID made on the device when its user agreed; it names no person or account. */
- installId: v.pipe(v.string(), v.regex(/^[0-9a-f]{32}$/)),
+ installId: installIdSchema,
events: v.pipe(v.array(usageEventSchema), v.minLength(1), v.maxLength(USAGE_BATCH_LIMIT))
})
export type UsageBatch = v.InferOutput<typeof usageBatchSchema>
@@ -308,3 +310,127 @@ export const metricsSnapshotSchema = v.object({
usage: v.nullable(metricsUsageSchema)
})
export type MetricsSnapshot = v.InferOutput<typeof metricsSnapshotSchema>
+
+/** How long the files attached to a report are kept before retention deletes them. */
+export const REPORT_FILE_RETENTION_DAYS = 90
+export const REPORT_FILE_MAX_BYTES = 50 * 1024 * 1024
+export const REPORT_STEPS_LIMIT = 50
+/** The largest report body the service takes; the app leaves out the oldest steps to fit it. */
+export const REPORT_BODY_MAX_BYTES = 256 * 1024
+export const REPORT_FRAMES_LIMIT = 100
+export const REPORT_NOTE_MAX_LENGTH = 5000
+
+/** Where an error was caught: the window, an unhandled rejection, a Vue component, or the desktop shell. */
+export const REPORT_ERROR_SOURCES = ['window', 'rejection', 'vue', 'panic'] as const
+export type ReportErrorSource = (typeof REPORT_ERROR_SOURCES)[number]
+
+export const REPORT_STEP_LEVELS = ['debug', 'info', 'warning', 'error'] as const
+
+const text = (max: number) => v.pipe(v.string(), v.maxLength(max))
+const positionSchema = v.pipe(v.number(), v.integer(), v.minValue(0))
+const uuidSchema = v.pipe(v.string(), v.uuid())
+
+/** One stack frame as PostHog's error tracking reads it; `chunk_id` points it at an uploaded source map. */
+const frameSchema = v.strictObject({
+ platform: v.literal('web:javascript'),
+ filename: v.optional(text(1024)),
+ function: v.optional(text(256)),
+ lineno: v.optional(positionSchema),
+ colno: v.optional(positionSchema),
+ in_app: v.optional(v.boolean()),
+ chunk_id: v.optional(uuidSchema)
+})
+
+/** One error in PostHog's `$exception_list` shape; a cause chain sends several. */
+const exceptionSchema = v.strictObject({
+ type: v.pipe(v.string(), v.minLength(1), v.maxLength(128)),
+ value: v.optional(text(1000)),
+ mechanism: v.strictObject({
+ handled: v.boolean(),
+ synthetic: v.boolean(),
+ type: v.picklist(REPORT_ERROR_SOURCES)
+ }),
+ stacktrace: v.optional(
+ v.strictObject({
+ type: v.literal('raw'),
+ frames: v.pipe(v.array(frameSchema), v.maxLength(REPORT_FRAMES_LIMIT))
+ })
+ )
+})
+
+const attributeKeySchema = v.pipe(v.string(), v.regex(/^[A-Za-z][\w.]{0,63}$/))
+
+/** A recent diagnostics event, scrubbed on the device, that led up to the report. */
+const stepSchema = v.strictObject({
+ name: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9_.]{0,63}$/)),
+ category: v.pipe(v.string(), v.regex(/^[a-z]{1,32}$/)),
+ level: v.picklist(REPORT_STEP_LEVELS),
+ timestamp: v.pipe(v.string(), v.isoTimestamp()),
+ attributes: v.pipe(
+ v.record(attributeKeySchema, v.nullable(v.union([text(4000), v.number(), v.boolean()]))),
+ v.maxEntries(24)
+ )
+})
+
+/**
+ * The files a report may attach, each under this fixed name, never its own: the open document.
+ * A name joins the list when the app starts to send that file.
+ */
+export const REPORT_FILE_NAMES = ['document.fig'] as const
+export const reportFileNameSchema = v.picklist(REPORT_FILE_NAMES)
+export type ReportFileName = v.InferOutput<typeof reportFileNameSchema>
+
+const reportFileSchema = v.strictObject({
+ name: reportFileNameSchema,
+ size: v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(REPORT_FILE_MAX_BYTES))
+})
+
+const reportEntries = {
+ ...buildSchema.entries,
+ /** Present only when the install shares usage stats, so the report joins its usage events. */
+ installId: v.optional(installIdSchema),
+ /** The PostHog release the app's chunks carry, which picks the source maps for its frames. */
+ release: v.optional(uuidSchema),
+ note: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(REPORT_NOTE_MAX_LENGTH))),
+ email: v.optional(v.pipe(v.string(), v.trim(), v.maxLength(254), v.email())),
+ steps: v.optional(v.pipe(v.array(stepSchema), v.maxLength(REPORT_STEPS_LIMIT))),
+ files: v.optional(
+ v.pipe(
+ v.array(reportFileSchema),
+ v.maxLength(REPORT_FILE_NAMES.length),
+ v.check(
+ (files) => new Set(files.map((file) => file.name)).size === files.length,
+ 'Attached files need distinct names'
+ )
+ )
+ )
+}
+
+/**
+ * A report a person chose to send: an error the app caught, or a problem they describe. Nothing
+ * is sent without their click; the app shows them this body before it goes.
+ */
+export const reportSchema = v.variant('kind', [
+ v.strictObject({
+ kind: v.literal('error'),
+ exceptions: v.pipe(v.array(exceptionSchema), v.minLength(1), v.maxLength(5)),
+ ...reportEntries
+ }),
+ v.strictObject({
+ kind: v.literal('problem'),
+ ...reportEntries,
+ note: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(REPORT_NOTE_MAX_LENGTH))
+ })
+])
+export type Report = v.InferOutput<typeof reportSchema>
+export type ReportException = v.InferOutput<typeof exceptionSchema>
+export type ReportFrame = v.InferOutput<typeof frameSchema>
+export type ReportStep = v.InferOutput<typeof stepSchema>
+export type ReportFile = v.InferOutput<typeof reportFileSchema>
+
+/** What `POST /reports` answers: the report's ID and, when it declared files, the token that uploads them. */
+export const reportReceiptSchema = v.strictObject({
+ reportId: uuidSchema,
+ uploadToken: v.nullable(v.string())
+})
+export type ReportReceipt = v.InferOutput<typeof reportReceiptSchema>
diff --git a/packages/feedback/src/env.ts b/packages/feedback/src/env.ts
index b8a154a86..7c0874edb 100644
--- a/packages/feedback/src/env.ts
+++ b/packages/feedback/src/env.ts
@@ -1,4 +1,19 @@
-import type { D1Database, Fetcher, RateLimit, SendEmail } from '@cloudflare/workers-types/index'
+import type {
+ D1Database,
+ Fetcher,
+ R2Bucket,
+ R2PutOptions,
+ RateLimit,
+ SendEmail
+} from '@cloudflare/workers-types/index'
+
+/**
+ * The report files bucket, as the Worker uses it. `put` takes a request body as it arrives, a
+ * stream of declared length, which the Workers types spell as their own `ReadableStream`.
+ */
+export type ReportsBucket = Pick<R2Bucket, 'get' | 'head' | 'list' | 'delete'> & {
+ put(key: string, value: ReadableStream | ArrayBuffer, options?: R2PutOptions): Promise<unknown>
+}
/**
* The Worker's bindings, from `wrangler.jsonc` and its secrets. They are declared here with
@@ -14,6 +29,12 @@ export interface FeedbackBindings {
PING_LIMITER: RateLimit
INGEST_LIMITER: RateLimit
WAITLIST_LIMITER: RateLimit
+ /** Counts report submissions and file uploads together. */
+ REPORT_LIMITER: RateLimit
+ /** Files people attach to error and problem reports, kept for `REPORT_FILE_RETENTION_DAYS`. */
+ REPORTS: ReportsBucket
+ /** Signs the short-lived token that lets a report's sender upload the files it declared. */
+ REPORT_UPLOAD_SECRET: string
POSTHOG_HOST: string
POSTHOG_KEY: string
EMAIL_FROM: string
diff --git a/packages/feedback/src/http/cors.ts b/packages/feedback/src/http/cors.ts
index cb0840a21..3eec93238 100644
--- a/packages/feedback/src/http/cors.ts
+++ b/packages/feedback/src/http/cors.ts
@@ -16,7 +16,8 @@ export const ALLOWED_ORIGINS = [
export const allowOpenPencilOrigins = cors({
origin: ALLOWED_ORIGINS,
- allowMethods: ['POST'],
- allowHeaders: ['Content-Type'],
+ allowMethods: ['POST', 'PUT'],
+ // `Authorization` carries a report's upload token.
+ allowHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400
})
diff --git a/packages/feedback/src/reports/files.ts b/packages/feedback/src/reports/files.ts
new file mode 100644
index 000000000..d3feaab0f
--- /dev/null
+++ b/packages/feedback/src/reports/files.ts
@@ -0,0 +1,27 @@
+import { REPORT_FILE_RETENTION_DAYS } from '#feedback/contract'
+import type { ReportsBucket } from '#feedback/env'
+
+const PREFIX = 'reports/'
+const DAY_MS = 24 * 60 * 60 * 1000
+
+/** Where a report's attached file lives in the bucket. */
+export function reportFileKey(reportId: string, name: string): string {
+ return `${PREFIX}${reportId}/${name}`
+}
+
+/** Deletes attached files older than `REPORT_FILE_RETENTION_DAYS`, as the privacy page promises. */
+export async function deleteExpiredReportFiles(bucket: ReportsBucket, now: Date): Promise<number> {
+ const cutoff = now.getTime() - REPORT_FILE_RETENTION_DAYS * DAY_MS
+ let deleted = 0
+ let cursor: string | undefined
+ do {
+ const page = await bucket.list({ prefix: PREFIX, cursor })
+ const expired = page.objects
+ .filter((object) => object.uploaded.getTime() < cutoff)
+ .map((object) => object.key)
+ if (expired.length > 0) await bucket.delete(expired)
+ deleted += expired.length
+ cursor = page.truncated ? page.cursor : undefined
+ } while (cursor)
+ return deleted
+}
diff --git a/packages/feedback/src/reports/posthog.ts b/packages/feedback/src/reports/posthog.ts
new file mode 100644
index 000000000..22ffaae5d
--- /dev/null
+++ b/packages/feedback/src/reports/posthog.ts
@@ -0,0 +1,64 @@
+import type { Report, ReportStep } from '#feedback/contract'
+import { mapKeys, pick } from 'es-toolkit'
+
+const BUILD_KEYS = ['version', 'platform', 'arch', 'app', 'browser'] as const
+
+/** Where the team opens a report's attached files, behind Cloudflare Access. */
+export function reportFileURL(origin: string, reportId: string, name: string): string {
+ return `${origin}/admin/reports/${reportId}/files/${name}`
+}
+
+/** A diagnostics event as one of PostHog's exception steps, its attributes beside the message. */
+function exceptionStep(step: ReportStep) {
+ return {
+ $message: step.name,
+ $timestamp: step.timestamp,
+ category: step.category,
+ level: step.level,
+ ...mapKeys(step.attributes, (_value, key) => `attribute_${key}`)
+ }
+}
+
+/**
+ * PostHog's `/batch/` body for one report: an `$exception` for an error, which error tracking
+ * groups into issues, or `problem_reported` for a problem a person describes. Like usage events,
+ * it creates no person profile and skips GeoIP, and the request comes from the Worker.
+ */
+export function toPostHogReport(
+ report: Report,
+ options: { apiKey: string; reportId: string; origin: string; timestamp: string }
+) {
+ const { kind, installId, release, note, email, steps, files } = report
+ const properties = {
+ ...pick(report, BUILD_KEYS),
+ report_id: options.reportId,
+ report_note: note ?? null,
+ report_email: email ?? null,
+ report_files: (files ?? []).map((file) =>
+ reportFileURL(options.origin, options.reportId, file.name)
+ ),
+ ...(release && { $release_id: release }),
+ $lib: 'openpencil',
+ $process_person_profile: false,
+ $geoip_disable: true
+ }
+ const exception =
+ kind === 'error'
+ ? {
+ $exception_list: report.exceptions,
+ $exception_level: 'error',
+ $exception_steps: (steps ?? []).map(exceptionStep)
+ }
+ : { report_steps: (steps ?? []).map(exceptionStep) }
+ return {
+ api_key: options.apiKey,
+ batch: [
+ {
+ event: kind === 'error' ? '$exception' : 'problem_reported',
+ timestamp: options.timestamp,
+ distinct_id: installId ?? options.reportId,
+ properties: { ...properties, ...exception }
+ }
+ ]
+ }
+}
diff --git a/packages/feedback/src/reports/route.ts b/packages/feedback/src/reports/route.ts
new file mode 100644
index 000000000..2f9603ede
--- /dev/null
+++ b/packages/feedback/src/reports/route.ts
@@ -0,0 +1,87 @@
+import {
+ REPORT_BODY_MAX_BYTES,
+ reportFileNameSchema,
+ reportSchema,
+ type ReportReceipt
+} from '#feedback/contract'
+import type { FeedbackEnv, FeedbackServices } from '#feedback/env'
+import { rateLimited, validatedJSON } from '#feedback/http/request'
+import { Hono } from 'hono'
+import { bodyLimit } from 'hono/body-limit'
+import * as v from 'valibot'
+
+import { reportFileKey } from './files'
+import { toPostHogReport } from './posthog'
+import { allowedUpload, signUploadToken } from './upload'
+
+const uploadParamsSchema = v.object({
+ reportId: v.pipe(v.string(), v.uuid()),
+ name: reportFileNameSchema
+})
+
+/**
+ * Error and problem reports a person chose to send. The report goes to PostHog as it arrives and
+ * nothing of it is stored here; files it declared are uploaded next, one request each, with the
+ * token the answer carries, and kept in R2 until retention deletes them.
+ */
+export function reportRoutes(services: FeedbackServices) {
+ const limited = rateLimited((env) => env.REPORT_LIMITER)
+ return new Hono<FeedbackEnv>()
+ .post(
+ '/reports',
+ bodyLimit({ maxSize: REPORT_BODY_MAX_BYTES }),
+ limited,
+ validatedJSON(reportSchema),
+ async (c) => {
+ const report = c.req.valid('json')
+ const reportId = crypto.randomUUID()
+ const now = services.now()
+ // Signed first, so a failure here stops the report before PostHog receives it.
+ const files = report.files ?? []
+ const receipt: ReportReceipt = {
+ reportId,
+ uploadToken:
+ files.length > 0
+ ? await signUploadToken(c.env.REPORT_UPLOAD_SECRET, reportId, files, now)
+ : null
+ }
+ const body = toPostHogReport(report, {
+ apiKey: c.env.POSTHOG_KEY,
+ reportId,
+ origin: new URL(c.req.url).origin,
+ timestamp: now.toISOString()
+ })
+ const response = await services
+ .fetch(`${c.env.POSTHOG_HOST}/batch/`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body)
+ })
+ .catch(() => null)
+ if (!response?.ok) return c.body(null, 502)
+ return c.json(receipt, 201)
+ }
+ )
+ .put('/reports/:reportId/files/:name', limited, async (c) => {
+ const params = v.safeParse(uploadParamsSchema, c.req.param())
+ const token = c.req.header('authorization')?.match(/^Bearer (\S+)$/)?.[1]
+ if (!params.success || !token) return c.body(null, 403)
+ const { reportId, name } = params.output
+ const file = await allowedUpload(
+ c.env.REPORT_UPLOAD_SECRET,
+ token,
+ reportId,
+ name,
+ services.now()
+ )
+ if (!file) return c.body(null, 403)
+ // The runtime holds a body to its declared length, so the declared size bounds the upload.
+ if (Number(c.req.header('content-length')) !== file.size) return c.body(null, 400)
+ const stream = c.req.raw.body
+ if (!stream) return c.body(null, 400)
+ await c.env.REPORTS.put(reportFileKey(reportId, name), stream, {
+ httpMetadata: { contentType: 'application/octet-stream' }
+ })
+ return c.body(null, 204)
+ })
+}
diff --git a/packages/feedback/src/reports/upload.ts b/packages/feedback/src/reports/upload.ts
new file mode 100644
index 000000000..7046ad2e4
--- /dev/null
+++ b/packages/feedback/src/reports/upload.ts
@@ -0,0 +1,60 @@
+import { reportFileNameSchema, type ReportFile } from '#feedback/contract'
+import { jwtVerify, SignJWT } from 'jose'
+import * as v from 'valibot'
+
+/** Long enough for a slow connection to upload the largest file, short enough to be useless later. */
+export const UPLOAD_TOKEN_TTL_SECONDS = 60 * 60
+
+const ISSUER = 'feedback.openpencil.dev'
+const AUDIENCE = 'report-upload'
+
+const claimsSchema = v.object({
+ sub: v.pipe(v.string(), v.uuid()),
+ files: v.array(v.object({ name: reportFileNameSchema, size: v.number() }))
+})
+
+function key(secret: string): Uint8Array {
+ return new TextEncoder().encode(secret)
+}
+
+/** A token that lets the report's sender upload exactly the files, and sizes, it declared. */
+export async function signUploadToken(
+ secret: string,
+ reportId: string,
+ files: ReportFile[],
+ now: Date
+): Promise<string> {
+ const issuedAt = Math.floor(now.getTime() / 1000)
+ return new SignJWT({ files })
+ .setProtectedHeader({ alg: 'HS256' })
+ .setIssuer(ISSUER)
+ .setAudience(AUDIENCE)
+ .setSubject(reportId)
+ .setIssuedAt(issuedAt)
+ .setExpirationTime(issuedAt + UPLOAD_TOKEN_TTL_SECONDS)
+ .sign(key(secret))
+}
+
+/** The file a token allows under `name` for `reportId`, or null for any other token or file. */
+export async function allowedUpload(
+ secret: string,
+ token: string,
+ reportId: string,
+ name: string,
+ now: Date
+): Promise<ReportFile | null> {
+ try {
+ const { payload } = await jwtVerify(token, key(secret), {
+ issuer: ISSUER,
+ audience: AUDIENCE,
+ algorithms: ['HS256'],
+ requiredClaims: ['exp'],
+ currentDate: now
+ })
+ const claims = v.parse(claimsSchema, payload)
+ if (claims.sub !== reportId) return null
+ return claims.files.find((file) => file.name === name) ?? null
+ } catch {
+ return null
+ }
+}
diff --git a/packages/feedback/src/retention/index.ts b/packages/feedback/src/retention/index.ts
index 2d75bbf12..9e17f028f 100644
--- a/packages/feedback/src/retention/index.ts
+++ b/packages/feedback/src/retention/index.ts
@@ -1,8 +1,18 @@
import { createFeedbackDatabase } from '#feedback/db'
import type { FeedbackBindings } from '#feedback/env'
+import { deleteExpiredReportFiles } from '#feedback/reports/files'
import { deleteUnconfirmedSignups } from '#feedback/waitlist/signup'
-/** The daily cron: drops what the privacy page says we do not keep. Ping counts hold no personal data and stay. */
+/**
+ * The daily cron: drops what the privacy page says we do not keep, unconfirmed sign-ups and old
+ * report files. Ping counts hold no personal data and stay.
+ */
export async function runRetention(env: FeedbackBindings, now: Date): Promise<void> {
- await deleteUnconfirmedSignups(createFeedbackDatabase(env.DB), now)
+ // Each cleanup runs whether or not the other fails; the first failure is still thrown.
+ const results = await Promise.allSettled([
+ deleteUnconfirmedSignups(createFeedbackDatabase(env.DB), now),
+ deleteExpiredReportFiles(env.REPORTS, now)
+ ])
+ const failed = results.find((result) => result.status === 'rejected')
+ if (failed) throw failed.reason
}
diff --git a/packages/feedback/tests/access.ts b/packages/feedback/tests/access.ts
new file mode 100644
index 000000000..ada894ae5
--- /dev/null
+++ b/packages/feedback/tests/access.ts
@@ -0,0 +1,35 @@
+import { exportJWK, generateKeyPair, SignJWT, type CryptoKey } from 'jose'
+
+import type { TestService } from './harness'
+
+/** The Access team and application `tests/harness.ts` configures the service with. */
+export const ACCESS_TEAM = 'https://openpencil.cloudflareaccess.com'
+export const ACCESS_AUDIENCE = 'admin-audience'
+
+/**
+ * Publishes a fresh signing key as the team's Access certificates, so tokens it signs pass
+ * `requireAccess`; the stranger key signs tokens Cloudflare never issued.
+ */
+export async function trustAccessKey(service: TestService) {
+ const current = await generateKeyPair('RS256')
+ const strangerKey = (await generateKeyPair('RS256')).privateKey
+ const publicKey = { ...(await exportJWK(current.publicKey)), kid: 'current', alg: 'RS256' }
+ service.respond(`${ACCESS_TEAM}/cdn-cgi/access/certs`, () => Response.json({ keys: [publicKey] }))
+ return { signingKey: current.privateKey, strangerKey }
+}
+
+/** An Access token as Cloudflare would issue it, signed with `key`; `expiresIn` null leaves `exp` out. */
+export function signAccessToken(
+ key: CryptoKey,
+ now: Date,
+ claims: { aud?: string; iss?: string; expiresIn?: number | null } = {}
+) {
+ const seconds = Math.floor(now.getTime() / 1000)
+ const token = new SignJWT({ email: '[email protected]' })
+ .setProtectedHeader({ alg: 'RS256', kid: 'current' })
+ .setIssuer(claims.iss ?? ACCESS_TEAM)
+ .setAudience(claims.aud ?? ACCESS_AUDIENCE)
+ .setIssuedAt(seconds - 7200)
+ const expiresIn = claims.expiresIn === undefined ? 3600 : claims.expiresIn
+ return (expiresIn === null ? token : token.setExpirationTime(seconds + expiresIn)).sign(key)
+}
diff --git a/packages/feedback/tests/admin.test.ts b/packages/feedback/tests/admin.test.ts
index 99ee63b61..c54d2e59c 100644
--- a/packages/feedback/tests/admin.test.ts
+++ b/packages/feedback/tests/admin.test.ts
@@ -1,17 +1,16 @@
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test'
+import { signAccessToken, trustAccessKey } from '#feedback-tests/access'
import { createTestService, type TestService } from '#feedback-tests/harness'
import { metricsSnapshotSchema, type MetricsSnapshot } from '#feedback/contract'
import { createFeedbackDatabase } from '#feedback/db'
-import { exportJWK, generateKeyPair, SignJWT, type CryptoKey } from 'jose'
+import type { CryptoKey } from 'jose'
import * as v from 'valibot'
let service: TestService
let signingKey: CryptoKey
let strangerKey: CryptoKey
-const TEAM = 'https://openpencil.cloudflareaccess.com'
-const AUDIENCE = 'admin-audience'
const POSTHOG_QUERY = 'https://eu.posthog.com/api/projects/267806/query/'
const NOW = new Date('2026-10-20T12:00:00.000Z')
const TABLES = [
@@ -28,20 +27,8 @@ const TABLES = [
'repoItems'
] as const
-/** An Access token as Cloudflare would issue it, signed with `key`; `expiresIn` null leaves `exp` out. */
-function accessToken(
- key: CryptoKey,
- claims: { aud?: string; iss?: string; expiresIn?: number | null } = {}
-) {
- const seconds = Math.floor(NOW.getTime() / 1000)
- const token = new SignJWT({ email: '[email protected]' })
- .setProtectedHeader({ alg: 'RS256', kid: 'current' })
- .setIssuer(claims.iss ?? TEAM)
- .setAudience(claims.aud ?? AUDIENCE)
- .setIssuedAt(seconds - 7200)
- const expiresIn = claims.expiresIn === undefined ? 3600 : claims.expiresIn
- return (expiresIn === null ? token : token.setExpirationTime(seconds + expiresIn)).sign(key)
-}
+const accessToken = (key: CryptoKey, claims?: Parameters<typeof signAccessToken>[2]) =>
+ signAccessToken(key, NOW, claims)
async function getSnapshot(query: string, token?: string) {
return service.request(`/admin/api/snapshot?${query}`, {
@@ -112,11 +99,9 @@ function answerPostHog() {
beforeAll(async () => {
service = await createTestService()
- const current = await generateKeyPair('RS256')
- signingKey = current.privateKey
- strangerKey = (await generateKeyPair('RS256')).privateKey
- const publicKey = { ...(await exportJWK(current.publicKey)), kid: 'current', alg: 'RS256' }
- service.respond(`${TEAM}/cdn-cgi/access/certs`, () => Response.json({ keys: [publicKey] }))
+ const keys = await trustAccessKey(service)
+ signingKey = keys.signingKey
+ strangerKey = keys.strangerKey
})
beforeEach(async () => {
diff --git a/packages/feedback/tests/contract.test.ts b/packages/feedback/tests/contract.test.ts
index 3c0c8c947..ee42454c8 100644
--- a/packages/feedback/tests/contract.test.ts
+++ b/packages/feedback/tests/contract.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, test } from 'bun:test'
-import { describeBuildFields, describePingFields, describeUsageEvents } from '#feedback/contract'
+import {
+ describeBuildFields,
+ describePingFields,
+ describeReportFields,
+ describeUsageEvents,
+ reportSchema
+} from '#feedback/contract'
describe('contract descriptions', () => {
test('describe every usage event and property, with the values each can take', () => {
@@ -46,4 +52,18 @@ describe('contract descriptions', () => {
'browser'
])
})
+
+ test('describe every report field besides the build', () => {
+ const build = new Set(describeBuildFields().map(({ name }) => name))
+ const fields = new Set(
+ reportSchema.options
+ .flatMap((option) => Object.keys(option.entries))
+ .filter((name) => !build.has(name))
+ )
+ const described = describeReportFields()
+
+ expect(new Set(described.map(({ name }) => name))).toEqual(fields)
+ expect(described.every(({ description }) => description !== '')).toBe(true)
+ expect(described.find(({ name }) => name === 'kind')?.values).toEqual(['error', 'problem'])
+ })
})
diff --git a/packages/feedback/tests/harness.ts b/packages/feedback/tests/harness.ts
index 3e15a07d6..ef68491f4 100644
--- a/packages/feedback/tests/harness.ts
+++ b/packages/feedback/tests/harness.ts
@@ -53,10 +53,26 @@ export async function createTestService() {
const responses = new Map<string, (call: FetchCall) => Response>()
const sentEmails: EmailMessageBuilder[] = []
let now = new Date('2026-10-12T09:00:00.000Z')
- const limiters = { ping: testLimiter(), ingest: testLimiter(), waitlist: testLimiter() }
+ const limiters = {
+ ping: testLimiter(),
+ ingest: testLimiter(),
+ waitlist: testLimiter(),
+ report: testLimiter()
+ }
+ const bucket = proxy.env.REPORTS
const env: Env = {
...proxy.env,
+ // Workers stream a request body of declared length straight into R2; under Bun the body is a
+ // plain stream, which Miniflare's proxy refuses, so it is read first.
+ REPORTS: Object.assign(Object.create(bucket) as R2Bucket, {
+ put: async (...[key, value, options]: Parameters<R2Bucket['put']>) =>
+ bucket.put(
+ key,
+ value instanceof ReadableStream ? await new Response(value).arrayBuffer() : value,
+ options
+ )
+ }),
POSTHOG_HOST: 'https://eu.i.posthog.com',
POSTHOG_KEY: 'phc_test',
TURNSTILE_SECRET: 'turnstile-secret',
@@ -84,6 +100,8 @@ export async function createTestService() {
PING_LIMITER: limiters.ping,
INGEST_LIMITER: limiters.ingest,
WAITLIST_LIMITER: limiters.waitlist,
+ REPORT_LIMITER: limiters.report,
+ REPORT_UPLOAD_SECRET: 'report-upload-secret',
EMAIL: {
async send(message: EmailMessageBuilder | EmailMessage) {
if (!('subject' in message)) throw new Error('Tests send composed emails only')
diff --git a/packages/feedback/tests/reports.test.ts b/packages/feedback/tests/reports.test.ts
new file mode 100644
index 000000000..5df0a54e7
--- /dev/null
+++ b/packages/feedback/tests/reports.test.ts
@@ -0,0 +1,322 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test'
+
+import { signAccessToken, trustAccessKey } from '#feedback-tests/access'
+import { createTestService, type TestService } from '#feedback-tests/harness'
+import { reportReceiptSchema, type Report } from '#feedback/contract'
+import { deleteExpiredReportFiles, reportFileKey } from '#feedback/reports/files'
+import { runRetention } from '#feedback/retention'
+import type { CryptoKey } from 'jose'
+import * as v from 'valibot'
+
+let service: TestService
+let signingKey: CryptoKey
+
+const NOW = new Date('2026-11-03T10:00:00.000Z')
+const RELEASE = '01a19e69-fdef-0000-e554-4733f3a5a77c'
+const CHUNK = '849ab7be-6ab8-5c38-8851-ee4992cad3e5'
+
+const BUILD = {
+ version: '0.17.0',
+ platform: 'macos',
+ arch: 'arm64',
+ app: 'desktop',
+ browser: 'unknown'
+} as const
+
+const ERROR_REPORT: Report = {
+ kind: 'error',
+ ...BUILD,
+ release: RELEASE,
+ exceptions: [
+ {
+ type: 'TypeError',
+ value: 'nodes.map is not a function',
+ mechanism: { handled: false, synthetic: false, type: 'window' },
+ stacktrace: {
+ type: 'raw',
+ frames: [
+ {
+ platform: 'web:javascript',
+ filename: 'tauri://localhost/assets/index-a1b2c3d4.js',
+ function: 'Le',
+ lineno: 1,
+ colno: 52114,
+ in_app: true,
+ chunk_id: CHUNK
+ }
+ ]
+ }
+ }
+ ],
+ steps: [
+ {
+ name: 'document.operation.failed',
+ category: 'document',
+ level: 'error',
+ timestamp: '2026-11-03T09:59:58.000Z',
+ attributes: { operation: 'open', format: 'fig', durationMs: 120 }
+ }
+ ]
+}
+
+const PROBLEM_REPORT: Report = {
+ kind: 'problem',
+ ...BUILD,
+ note: 'Text jumps when I resize the frame.',
+ email: '[email protected]',
+ files: [{ name: 'document.fig', size: 5 }]
+}
+
+const postHogBodySchema = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({
+ api_key: v.string(),
+ batch: v.tuple([
+ v.object({
+ event: v.string(),
+ timestamp: v.string(),
+ distinct_id: v.string(),
+ properties: v.record(v.string(), v.unknown())
+ })
+ ])
+ })
+)
+
+/** The event the last report sent to PostHog. */
+function sentEvent() {
+ const call = service.fetchCalls.at(-1)
+ expect(call?.url).toBe('https://eu.i.posthog.com/batch/')
+ return v.parse(postHogBodySchema, call?.init?.body).batch[0]
+}
+
+async function submit(report: unknown) {
+ const response = await service.postJSON('/reports', report, { 'CF-Connecting-IP': '203.0.113.7' })
+ const receipt =
+ response.status === 201 ? v.parse(reportReceiptSchema, await response.json()) : null
+ return { status: response.status, receipt }
+}
+
+function upload(reportId: string, name: string, body: string, token: string | null) {
+ return service.request(`/reports/${reportId}/files/${name}`, {
+ method: 'PUT',
+ headers: token ? { Authorization: `Bearer ${token}` } : {},
+ body
+ })
+}
+
+beforeAll(async () => {
+ service = await createTestService()
+ signingKey = (await trustAccessKey(service)).signingKey
+})
+
+beforeEach(() => {
+ service.fetchCalls.length = 0
+ service.limiters.report.exhausted = false
+ service.setNow(NOW)
+})
+
+afterAll(async () => {
+ await service.dispose()
+})
+
+describe('error reports', () => {
+ test('go to PostHog error tracking as one exception, without a person or an address', async () => {
+ const { status, receipt } = await submit(ERROR_REPORT)
+
+ expect(status).toBe(201)
+ if (!receipt) throw new Error('The report was not accepted')
+ expect(receipt.uploadToken).toBeNull()
+ const event = sentEvent()
+ expect(event.event).toBe('$exception')
+ expect(event.timestamp).toBe(NOW.toISOString())
+ // No install ID was sent, so the report is its own PostHog person.
+ expect(event.distinct_id).toBe(receipt.reportId)
+ expect(event.properties).toEqual({
+ ...BUILD,
+ report_id: receipt.reportId,
+ report_note: null,
+ report_email: null,
+ report_files: [],
+ $release_id: RELEASE,
+ $exception_list: ERROR_REPORT.kind === 'error' ? ERROR_REPORT.exceptions : [],
+ $exception_level: 'error',
+ $exception_steps: [
+ {
+ $message: 'document.operation.failed',
+ $timestamp: '2026-11-03T09:59:58.000Z',
+ category: 'document',
+ level: 'error',
+ attribute_operation: 'open',
+ attribute_format: 'fig',
+ attribute_durationMs: 120
+ }
+ ],
+ $lib: 'openpencil',
+ $process_person_profile: false,
+ $geoip_disable: true
+ })
+ expect(JSON.stringify(event)).not.toContain('203.0.113.7')
+ })
+
+ test('join the install’s usage events when it shares usage stats', async () => {
+ const installId = '0123456789abcdef0123456789abcdef'
+ await submit({ ...ERROR_REPORT, installId })
+ expect(sentEvent().distinct_id).toBe(installId)
+ })
+
+ test.each([
+ ['no exception', { ...ERROR_REPORT, exceptions: [] }],
+ ['an unknown field', { ...ERROR_REPORT, fileName: 'Client roadmap.fig' }],
+ [
+ 'a frame from another platform',
+ {
+ ...ERROR_REPORT,
+ exceptions: [
+ {
+ type: 'Error',
+ mechanism: { handled: false, synthetic: false, type: 'window' },
+ stacktrace: { type: 'raw', frames: [{ platform: 'python' }] }
+ }
+ ]
+ }
+ ],
+ ['a file under its own name', { ...ERROR_REPORT, files: [{ name: 'Roadmap.fig', size: 5 }] }],
+ [
+ 'a file the app never sends',
+ { ...ERROR_REPORT, files: [{ name: 'customer-data.txt', size: 5 }] }
+ ]
+ ])('refuse a report with %s', async (_scenario, report) => {
+ expect((await submit(report)).status).toBe(400)
+ expect(service.fetchCalls).toHaveLength(0)
+ })
+
+ test('report a PostHog failure and hand out no upload token', async () => {
+ service.respond('https://eu.i.posthog.com', () => new Response(null, { status: 503 }))
+ try {
+ const { status, receipt } = await submit(PROBLEM_REPORT)
+ expect(status).toBe(502)
+ expect(receipt).toBeNull()
+ } finally {
+ service.respond('https://eu.i.posthog.com', () => new Response(null, { status: 200 }))
+ }
+ })
+
+ test('take a body larger than the other routes allow', async () => {
+ const note = 'x'.repeat(4000)
+ const steps = Array.from({ length: 50 }, (_, index) => ({
+ name: 'runtime.error',
+ category: 'runtime',
+ level: 'error',
+ timestamp: '2026-11-03T09:59:58.000Z',
+ attributes: { stack: `frame ${index}\n`.repeat(20) }
+ }))
+ const report = { ...ERROR_REPORT, note, steps }
+ expect(JSON.stringify(report).length).toBeGreaterThan(16 * 1024)
+ expect((await submit(report)).status).toBe(201)
+ })
+
+ test('count against the report rate limit', async () => {
+ service.limiters.report.exhausted = true
+ expect((await submit(ERROR_REPORT)).status).toBe(429)
+ })
+})
+
+describe('problem reports', () => {
+ test('go to PostHog with the note, the email, and links to their files', async () => {
+ const { receipt } = await submit(PROBLEM_REPORT)
+
+ const event = sentEvent()
+ expect(event.event).toBe('problem_reported')
+ expect(event.properties.report_note).toBe(PROBLEM_REPORT.note)
+ expect(event.properties.report_email).toBe('[email protected]')
+ expect(event.properties.report_files).toEqual([
+ `https://feedback.openpencil.dev/admin/reports/${receipt?.reportId}/files/document.fig`
+ ])
+ expect(event.properties).not.toHaveProperty('$exception_list')
+ })
+
+ test('need a note', async () => {
+ expect((await submit({ ...PROBLEM_REPORT, note: ' ' })).status).toBe(400)
+ })
+})
+
+describe('report files', () => {
+ async function submitted() {
+ const { receipt } = await submit(PROBLEM_REPORT)
+ if (!receipt?.uploadToken) throw new Error('The report answered without an upload token')
+ return { reportId: receipt.reportId, token: receipt.uploadToken }
+ }
+
+ test('upload once with the report’s token and download only through Access', async () => {
+ const { reportId, token } = await submitted()
+
+ expect((await upload(reportId, 'document.fig', 'bytes', token)).status).toBe(204)
+
+ const path = `/admin/reports/${reportId}/files/document.fig`
+ expect((await service.request(path)).status).toBe(403)
+ const download = await service.request(path, {
+ headers: { 'cf-access-jwt-assertion': await signAccessToken(signingKey, NOW) }
+ })
+ expect(download.status).toBe(200)
+ expect(download.headers.get('content-disposition')).toBe(
+ `attachment; filename="${reportId}-document.fig"`
+ )
+ expect(download.headers.get('cache-control')).toBe('private, no-store')
+ expect(await download.text()).toBe('bytes')
+ })
+
+ test('refuse a file the service does not take, at another size, or for another report', async () => {
+ const { reportId, token } = await submitted()
+ const other = await submitted()
+
+ expect((await upload(reportId, 'screenshot.png', 'bytes', token)).status).toBe(403)
+ expect((await upload(reportId, 'document.fig', 'more bytes', token)).status).toBe(400)
+ expect((await upload(other.reportId, 'document.fig', 'bytes', token)).status).toBe(403)
+ expect((await upload(reportId, 'document.fig', 'bytes', null)).status).toBe(403)
+ expect(await service.env.REPORTS.head(reportFileKey(reportId, 'document.fig'))).toBeNull()
+ })
+
+ test('refuse an upload token after its hour', async () => {
+ const { reportId, token } = await submitted()
+ service.setNow(new Date(NOW.getTime() + 61 * 60 * 1000))
+ expect((await upload(reportId, 'document.fig', 'bytes', token)).status).toBe(403)
+ })
+
+ test('are deleted by retention after 90 days', async () => {
+ const { reportId, token } = await submitted()
+ await upload(reportId, 'document.fig', 'bytes', token)
+ const key = reportFileKey(reportId, 'document.fig')
+ const day = 24 * 60 * 60 * 1000
+
+ await deleteExpiredReportFiles(service.env.REPORTS, new Date(Date.now() + 89 * day))
+ expect(await service.env.REPORTS.head(key)).not.toBeNull()
+ await deleteExpiredReportFiles(service.env.REPORTS, new Date(Date.now() + 91 * day))
+ expect(await service.env.REPORTS.head(key)).toBeNull()
+ })
+
+ test('are deleted by retention even when the sign-up cleanup fails', async () => {
+ const { reportId, token } = await submitted()
+ await upload(reportId, 'document.fig', 'bytes', token)
+ const key = reportFileKey(reportId, 'document.fig')
+ const failingDatabase = new Proxy(service.env.DB, {
+ get: (database, key) =>
+ key === 'prepare'
+ ? () => {
+ throw new Error('D1 is unavailable')
+ }
+ : Reflect.get(database, key)
+ })
+ const env = { ...service.env, DB: failingDatabase }
+
+ await expect(
+ runRetention(env, new Date(Date.now() + 91 * 24 * 60 * 60 * 1000))
+ ).rejects.toThrow('D1 is unavailable')
+ expect(await service.env.REPORTS.head(key)).toBeNull()
+ })
+})
+
+test('other routes keep the small body limit', async () => {
+ const response = await service.postJSON('/ping', { padding: 'x'.repeat(20 * 1024) })
+ expect(response.status).toBe(413)
+})
diff --git a/packages/feedback/worker-configuration.d.ts b/packages/feedback/worker-configuration.d.ts
index dfe33e107..f0296253b 100644
--- a/packages/feedback/worker-configuration.d.ts
+++ b/packages/feedback/worker-configuration.d.ts
@@ -1,11 +1,13 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 3a4cf01ae118ee1043bbb3047f489806)
+// Generated by Wrangler by running `wrangler types --include-runtime=false` (hash: 41376319c564e9bcff52ca4bedd44624)
interface __BaseEnv_Env {
+ REPORTS: R2Bucket;
DB: D1Database;
EMAIL: SendEmail;
PING_LIMITER: RateLimit;
INGEST_LIMITER: RateLimit;
WAITLIST_LIMITER: RateLimit;
+ REPORT_LIMITER: RateLimit;
ASSETS: Fetcher;
POSTHOG_HOST: "https://eu.i.posthog.com";
EMAIL_FROM: "[email protected]";
@@ -22,6 +24,7 @@ interface __BaseEnv_Env {
POSTHOG_PERSONAL_KEY: string;
ACCESS_TEAM_DOMAIN: string;
ACCESS_AUD: string;
+ REPORT_UPLOAD_SECRET: string;
}
declare namespace Cloudflare {
interface GlobalProps {
@@ -34,7 +37,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "POSTHOG_HOST" | "EMAIL_FROM" | "TURNSTILE_HOSTNAMES" | "GITHUB_REPOSITORY" | "SITE_ZONE_ID" | "SITE_HOSTS" | "POSTHOG_APP_HOST" | "POSTHOG_PROJECT_ID" | "POSTHOG_KEY" | "TURNSTILE_SECRET" | "GITHUB_TOKEN" | "CLOUDFLARE_ANALYTICS_TOKEN" | "POSTHOG_PERSONAL_KEY" | "ACCESS_TEAM_DOMAIN" | "ACCESS_AUD">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "POSTHOG_HOST" | "EMAIL_FROM" | "TURNSTILE_HOSTNAMES" | "GITHUB_REPOSITORY" | "SITE_ZONE_ID" | "SITE_HOSTS" | "POSTHOG_APP_HOST" | "POSTHOG_PROJECT_ID" | "POSTHOG_KEY" | "TURNSTILE_SECRET" | "GITHUB_TOKEN" | "CLOUDFLARE_ANALYTICS_TOKEN" | "POSTHOG_PERSONAL_KEY" | "ACCESS_TEAM_DOMAIN" | "ACCESS_AUD" | "REPORT_UPLOAD_SECRET">> {}
}
declare module "*.txt" {
const value: string;
diff --git a/packages/feedback/wrangler.jsonc b/packages/feedback/wrangler.jsonc
index 5cdf189fa..7efa2c262 100644
--- a/packages/feedback/wrangler.jsonc
+++ b/packages/feedback/wrangler.jsonc
@@ -33,7 +33,13 @@
"ratelimits": [
{ "name": "PING_LIMITER", "namespace_id": "1001", "simple": { "limit": 10, "period": 60 } },
{ "name": "INGEST_LIMITER", "namespace_id": "1002", "simple": { "limit": 60, "period": 60 } },
- { "name": "WAITLIST_LIMITER", "namespace_id": "1003", "simple": { "limit": 5, "period": 60 } }
+ { "name": "WAITLIST_LIMITER", "namespace_id": "1003", "simple": { "limit": 5, "period": 60 } },
+ { "name": "REPORT_LIMITER", "namespace_id": "1004", "simple": { "limit": 10, "period": 60 } }
+ ],
+ // Files attached to error and problem reports. Created with
+ // `wrangler r2 bucket create openpencil-reports --jurisdiction eu`, so they stay in the EU.
+ "r2_buckets": [
+ { "binding": "REPORTS", "bucket_name": "openpencil-reports", "jurisdiction": "eu" }
],
"send_email": [{ "name": "EMAIL" }],
// The metrics dashboard, built by `vite build --mode metrics` at the repository root. Its page
@@ -57,7 +63,9 @@
"POSTHOG_PERSONAL_KEY",
// Not secret, but set per deployment once the Access application in front of /admin exists.
"ACCESS_TEAM_DOMAIN",
- "ACCESS_AUD"
+ "ACCESS_AUD",
+ // Any long random string; rotating it only invalidates uploads in flight.
+ "REPORT_UPLOAD_SECRET"
]
}
}
diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.json
index b1949f225..202f31f1c 100644
--- a/packages/vue/src/i18n/locales/de/diagnostics.json
+++ b/packages/vue/src/i18n/locales/de/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Statistik teilen",
"sharingQuestionAccepted": "Danke. Du kannst das in den Datenschutz-Einstellungen ändern.",
"sharingQuestionDeclined": "Die Nutzungsstatistik bleibt aus. Du kannst das in den Datenschutz-Einstellungen ändern.",
- "sharingLocalData": "Nutzung und Diagnose speichern ihre Daten auf diesem Gerät und senden sie nie."
+ "sharingLocalData": "Nutzung und Diagnose speichern ihre Daten auf diesem Gerät. Diagnosedaten verlassen es nur in einem Bericht, den du selbst sendest.",
+ "reportError": "Melden…",
+ "reportErrorTitle": "Diesen Fehler melden",
+ "reportProblemTitle": "Problem melden",
+ "reportErrorDescription": "Sende diesen Fehler an das OpenPencil-Team, damit er behoben werden kann. Gesendet wird erst, wenn du „Bericht senden“ wählst.",
+ "reportProblemDescription": "Beschreibe dem OpenPencil-Team, was schiefgelaufen ist. Gesendet wird erst, wenn du „Bericht senden“ wählst.",
+ "reportNoteError": "Was hast du gerade gemacht? (optional)",
+ "reportNoteProblem": "Was ist passiert?",
+ "reportNotePlaceholder": "Was du getan hast, was passiert ist und was du stattdessen erwartet hast.",
+ "reportEmail": "E-Mail (optional)",
+ "reportEmailHint": "Nur, wenn wir uns bei dir melden sollen.",
+ "reportActivity": "Letzte Aktivität einbeziehen",
+ "reportActivityDescription": "Die letzten 50 Ereignisse aus der Diagnose, etwa Fehler und Zeiten. Nie Chatnachrichten oder Werkzeugausgaben.",
+ "reportDocument": "Dieses Dokument anhängen",
+ "reportDocumentDescription": "Lädt das ganze Design als .fig-Datei hoch. Nur das OpenPencil-Team kann es öffnen, und es wird nach 90 Tagen gelöscht.",
+ "reportPreview": "Was gesendet wird",
+ "reportSend": "Bericht senden",
+ "reportSent": "Bericht gesendet. Danke!",
+ "reportFailed": "Der Bericht konnte nicht gesendet werden. Prüfe deine Verbindung und versuche es erneut.",
+ "reportFilesFailed": "Der Bericht wurde gesendet, aber das Dokument konnte nicht hochgeladen werden.",
+ "reportDocumentFailed": "Das Dokument konnte nicht angehängt werden. Du kannst den Bericht ohne es senden.",
+ "reportUnexpectedError": "In OpenPencil ist etwas schiefgelaufen.",
+ "reportPanic": "OpenPencil hatte beim letzten Start einen internen Fehler.",
+ "reportCrashed": "OpenPencil wurde nach einem Fehler unerwartet beendet."
}
diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.json
index 76f0140d7..e50bd6e21 100644
--- a/packages/vue/src/i18n/locales/de/menu.json
+++ b/packages/vue/src/i18n/locales/de/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Vorschau",
"saveTo": "Speichern in…",
"showVersionHistory": "Versionsverlauf anzeigen",
- "saveToVersionHistory": "Im Versionsverlauf speichern…"
+ "saveToVersionHistory": "Im Versionsverlauf speichern…",
+ "reportProblem": "Problem melden…"
}
diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.json
index 3332b9711..a84cea97d 100644
--- a/packages/vue/src/i18n/locales/es/diagnostics.json
+++ b/packages/vue/src/i18n/locales/es/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Compartir estadísticas",
"sharingQuestionAccepted": "Gracias. Puedes cambiarlo en los ajustes de Privacidad.",
"sharingQuestionDeclined": "Las estadísticas de uso seguirán desactivadas. Puedes cambiarlo en los ajustes de Privacidad.",
- "sharingLocalData": "Uso y Diagnóstico guardan sus registros en este dispositivo y nunca los envían."
+ "sharingLocalData": "Uso y Diagnóstico guardan sus registros en este dispositivo. Los diagnósticos solo salen de él en un informe que tú decidas enviar.",
+ "reportError": "Informar…",
+ "reportErrorTitle": "Informar de este error",
+ "reportProblemTitle": "Informar de un problema",
+ "reportErrorDescription": "Envía este error al equipo de OpenPencil para que pueda corregirse. No se envía nada hasta que elijas Enviar informe.",
+ "reportProblemDescription": "Cuéntale al equipo de OpenPencil qué salió mal. No se envía nada hasta que elijas Enviar informe.",
+ "reportNoteError": "¿Qué estabas haciendo? (opcional)",
+ "reportNoteProblem": "¿Qué ha pasado?",
+ "reportNotePlaceholder": "Qué hiciste, qué pasó y qué esperabas en su lugar.",
+ "reportEmail": "Correo electrónico (opcional)",
+ "reportEmailHint": "Solo si quieres que te respondamos.",
+ "reportActivity": "Incluir la actividad reciente",
+ "reportActivityDescription": "Los últimos 50 eventos de Diagnóstico, como errores y tiempos. Nunca mensajes del chat ni resultados de herramientas.",
+ "reportDocument": "Adjuntar este documento",
+ "reportDocumentDescription": "Sube el diseño completo como archivo .fig. Solo el equipo de OpenPencil puede abrirlo, y se elimina a los 90 días.",
+ "reportPreview": "Qué se enviará",
+ "reportSend": "Enviar informe",
+ "reportSent": "Informe enviado. ¡Gracias!",
+ "reportFailed": "No se pudo enviar el informe. Comprueba tu conexión e inténtalo de nuevo.",
+ "reportFilesFailed": "El informe se envió, pero no se pudo subir el documento.",
+ "reportDocumentFailed": "No se pudo adjuntar el documento. Puedes enviar el informe sin él.",
+ "reportUnexpectedError": "Algo salió mal en OpenPencil.",
+ "reportPanic": "OpenPencil tuvo un error interno la última vez que se ejecutó.",
+ "reportCrashed": "OpenPencil se cerró inesperadamente tras un error."
}
diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.json
index a71420988..b64176828 100644
--- a/packages/vue/src/i18n/locales/es/menu.json
+++ b/packages/vue/src/i18n/locales/es/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Vista previa",
"saveTo": "Guardar en…",
"showVersionHistory": "Mostrar historial de versiones",
- "saveToVersionHistory": "Guardar en el historial de versiones…"
+ "saveToVersionHistory": "Guardar en el historial de versiones…",
+ "reportProblem": "Informar de un problema…"
}
diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.json
index 9f204a2f7..7202c6dee 100644
--- a/packages/vue/src/i18n/locales/fr/diagnostics.json
+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Partager les statistiques",
"sharingQuestionAccepted": "Merci. Vous pouvez modifier ce choix dans les réglages Confidentialité.",
"sharingQuestionDeclined": "Les statistiques d'utilisation restent désactivées. Vous pouvez modifier ce choix dans les réglages Confidentialité.",
- "sharingLocalData": "Utilisation et Diagnostics conservent leurs données sur cet appareil et ne les envoient jamais."
+ "sharingLocalData": "Utilisation et Diagnostics conservent leurs données sur cet appareil. Les diagnostics n’en sortent que dans un rapport que vous choisissez d’envoyer.",
+ "reportError": "Signaler…",
+ "reportErrorTitle": "Signaler cette erreur",
+ "reportProblemTitle": "Signaler un problème",
+ "reportErrorDescription": "Envoyez cette erreur à l’équipe OpenPencil pour qu’elle puisse être corrigée. Rien n’est envoyé avant que vous choisissiez Envoyer le rapport.",
+ "reportProblemDescription": "Décrivez à l’équipe OpenPencil ce qui n’a pas fonctionné. Rien n’est envoyé avant que vous choisissiez Envoyer le rapport.",
+ "reportNoteError": "Que faisiez-vous ? (facultatif)",
+ "reportNoteProblem": "Que s’est-il passé ?",
+ "reportNotePlaceholder": "Ce que vous avez fait, ce qui s’est passé et ce que vous attendiez à la place.",
+ "reportEmail": "E-mail (facultatif)",
+ "reportEmailHint": "Seulement si vous souhaitez que nous vous recontactions.",
+ "reportActivity": "Inclure l’activité récente",
+ "reportActivityDescription": "Les 50 derniers événements des Diagnostics, comme les erreurs et les durées. Jamais les messages du chat ni les sorties d’outils.",
+ "reportDocument": "Joindre ce document",
+ "reportDocumentDescription": "Envoie tout le design sous forme de fichier .fig. Seule l’équipe OpenPencil peut l’ouvrir, et il est supprimé au bout de 90 jours.",
+ "reportPreview": "Ce qui sera envoyé",
+ "reportSend": "Envoyer le rapport",
+ "reportSent": "Rapport envoyé. Merci !",
+ "reportFailed": "Impossible d’envoyer le rapport. Vérifiez votre connexion et réessayez.",
+ "reportFilesFailed": "Le rapport a été envoyé, mais le document n’a pas pu être téléversé.",
+ "reportDocumentFailed": "Impossible de joindre le document. Vous pouvez envoyer le rapport sans lui.",
+ "reportUnexpectedError": "Une erreur s’est produite dans OpenPencil.",
+ "reportPanic": "OpenPencil a rencontré une erreur interne lors de sa dernière exécution.",
+ "reportCrashed": "OpenPencil s’est fermé de façon inattendue après une erreur."
}
diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.json
index b7876b154..d840b8018 100644
--- a/packages/vue/src/i18n/locales/fr/menu.json
+++ b/packages/vue/src/i18n/locales/fr/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Aperçu",
"saveTo": "Enregistrer dans…",
"showVersionHistory": "Afficher l’historique des versions",
- "saveToVersionHistory": "Enregistrer dans l’historique des versions…"
+ "saveToVersionHistory": "Enregistrer dans l’historique des versions…",
+ "reportProblem": "Signaler un problème…"
}
diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.json
index fe10af687..aab7285b0 100644
--- a/packages/vue/src/i18n/locales/it/diagnostics.json
+++ b/packages/vue/src/i18n/locales/it/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Condividi statistiche",
"sharingQuestionAccepted": "Grazie. Puoi cambiare questa scelta nelle impostazioni Privacy.",
"sharingQuestionDeclined": "Le statistiche di utilizzo restano disattivate. Puoi cambiare questa scelta nelle impostazioni Privacy.",
- "sharingLocalData": "Utilizzo e Diagnostica conservano i dati su questo dispositivo e non li inviano mai."
+ "sharingLocalData": "Utilizzo e Diagnostica conservano i loro dati su questo dispositivo. I dati diagnostici lo lasciano solo in una segnalazione che scegli di inviare.",
+ "reportError": "Segnala…",
+ "reportErrorTitle": "Segnala questo errore",
+ "reportProblemTitle": "Segnala un problema",
+ "reportErrorDescription": "Invia questo errore al team di OpenPencil perché possa essere corretto. Non viene inviato nulla finché non scegli Invia segnalazione.",
+ "reportProblemDescription": "Racconta al team di OpenPencil cosa è andato storto. Non viene inviato nulla finché non scegli Invia segnalazione.",
+ "reportNoteError": "Cosa stavi facendo? (facoltativo)",
+ "reportNoteProblem": "Cosa è successo?",
+ "reportNotePlaceholder": "Cosa hai fatto, cosa è successo e cosa ti aspettavi invece.",
+ "reportEmail": "Email (facoltativa)",
+ "reportEmailHint": "Solo se vuoi che ti ricontattiamo.",
+ "reportActivity": "Includi l’attività recente",
+ "reportActivityDescription": "Gli ultimi 50 eventi della Diagnostica, come errori e tempi. Mai messaggi della chat o output degli strumenti.",
+ "reportDocument": "Allega questo documento",
+ "reportDocumentDescription": "Carica l’intero design come file .fig. Solo il team di OpenPencil può aprirlo e viene eliminato dopo 90 giorni.",
+ "reportPreview": "Cosa verrà inviato",
+ "reportSend": "Invia segnalazione",
+ "reportSent": "Segnalazione inviata. Grazie!",
+ "reportFailed": "Impossibile inviare la segnalazione. Controlla la connessione e riprova.",
+ "reportFilesFailed": "La segnalazione è stata inviata, ma non è stato possibile caricare il documento.",
+ "reportDocumentFailed": "Impossibile allegare il documento. Puoi inviare la segnalazione senza.",
+ "reportUnexpectedError": "Qualcosa è andato storto in OpenPencil.",
+ "reportPanic": "OpenPencil ha avuto un errore interno l’ultima volta che è stato eseguito.",
+ "reportCrashed": "OpenPencil si è chiuso inaspettatamente dopo un errore."
}
diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.json
index 9b4e221f0..8f7e2e990 100644
--- a/packages/vue/src/i18n/locales/it/menu.json
+++ b/packages/vue/src/i18n/locales/it/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Anteprima",
"saveTo": "Salva in…",
"showVersionHistory": "Mostra cronologia versioni",
- "saveToVersionHistory": "Salva nella cronologia versioni…"
+ "saveToVersionHistory": "Salva nella cronologia versioni…",
+ "reportProblem": "Segnala un problema…"
}
diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.json
index ac3182a72..4a7c81963 100644
--- a/packages/vue/src/i18n/locales/ja/diagnostics.json
+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "統計を共有",
"sharingQuestionAccepted": "ありがとうございます。プライバシーの設定でいつでも変更できます。",
"sharingQuestionDeclined": "利用統計はオフのままです。プライバシーの設定でいつでも変更できます。",
- "sharingLocalData": "「使用状況」と「診断」の記録はこの端末に保存され、送信されることはありません。"
+ "sharingLocalData": "使用状況と診断の記録はこのデバイスに保存されます。診断が外部に送られるのは、あなたが送信を選んだレポートの中だけです。",
+ "reportError": "報告…",
+ "reportErrorTitle": "このエラーを報告",
+ "reportProblemTitle": "問題を報告",
+ "reportErrorDescription": "修正のため、このエラーを OpenPencil チームに送信します。「レポートを送信」を選ぶまで何も送信されません。",
+ "reportProblemDescription": "何が起きたかを OpenPencil チームに伝えてください。「レポートを送信」を選ぶまで何も送信されません。",
+ "reportNoteError": "何をしていましたか?(任意)",
+ "reportNoteProblem": "何が起きましたか?",
+ "reportNotePlaceholder": "行った操作、起きたこと、本来期待していた動作。",
+ "reportEmail": "メールアドレス(任意)",
+ "reportEmailHint": "返信を希望する場合のみ。",
+ "reportActivity": "最近のアクティビティを含める",
+ "reportActivityDescription": "診断の直近 50 件のイベント(エラーや所要時間など)。チャットのメッセージやツールの出力は含まれません。",
+ "reportDocument": "このドキュメントを添付",
+ "reportDocumentDescription": "デザイン全体を .fig ファイルとしてアップロードします。開けるのは OpenPencil チームだけで、90 日後に削除されます。",
+ "reportPreview": "送信される内容",
+ "reportSend": "レポートを送信",
+ "reportSent": "レポートを送信しました。ありがとうございます。",
+ "reportFailed": "レポートを送信できませんでした。接続を確認して、もう一度お試しください。",
+ "reportFilesFailed": "レポートは送信されましたが、ドキュメントをアップロードできませんでした。",
+ "reportDocumentFailed": "ドキュメントを添付できませんでした。添付せずにレポートを送信できます。",
+ "reportUnexpectedError": "OpenPencil で問題が発生しました。",
+ "reportPanic": "前回の実行中に OpenPencil で内部エラーが発生しました。",
+ "reportCrashed": "OpenPencil はエラーの後、予期せず終了しました。"
}
diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.json
index 066edcaa0..60438b135 100644
--- a/packages/vue/src/i18n/locales/ja/menu.json
+++ b/packages/vue/src/i18n/locales/ja/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "プレビュー",
"saveTo": "保存先を選んで保存…",
"showVersionHistory": "バージョン履歴を表示",
- "saveToVersionHistory": "バージョン履歴に保存…"
+ "saveToVersionHistory": "バージョン履歴に保存…",
+ "reportProblem": "問題を報告…"
}
diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.json
index e9ee9b366..98128a89e 100644
--- a/packages/vue/src/i18n/locales/pl/diagnostics.json
+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Udostępniaj statystyki",
"sharingQuestionAccepted": "Dziękujemy. Możesz to zmienić w ustawieniach prywatności.",
"sharingQuestionDeclined": "Statystyki użycia pozostaną wyłączone. Możesz to zmienić w ustawieniach prywatności.",
- "sharingLocalData": "Użycie i Diagnostyka przechowują dane na tym urządzeniu i nigdy ich nie wysyłają."
+ "sharingLocalData": "Użycie i Diagnostyka przechowują swoje dane na tym urządzeniu. Dane diagnostyczne opuszczają je tylko w zgłoszeniu, które sam zdecydujesz się wysłać.",
+ "reportError": "Zgłoś…",
+ "reportErrorTitle": "Zgłoś ten błąd",
+ "reportProblemTitle": "Zgłoś problem",
+ "reportErrorDescription": "Wyślij ten błąd do zespołu OpenPencil, aby można go było naprawić. Nic nie zostanie wysłane, dopóki nie wybierzesz Wyślij zgłoszenie.",
+ "reportProblemDescription": "Opisz zespołowi OpenPencil, co poszło nie tak. Nic nie zostanie wysłane, dopóki nie wybierzesz Wyślij zgłoszenie.",
+ "reportNoteError": "Co robiłeś? (opcjonalnie)",
+ "reportNoteProblem": "Co się stało?",
+ "reportNotePlaceholder": "Co zrobiłeś, co się stało i czego oczekiwałeś zamiast tego.",
+ "reportEmail": "E-mail (opcjonalnie)",
+ "reportEmailHint": "Tylko jeśli chcesz, żebyśmy się odezwali.",
+ "reportActivity": "Dołącz ostatnią aktywność",
+ "reportActivityDescription": "Ostatnie 50 zdarzeń z Diagnostyki, takich jak błędy i czasy. Nigdy wiadomości z czatu ani wyniki narzędzi.",
+ "reportDocument": "Dołącz ten dokument",
+ "reportDocumentDescription": "Przesyła cały projekt jako plik .fig. Otworzyć go może tylko zespół OpenPencil, a po 90 dniach jest usuwany.",
+ "reportPreview": "Co zostanie wysłane",
+ "reportSend": "Wyślij zgłoszenie",
+ "reportSent": "Zgłoszenie wysłane. Dziękujemy!",
+ "reportFailed": "Nie udało się wysłać zgłoszenia. Sprawdź połączenie i spróbuj ponownie.",
+ "reportFilesFailed": "Zgłoszenie zostało wysłane, ale nie udało się przesłać dokumentu.",
+ "reportDocumentFailed": "Nie udało się dołączyć dokumentu. Możesz wysłać zgłoszenie bez niego.",
+ "reportUnexpectedError": "W OpenPencil coś poszło nie tak.",
+ "reportPanic": "Podczas ostatniego uruchomienia w OpenPencil wystąpił błąd wewnętrzny.",
+ "reportCrashed": "OpenPencil nieoczekiwanie zamknął się po błędzie."
}
diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.json
index a39366d61..a7f251da4 100644
--- a/packages/vue/src/i18n/locales/pl/menu.json
+++ b/packages/vue/src/i18n/locales/pl/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Podgląd",
"saveTo": "Zapisz w…",
"showVersionHistory": "Pokaż historię wersji",
- "saveToVersionHistory": "Zapisz w historii wersji…"
+ "saveToVersionHistory": "Zapisz w historii wersji…",
+ "reportProblem": "Zgłoś problem…"
}
diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.json
index c01f3e705..81a1c25f3 100644
--- a/packages/vue/src/i18n/locales/ru/diagnostics.json
+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "Делиться статистикой",
"sharingQuestionAccepted": "Спасибо. Это можно изменить в настройках конфиденциальности.",
"sharingQuestionDeclined": "Статистика использования останется выключенной. Это можно изменить в настройках конфиденциальности.",
- "sharingLocalData": "Разделы «Использование» и «Диагностика» хранят данные на этом устройстве и никогда их не отправляют."
+ "sharingLocalData": "Использование и Диагностика хранят записи на этом устройстве. Данные диагностики покидают его только в отчёте, который вы сами решите отправить.",
+ "reportError": "Сообщить…",
+ "reportErrorTitle": "Сообщить об этой ошибке",
+ "reportProblemTitle": "Сообщить о проблеме",
+ "reportErrorDescription": "Отправьте эту ошибку команде OpenPencil, чтобы её исправили. Ничего не отправится, пока вы не нажмёте «Отправить отчёт».",
+ "reportProblemDescription": "Расскажите команде OpenPencil, что пошло не так. Ничего не отправится, пока вы не нажмёте «Отправить отчёт».",
+ "reportNoteError": "Что вы делали? (необязательно)",
+ "reportNoteProblem": "Что случилось?",
+ "reportNotePlaceholder": "Что вы сделали, что произошло и чего вы ожидали.",
+ "reportEmail": "Эл. почта (необязательно)",
+ "reportEmailHint": "Только если хотите, чтобы мы ответили.",
+ "reportActivity": "Приложить недавнюю активность",
+ "reportActivityDescription": "Последние 50 событий из Диагностики, например ошибки и время выполнения. Никогда не сообщения чата и не вывод инструментов.",
+ "reportDocument": "Приложить этот документ",
+ "reportDocumentDescription": "Загружает весь дизайн как файл .fig. Открыть его может только команда OpenPencil, и через 90 дней он удаляется.",
+ "reportPreview": "Что будет отправлено",
+ "reportSend": "Отправить отчёт",
+ "reportSent": "Отчёт отправлен. Спасибо!",
+ "reportFailed": "Не удалось отправить отчёт. Проверьте подключение и попробуйте ещё раз.",
+ "reportFilesFailed": "Отчёт отправлен, но документ загрузить не удалось.",
+ "reportDocumentFailed": "Не удалось приложить документ. Отчёт можно отправить без него.",
+ "reportUnexpectedError": "В OpenPencil что-то пошло не так.",
+ "reportPanic": "При прошлом запуске в OpenPencil произошла внутренняя ошибка.",
+ "reportCrashed": "OpenPencil неожиданно закрылся после ошибки."
}
diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.json
index 2c17c102d..eea03fa08 100644
--- a/packages/vue/src/i18n/locales/ru/menu.json
+++ b/packages/vue/src/i18n/locales/ru/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "Просмотр",
"saveTo": "Сохранить в…",
"showVersionHistory": "Показать историю версий",
- "saveToVersionHistory": "Сохранить в историю версий…"
+ "saveToVersionHistory": "Сохранить в историю версий…",
+ "reportProblem": "Сообщить о проблеме…"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
index e999fc156..f111b2486 100644
--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
@@ -84,5 +84,28 @@
"sharingQuestionAccept": "共享统计",
"sharingQuestionAccepted": "谢谢。你可以在隐私设置中更改此选项。",
"sharingQuestionDeclined": "使用统计将保持关闭。你可以在隐私设置中更改此选项。",
- "sharingLocalData": "“使用情况”和“诊断”的记录保存在此设备上,从不发送。"
+ "sharingLocalData": "使用情况和诊断的记录保存在此设备上。诊断数据只会随你选择发送的报告离开此设备。",
+ "reportError": "报告…",
+ "reportErrorTitle": "报告此错误",
+ "reportProblemTitle": "报告问题",
+ "reportErrorDescription": "将此错误发送给 OpenPencil 团队以便修复。在你选择“发送报告”之前不会发送任何内容。",
+ "reportProblemDescription": "告诉 OpenPencil 团队出了什么问题。在你选择“发送报告”之前不会发送任何内容。",
+ "reportNoteError": "你当时在做什么?(可选)",
+ "reportNoteProblem": "发生了什么?",
+ "reportNotePlaceholder": "你做了什么、发生了什么,以及你原本期望的结果。",
+ "reportEmail": "电子邮件(可选)",
+ "reportEmailHint": "仅在你希望我们回复时填写。",
+ "reportActivity": "包含最近的活动",
+ "reportActivityDescription": "来自诊断的最近 50 个事件,例如错误和耗时。绝不包括聊天消息或工具输出。",
+ "reportDocument": "附加此文档",
+ "reportDocumentDescription": "将整个设计作为 .fig 文件上传。只有 OpenPencil 团队可以打开它,90 天后删除。",
+ "reportPreview": "将要发送的内容",
+ "reportSend": "发送报告",
+ "reportSent": "报告已发送。谢谢!",
+ "reportFailed": "无法发送报告。请检查网络连接后重试。",
+ "reportFilesFailed": "报告已发送,但文档未能上传。",
+ "reportDocumentFailed": "无法附加文档。你可以不附带文档发送报告。",
+ "reportUnexpectedError": "OpenPencil 出现了问题。",
+ "reportPanic": "OpenPencil 上次运行时发生了内部错误。",
+ "reportCrashed": "OpenPencil 在出错后意外关闭。"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.json
index 94dbcabc1..f71dfb977 100644
--- a/packages/vue/src/i18n/locales/zh-cn/menu.json
+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json
@@ -87,5 +87,6 @@
"togglePreview": "预览",
"saveTo": "保存到…",
"showVersionHistory": "显示版本历史",
- "saveToVersionHistory": "保存到版本历史…"
+ "saveToVersionHistory": "保存到版本历史…",
+ "reportProblem": "报告问题…"
}
diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.ts
index 17c113a01..218162ace 100644
--- a/packages/vue/src/i18n/messages/diagnostics.ts
+++ b/packages/vue/src/i18n/messages/diagnostics.ts
@@ -95,7 +95,35 @@ export const diagnosticsMessageDefaults = {
sharingQuestionAccept: 'Share stats',
sharingQuestionAccepted: 'Thank you. You can change this in Privacy settings.',
sharingQuestionDeclined: 'Usage stats stay off. You can change this in Privacy settings.',
- sharingLocalData: 'Usage and Diagnostics keep their records on this device and never send them.'
+ sharingLocalData:
+ 'Usage and Diagnostics keep their records on this device. Diagnostics leave it only in a report you choose to send.',
+ reportError: 'Report…',
+ reportErrorTitle: 'Report this error',
+ reportProblemTitle: 'Report a problem',
+ reportErrorDescription:
+ 'Send this error to the OpenPencil team so it can be fixed. Nothing is sent until you choose Send report.',
+ reportProblemDescription:
+ 'Tell the OpenPencil team what went wrong. Nothing is sent until you choose Send report.',
+ reportNoteError: 'What were you doing? (optional)',
+ reportNoteProblem: 'What happened?',
+ reportNotePlaceholder: 'What you did, what happened, and what you expected instead.',
+ reportEmail: 'Email (optional)',
+ reportEmailHint: 'Only if you want us to follow up.',
+ reportActivity: 'Include recent activity',
+ reportActivityDescription:
+ 'The last 50 events from Diagnostics, such as errors and timings. Never chat messages or tool output.',
+ reportDocument: 'Attach this document',
+ reportDocumentDescription:
+ 'Uploads the whole design as a .fig file. Only the OpenPencil team can open it, and it is deleted after 90 days.',
+ reportPreview: 'What will be sent',
+ reportSend: 'Send report',
+ reportSent: 'Report sent. Thank you.',
+ reportFailed: 'Could not send the report. Check your connection and try again.',
+ reportFilesFailed: 'The report was sent, but the document could not be uploaded.',
+ reportDocumentFailed: 'The document could not be attached. You can send the report without it.',
+ reportPanic: 'OpenPencil hit an internal error the last time it ran.',
+ reportCrashed: 'OpenPencil closed unexpectedly after an error.',
+ reportUnexpectedError: 'Something went wrong in OpenPencil.'
} as const
export const diagnosticsMessages = i18n('diagnostics', diagnosticsMessageDefaults)
diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.ts
index ee0809e8d..7820bad51 100644
--- a/packages/vue/src/i18n/messages/menu.ts
+++ b/packages/vue/src/i18n/messages/menu.ts
@@ -13,6 +13,7 @@ export const menuMessageDefaults = {
open: 'Open…',
openTour: 'Open the Tour',
diagnostics: 'Diagnostics…',
+ reportProblem: 'Report a problem…',
save: 'Save',
saveAs: 'Save as…',
saveTo: 'Save to…',
diff --git a/src/App.vue b/src/App.vue
index d57d8c85a..dfe69fe32 100644
--- a/src/App.vue
+++ b/src/App.vue
@@ -13,6 +13,7 @@ import { startCloud } from '@/app/cloud/integration'
import { useDocumentCloseProtection } from '@/app/document/close/use'
import { endRecoverySession, startRecoverySession } from '@/app/document/recovery/session'
import { useFollowingEditorStore } from '@/app/editor/active-store'
+import { offerCrashReports } from '@/app/reports/crash'
import { interfaceScalePreference } from '@/app/shell/interface-scale'
import { animationsEnabled } from '@/app/shell/motion'
import { useAppTheme } from '@/app/shell/theme'
@@ -25,6 +26,7 @@ import { CloudHosts } from '@/components/cloud/integration'
import UnsavedChangesDialog from '@/components/document/UnsavedChangesDialog.vue'
import PublishLibraryDialog from '@/components/libraries/PublishLibraryDialog.vue'
import LibraryUpdateReviewDialog from '@/components/libraries/review/LibraryUpdateReviewDialog.vue'
+import ReportDialogHost from '@/components/reports/ReportDialogHost.vue'
import SaveToHost from '@/components/save-to/SaveToHost.vue'
import AISetupDialog from '@/components/settings/ai-setup/AISetupDialog.vue'
import SettingsDialog from '@/components/settings/SettingsDialog.vue'
@@ -61,6 +63,7 @@ useEventListener(window, 'pageshow', (event) => {
onMounted(() => {
toast.setupGlobalErrorHandler()
+ void offerCrashReports()
scheduleStartupUpdateCheck(updates)
void kickSyncEngine()
onUnmounted(
@@ -83,6 +86,7 @@ onMounted(() => {
<PublishLibraryDialog />
<LibraryUpdateReviewDialog />
<UsageStatsPrompt />
+ <ReportDialogHost />
<AppToaster />
<VoiceCallAudio />
</TooltipProvider>
diff --git a/src/app/diagnostics/error.ts b/src/app/diagnostics/error.ts
index cce47c6b0..30b8a56fb 100644
--- a/src/app/diagnostics/error.ts
+++ b/src/app/diagnostics/error.ts
@@ -36,7 +36,7 @@ const MAX_STACK_LENGTH = 4000
* AI SDK and provider errors (`AI_APICallError`, `AI_InvalidPromptError`, …) and errors that
* carry a response can quote prompts, responses, or request URLs in their message.
*/
-function mayQuoteContent(error: Error): boolean {
+export function mayQuoteContent(error: Error): boolean {
return error.name.startsWith('AI_') || 'responseBody' in error || 'requestBodyValues' in error
}
diff --git a/src/app/diagnostics/events/runtime.ts b/src/app/diagnostics/events/runtime.ts
index 72de8b318..bc93ffe4a 100644
--- a/src/app/diagnostics/events/runtime.ts
+++ b/src/app/diagnostics/events/runtime.ts
@@ -1,3 +1,6 @@
+import { recoverySessionId } from '@/app/document/recovery/session'
+import { APP_VERSION } from '@/app/runtime/version'
+
import { diagnosticErrorDetails } from '../error'
import { recordDiagnostic } from '../recorder'
@@ -49,7 +52,10 @@ export function recordRuntimeError(
errorCode: details.errorCode,
message: details.message,
stack: details.stack,
- info: info ?? null
+ info: info ?? null,
+ // Which window's run and build it came from, so a launch after a crash can offer to report it.
+ appSession: recoverySessionId,
+ appVersion: APP_VERSION
}
})
}
diff --git a/src/app/diagnostics/index.ts b/src/app/diagnostics/index.ts
index 448ae2910..6b96ec368 100644
--- a/src/app/diagnostics/index.ts
+++ b/src/app/diagnostics/index.ts
@@ -11,7 +11,7 @@ export {
recordStorageFailure,
storageOperationForJob
} from './events'
-export { describeDiagnosticError, diagnosticErrorDetails } from './error'
+export { describeDiagnosticError, diagnosticErrorDetails, mayQuoteContent } from './error'
export { summarizeDiagnosticEvent } from './summary'
export type { DiagnosticEventSummary } from './summary'
export { diagnostics } from './recorder'
diff --git a/src/app/document/recovery/session/index.ts b/src/app/document/recovery/session/index.ts
index 1d727a572..63e347738 100644
--- a/src/app/document/recovery/session/index.ts
+++ b/src/app/document/recovery/session/index.ts
@@ -69,15 +69,20 @@ export function sessionStates(
return { live, crashed: new Set(started.filter((id) => !live.has(id))) }
}
+/** The sessions whose windows hold their lock right now. */
+async function heldSessions(locks: SessionLocks): Promise<string[]> {
+ const { held = [] } = await locks.query()
+ return held.flatMap(({ name }) =>
+ name?.startsWith(SESSION_LOCK_PREFIX) ? [name.slice(SESSION_LOCK_PREFIX.length)] : []
+ )
+}
+
export async function recoverySessionStates(
locks = sessionLocks()
): Promise<RecoverySessionStates> {
if (!locks) return sessionStates(startedSessionIds(), null)
const before = startedSessionIds()
- const { held = [] } = await locks.query()
- const sessions = held.flatMap(({ name }) =>
- name?.startsWith(SESSION_LOCK_PREFIX) ? [name.slice(SESSION_LOCK_PREFIX.length)] : []
- )
+ const sessions = await heldSessions(locks)
// Started both before and after the query: one that began or ended meanwhile is not a crash.
const after = new Set(startedSessionIds())
return sessionStates(
diff --git a/src/app/reports/build.ts b/src/app/reports/build.ts
new file mode 100644
index 000000000..14c292f4b
--- /dev/null
+++ b/src/app/reports/build.ts
@@ -0,0 +1,95 @@
+import { getInjectedReleaseId } from '@posthog/core/error-tracking'
+import * as v from 'valibot'
+
+import {
+ REPORT_BODY_MAX_BYTES,
+ reportSchema,
+ type Build,
+ type Report,
+ type ReportException,
+ type ReportFileName
+} from '@open-pencil/feedback/contract'
+
+import type { DiagnosticEvent } from '@/app/diagnostics'
+
+import { reportSteps } from './steps'
+
+/** A file attached to a report, under a fixed name the service accepts. */
+export interface ReportAttachment {
+ name: ReportFileName
+ bytes: Uint8Array
+}
+
+/** What the person filled in, and what the app knows about the error, before it becomes a report. */
+export interface ReportDraft {
+ /** The caught error, or none for a problem the person describes. */
+ exceptions: ReportException[] | null
+ note: string
+ email: string
+ /** Recent diagnostics events, recent first, when the person agreed to include them. */
+ activity: DiagnosticEvent[] | null
+ attachments: ReportAttachment[]
+}
+
+/** What else goes into every report: the build, and the install ID only while usage stats are shared. */
+export interface ReportContext {
+ build: Build
+ installId: string | null
+}
+
+function optionalText(text: string): string | undefined {
+ const trimmed = text.trim()
+ return trimmed ? trimmed : undefined
+}
+
+const encoder = new TextEncoder()
+
+function bodyBytes(value: unknown): number {
+ return encoder.encode(JSON.stringify(value)).byteLength
+}
+
+/**
+ * The report within the body limit: its most recent steps that fit, or `null` when even without
+ * steps it is too large.
+ */
+function withinBodyLimit(report: Report): Report | null {
+ if (bodyBytes(report) <= REPORT_BODY_MAX_BYTES) return report
+ const steps = report.steps ?? []
+ // Counts an empty list, which is longer than none, and a comma before each step.
+ let budget = REPORT_BODY_MAX_BYTES - bodyBytes({ ...report, steps: [] })
+ let kept = 0
+ for (const step of steps.toReversed()) {
+ const size = bodyBytes(step) + 1
+ if (size > budget) break
+ budget -= size
+ kept++
+ }
+ if (kept > 0) return { ...report, steps: steps.slice(-kept) }
+ const withoutSteps = { ...report, steps: undefined }
+ return bodyBytes(withoutSteps) <= REPORT_BODY_MAX_BYTES ? withoutSteps : null
+}
+
+/**
+ * The report exactly as it will be sent, which the dialog shows before sending, or `null` while
+ * the draft is not one the service would accept, such as a problem without a description. Steps
+ * that would push the body past the service's limit are left out, oldest first.
+ */
+export function buildReport(draft: ReportDraft, context: ReportContext): Report | null {
+ const steps = draft.activity ? reportSteps(draft.activity) : undefined
+ const fields = {
+ ...context.build,
+ installId: context.installId ?? undefined,
+ release: draft.exceptions ? getInjectedReleaseId() : undefined,
+ note: optionalText(draft.note),
+ email: optionalText(draft.email),
+ steps: steps?.length ? steps : undefined,
+ files: draft.attachments.length
+ ? draft.attachments.map((file) => ({ name: file.name, size: file.bytes.byteLength }))
+ : undefined
+ }
+ const report = draft.exceptions
+ ? { kind: 'error', exceptions: draft.exceptions, ...fields }
+ : { kind: 'problem', ...fields }
+ const parsed = v.safeParse(reportSchema, report)
+ return parsed.success ? withinBodyLimit(parsed.output) : null
+}
diff --git a/src/app/reports/crash.ts b/src/app/reports/crash.ts
new file mode 100644
index 000000000..19bfd3383
--- /dev/null
+++ b/src/app/reports/crash.ts
@@ -0,0 +1,117 @@
+import { invoke } from '@tauri-apps/api/core'
+import { useLocalStorage } from '@vueuse/core'
+import * as v from 'valibot'
+
+import { REPORT_ERROR_SOURCES, type ReportException } from '@open-pencil/feedback/contract'
+import { diagnosticsMessages } from '@open-pencil/vue/i18n'
+
+import { diagnostics, type DiagnosticEvent } from '@/app/diagnostics'
+import { scrubDiagnosticText } from '@/app/diagnostics/scrub'
+import { recoverySessionStates } from '@/app/document/recovery/session'
+import { startedSessionIds } from '@/app/document/recovery/session/storage'
+import { APP_VERSION } from '@/app/runtime/version'
+import { toast } from '@/app/shell/ui'
+import { IS_TAURI } from '@/constants'
+
+import { reportExceptions } from './exception'
+import { reportAction, REPORTS_ENABLED } from './state'
+
+/**
+ * The sessions that crashed, read as the app launches. Recovery forgets the crashed sessions it has
+ * no copies of, after a lock query of its own that is queued behind this one; a window that closes
+ * meanwhile leaves the registry, so it is not taken for a crash.
+ */
+const crashedAtLaunch = recoverySessionStates()
+ .then((states) => states.crashed)
+ .catch(() => new Set<string>())
+
+/**
+ * Crashed sessions already offered, so each crash is offered once whatever is chosen. Only those
+ * still in the registry are kept, as no other can be offered again.
+ */
+const offeredSessions = useLocalStorage<string[]>('open-pencil:reports:offered-crashes', [])
+
+const panicSchema = v.object({
+ message: v.string(),
+ location: v.nullable(v.string()),
+ version: v.string()
+})
+
+const runtimeErrorSchema = v.object({
+ source: v.picklist(REPORT_ERROR_SOURCES),
+ errorName: v.string(),
+ message: v.nullable(v.string()),
+ stack: v.nullable(v.string()),
+ appSession: v.string(),
+ appVersion: v.string()
+})
+type RuntimeError = v.InferOutput<typeof runtimeErrorSchema>
+
+/** A Rust panic as one exception; it has no JavaScript frames, only where in the source it was. */
+export function panicExceptions(panic: v.InferOutput<typeof panicSchema>): ReportException[] {
+ const where = panic.location ? ` (${panic.location})` : ''
+ return [
+ {
+ type: 'panic',
+ value: scrubDiagnosticText(`${panic.message}${where}`).slice(0, 1000),
+ mechanism: { handled: false, synthetic: false, type: 'panic' }
+ }
+ ]
+}
+
+/** The error a crashed session last logged, rebuilt from its scrubbed message and stack. */
+export function storedErrorExceptions(error: RuntimeError): ReportException[] {
+ const rebuilt = new Error(error.message ?? '')
+ rebuilt.name = error.errorName
+ if (error.stack) rebuilt.stack = error.stack
+ return reportExceptions(rebuilt, error.source)
+}
+
+/**
+ * The last error each crashed session logged under this build, most recent first. An error from
+ * another build would point at chunks this one does not have.
+ */
+export function crashErrors(
+ events: readonly DiagnosticEvent[],
+ crashed: ReadonlySet<string>
+): (RuntimeError & { at: number })[] {
+ const errors = events.flatMap((event) => {
+ if (event.name !== 'runtime.error') return []
+ const parsed = v.safeParse(runtimeErrorSchema, event.attributes)
+ if (!parsed.success || parsed.output.appVersion !== APP_VERSION) return []
+ return crashed.has(parsed.output.appSession) ? [{ ...parsed.output, at: event.timestamp }] : []
+ })
+ return errors.toSorted((a, b) => b.at - a.at)
+}
+
+function offer(message: string, exceptions: ReportException[]): void {
+ toast.error(message, reportAction(exceptions))
+}
+
+async function lastPanic() {
+ if (!IS_TAURI) return null
+ const answer: unknown = await invoke('take_last_panic').catch(() => null)
+ const parsed = v.safeParse(v.nullable(panicSchema), answer)
+ return parsed.success && parsed.output?.version === APP_VERSION ? parsed.output : null
+}
+
+/**
+ * On launch, offers to report what ended the last run: a desktop panic, or the last error of a
+ * window whose run ended without the window closing, such as a crash or a killed process. Nothing is
+ * sent unless the person opens the report and sends it.
+ */
+export async function offerCrashReports(): Promise<void> {
+ if (!REPORTS_ENABLED) return
+ const messages = diagnosticsMessages.get()
+ const panic = await lastPanic()
+ if (panic) offer(messages.reportPanic, panicExceptions(panic))
+
+ const offered = new Set(offeredSessions.value)
+ const crashed = new Set([...(await crashedAtLaunch)].filter((id) => !offered.has(id)))
+ if (crashed.size === 0) return
+ const events = await diagnostics.list()
+ const registered = new Set(startedSessionIds())
+ offeredSessions.value = [...offered, ...crashed].filter((id) => registered.has(id))
+ const last = crashErrors(events, crashed).at(0)
+ if (last) offer(messages.reportCrashed, storedErrorExceptions(last))
+}
diff --git a/src/app/reports/dialog.ts b/src/app/reports/dialog.ts
new file mode 100644
index 000000000..467ac21db
--- /dev/null
+++ b/src/app/reports/dialog.ts
@@ -0,0 +1,177 @@
+import * as v from 'valibot'
+import { computed, ref, shallowRef, watch } from 'vue'
+
+import { exportFigFile } from '@open-pencil/core/io/formats/fig'
+import type { Build, ReportReceipt } from '@open-pencil/feedback/contract'
+import { diagnosticsMessages } from '@open-pencil/vue/i18n'
+
+import { diagnostics, type DiagnosticEvent } from '@/app/diagnostics'
+import { useActiveEditorStoreRef, type EditorStore } from '@/app/editor/active-store'
+import { appPreferences } from '@/app/settings/preferences/store'
+import { toast } from '@/app/shell/ui'
+import { showsDocument } from '@/app/tabs'
+import { currentBuild } from '@/app/telemetry/build'
+import { sharingState } from '@/app/telemetry/state'
+
+import { buildReport, type ReportAttachment } from './build'
+import { sendReport, type ReportSendFailure } from './send'
+import {
+ reportDialogError,
+ reportDialogNotice,
+ reportDialogOpen,
+ reportDialogOpening
+} from './state'
+
+/** The install ID while usage stats are shared, read as it changes, also from another window. */
+function sharedInstallId(): string | null {
+ const shared = appPreferences.value.sharing.usageStats === 'granted'
+ return shared ? sharingState.value.installId : null
+}
+
+/** The document in the active tab; Home and a New file tab hold none, as the File menu decides. */
+const activeDocument = computed(() =>
+ showsDocument() ? (useActiveEditorStoreRef().value ?? null) : null
+)
+
+/** A document as a `.fig` file under the name reports accept, never its own name. */
+async function documentAttachment(store: EditorStore): Promise<ReportAttachment> {
+ const bytes = await exportFigFile(store.graph, {
+ pageId: store.state.currentPageId,
+ documentName: 'document'
+ })
+ return { name: 'document.fig', bytes }
+}
+
+/**
+ * The report dialog's draft, the exact report it would send, and sending it. Fields reset as the
+ * dialog opens; the recent activity is read then too, so the preview does not change under the
+ * person while they read it.
+ */
+export function useReportDialog() {
+ const note = ref('')
+ const email = ref('')
+ const includeActivity = ref(true)
+ const attachDocument = ref(false)
+ const hasDocument = computed(() => activeDocument.value !== null)
+ const sending = ref(false)
+ const failure = ref<ReportSendFailure | null>(null)
+ const build = shallowRef<Build | null>(null)
+ const activity = shallowRef<DiagnosticEvent[]>([])
+ const attachment = shallowRef<ReportAttachment | null>(null)
+ const preparingDocument = ref(false)
+ const documentFailed = ref(false)
+ /** Set once the report went through but a file did not, so Send uploads only the files. */
+ const delivered = shallowRef<ReportReceipt | null>(null)
+ let exportRequest = 0
+
+ // Each opening resets the draft, also one that replaces a report still open.
+ watch(
+ reportDialogOpening,
+ async () => {
+ if (!reportDialogOpen.value) return
+ note.value = ''
+ email.value = ''
+ includeActivity.value = true
+ attachDocument.value = false
+ attachment.value = null
+ failure.value = null
+ delivered.value = null
+ sending.value = false
+ activity.value = diagnostics.recent()
+ build.value = await currentBuild()
+ },
+ { immediate: true }
+ )
+
+ // The attachment follows the active tab, so a tab switched to with the dialog open is the one sent.
+ watch([attachDocument, activeDocument], async ([attach, store]) => {
+ // Only the latest export counts: an earlier one may be of the tab that was active before.
+ const request = ++exportRequest
+ attachment.value = null
+ documentFailed.value = false
+ preparingDocument.value = attach && store !== null
+ if (!attach || !store) return
+ try {
+ const file = await documentAttachment(store)
+ if (request === exportRequest) attachment.value = file
+ } catch {
+ if (request === exportRequest) documentFailed.value = true
+ } finally {
+ if (request === exportRequest) preparingDocument.value = false
+ }
+ })
+
+ // A changed report is a new one: sending it posts it rather than reusing a delivered receipt.
+ watch([note, email, includeActivity, attachment], () => {
+ delivered.value = null
+ })
+
+ const kind = computed(() => (reportDialogError.value ? 'error' : 'problem'))
+
+ /** The body that would be sent, or `null` while the service would refuse it. */
+ const report = computed(() => {
+ if (!build.value) return null
+ if (attachDocument.value && (!attachment.value || !hasDocument.value)) return null
+ return buildReport(
+ {
+ exceptions: reportDialogError.value,
+ note: note.value,
+ email: email.value,
+ activity: includeActivity.value ? activity.value : null,
+ attachments: attachment.value ? [attachment.value] : []
+ },
+ { build: build.value, installId: sharedInstallId() }
+ )
+ })
+
+ const preview = computed(() => (report.value ? JSON.stringify(report.value, null, 2) : ''))
+ const emailInvalid = computed(() => {
+ const value = email.value.trim()
+ return value !== '' && !v.is(v.pipe(v.string(), v.email()), value)
+ })
+
+ async function send(): Promise<void> {
+ const body = report.value
+ if (!body || sending.value) return
+ // A send that ends after the dialog opened again leaves the newer report alone.
+ const opening = reportDialogOpening.value
+ const notice = reportDialogNotice.value
+ const current = () => opening === reportDialogOpening.value
+ sending.value = true
+ failure.value = null
+ try {
+ const result = await sendReport(body, attachment.value ? [attachment.value] : [], {
+ delivered: delivered.value
+ })
+ if (!result.ok) {
+ if (!current()) return
+ failure.value = result.failure
+ if (result.failure === 'files') delivered.value = result.receipt
+ return
+ }
+ // The notice that offered this report would only offer it again.
+ if (notice) toast.removeOffer(notice.toastId, notice.action)
+ toast.info(diagnosticsMessages.get().reportSent)
+ if (current()) reportDialogOpen.value = false
+ } finally {
+ if (current()) sending.value = false
+ }
+ }
+
+ return {
+ kind,
+ note,
+ email,
+ emailInvalid,
+ includeActivity,
+ attachDocument,
+ hasDocument,
+ preparingDocument,
+ documentFailed,
+ report,
+ preview,
+ sending,
+ failure,
+ send
+ }
+}
diff --git a/src/app/reports/exception.ts b/src/app/reports/exception.ts
new file mode 100644
index 000000000..5d45de5a2
--- /dev/null
+++ b/src/app/reports/exception.ts
@@ -0,0 +1,121 @@
+import {
+ createDefaultStackParser,
+ DOMExceptionCoercer,
+ ErrorCoercer,
+ ErrorEventCoercer,
+ ErrorPropertiesBuilder,
+ EventCoercer,
+ ObjectCoercer,
+ PrimitiveCoercer,
+ PromiseRejectionEventCoercer,
+ StringCoercer,
+ type Exception,
+ type StackFrame
+} from '@posthog/core/error-tracking'
+
+import {
+ REPORT_FRAMES_LIMIT,
+ type ReportErrorSource,
+ type ReportException,
+ type ReportFrame
+} from '@open-pencil/feedback/contract'
+
+import { diagnosticErrorDetails, mayQuoteContent } from '@/app/diagnostics'
+import { scrubDiagnosticText } from '@/app/diagnostics/scrub'
+
+/** PostHog's own conversion, as its browser SDK sets it up; it also reads the injected chunk IDs. */
+const builder = new ErrorPropertiesBuilder(
+ [
+ new DOMExceptionCoercer(),
+ new PromiseRejectionEventCoercer(),
+ new ErrorEventCoercer(),
+ new ErrorCoercer(),
+ new EventCoercer(),
+ new ObjectCoercer(),
+ new StringCoercer(),
+ new PrimitiveCoercer()
+ ],
+ createDefaultStackParser()
+)
+
+const MAX_TYPE_LENGTH = 128
+const MAX_VALUE_LENGTH = 1000
+const MAX_FILENAME_LENGTH = 1024
+const MAX_FUNCTION_LENGTH = 256
+const MAX_EXCEPTIONS = 5
+const CHUNK_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
+
+function position(value: number | undefined): number | undefined {
+ return value !== undefined && Number.isInteger(value) && value >= 0 ? value : undefined
+}
+
+function toFrame(frame: StackFrame): ReportFrame {
+ return {
+ platform: 'web:javascript',
+ filename: frame.filename && scrubDiagnosticText(frame.filename).slice(0, MAX_FILENAME_LENGTH),
+ function: frame.function?.slice(0, MAX_FUNCTION_LENGTH),
+ lineno: position(frame.lineno),
+ colno: position(frame.colno),
+ in_app: frame.in_app,
+ chunk_id: frame.chunk_id && CHUNK_ID.test(frame.chunk_id) ? frame.chunk_id : undefined
+ }
+}
+
+function toException(
+ exception: Exception,
+ value: string | undefined,
+ source: ReportErrorSource
+): ReportException {
+ const frames = exception.stacktrace?.frames ?? []
+ return {
+ type: (exception.type || 'Error').slice(0, MAX_TYPE_LENGTH),
+ value: value?.slice(0, MAX_VALUE_LENGTH),
+ mechanism: {
+ handled: exception.mechanism?.handled ?? false,
+ synthetic: exception.mechanism?.synthetic ?? false,
+ type: source
+ },
+ stacktrace:
+ frames.length > 0
+ ? { type: 'raw', frames: frames.slice(-REPORT_FRAMES_LIMIT).map(toFrame) }
+ : undefined
+ }
+}
+
+/** The error and the causes it chains, as far as a report follows them. */
+function causeChain(error: unknown): unknown[] {
+ const chain: unknown[] = []
+ for (let link = error; link !== undefined && chain.length < MAX_EXCEPTIONS;) {
+ if (chain.includes(link)) break
+ chain.push(link)
+ link = link instanceof Error ? link.cause : undefined
+ }
+ return chain
+}
+
+/**
+ * An uncaught error, its causes included, as PostHog error tracking reads it. Messages are
+ * scrubbed as the diagnostics log scrubs them; when any error in the chain may quote prompts or
+ * responses, as provider errors do, no message in it is kept, only types and frames.
+ */
+export function reportExceptions(error: unknown, source: ReportErrorSource): ReportException[] {
+ const exceptions = builder
+ .buildFromUnknown(error, { mechanism: { handled: false } })
+ .$exception_list.slice(0, MAX_EXCEPTIONS)
+ const quotesContent = causeChain(error).some(
+ (link) => link instanceof Error && mayQuoteContent(link)
+ )
+ const topMessage = diagnosticErrorDetails(error).message
+ return exceptions.map((exception, index) => {
+ if (quotesContent) return toException(exception, undefined, source)
+ const value = index === 0 ? topMessage : exception.value && scrubDiagnosticText(exception.value)
+ return toException(exception, value || undefined, source)
+ })
+}
+
+/** Whether a frame of the error ran in OpenPencil's own code rather than an extension or a page script. */
+export function isOwnError(exceptions: ReportException[], origin: string): boolean {
+ return exceptions.some((exception) =>
+ exception.stacktrace?.frames.some((frame) => frame.filename?.startsWith(`${origin}/`))
+ )
+}
diff --git a/src/app/reports/send.ts b/src/app/reports/send.ts
new file mode 100644
index 000000000..2e952c791
--- /dev/null
+++ b/src/app/reports/send.ts
@@ -0,0 +1,68 @@
+import * as v from 'valibot'
+
+import type { FeedbackClient } from '@open-pencil/feedback/client'
+import {
+ reportReceiptSchema,
+ type Report,
+ type ReportReceipt
+} from '@open-pencil/feedback/contract'
+
+import { feedback } from '@/app/feedback/client'
+
+import type { ReportAttachment } from './build'
+
+export type ReportSendResult =
+ | { ok: true; reportId: string }
+ | { ok: false; failure: 'report' }
+ /** The report went through; sending again with its receipt uploads only the files. */
+ | { ok: false; failure: 'files'; receipt: ReportReceipt }
+
+/** Which step failed: the report itself, or an attached file after the report went through. */
+export type ReportSendFailure = Extract<ReportSendResult, { ok: false }>['failure']
+
+export interface ReportSendOptions {
+ client?: FeedbackClient
+ /** The receipt of this report from an earlier send whose files failed, so it is not sent twice. */
+ delivered?: ReportReceipt | null
+}
+
+async function deliver(report: Report, client: FeedbackClient): Promise<ReportReceipt | null> {
+ const response = await client.reports.$post({ json: report }).catch(() => null)
+ if (response?.status !== 201) return null
+ const receipt = v.safeParse(reportReceiptSchema, await response.json().catch(() => null))
+ return receipt.success ? receipt.output : null
+}
+
+/**
+ * Sends a report to the feedback service, then each attached file with the token its answer
+ * carries. A failed upload still leaves the report delivered, under its receipt.
+ */
+export async function sendReport(
+ report: Report,
+ attachments: ReportAttachment[],
+ { client = feedback, delivered = null }: ReportSendOptions = {}
+): Promise<ReportSendResult> {
+ const receipt = delivered ?? (await deliver(report, client))
+ if (!receipt) return { ok: false, failure: 'report' }
+ const { reportId, uploadToken } = receipt
+ if (attachments.length === 0) return { ok: true, reportId }
+ if (!uploadToken) return { ok: false, failure: 'files', receipt }
+
+ for (const file of attachments) {
+ const uploaded = await client.reports[':reportId'].files[':name']
+ .$put(
+ { param: { reportId, name: file.name } },
+ {
+ headers: {
+ Authorization: `Bearer ${uploadToken}`,
+ 'Content-Type': 'application/octet-stream'
+ },
+ // A copy backed by a plain ArrayBuffer, which `fetch` takes as a body.
+ init: { body: file.bytes.slice() }
+ }
+ )
+ .catch(() => null)
+ if (uploaded?.status !== 204) return { ok: false, failure: 'files', receipt }
+ }
+ return { ok: true, reportId }
+}
diff --git a/src/app/reports/state.ts b/src/app/reports/state.ts
new file mode 100644
index 000000000..23a6ed4ea
--- /dev/null
+++ b/src/app/reports/state.ts
@@ -0,0 +1,64 @@
+import { ref, shallowRef } from 'vue'
+
+import type { ReportErrorSource, ReportException } from '@open-pencil/feedback/contract'
+import { diagnosticsMessages } from '@open-pencil/vue/i18n'
+
+import type { ToastAction } from '@/app/shell/ui'
+import { FEEDBACK_ENABLED } from '@/app/telemetry/config'
+
+import { isOwnError, reportExceptions } from './exception'
+
+/** Only official builds send reports, as only they send anything; others never offer it. */
+export const REPORTS_ENABLED = FEEDBACK_ENABLED
+
+export const reportDialogOpen = ref(false)
+/** The error the open dialog reports, or `null` for a problem the person describes. */
+export const reportDialogError = shallowRef<ReportException[] | null>(null)
+/** A toast that offered a report, and the action on it that did. */
+export interface ReportNotice {
+ toastId: number
+ action: ToastAction
+}
+
+/** The notice that offered the open report, which goes away once the report is sent. */
+export const reportDialogNotice = shallowRef<ReportNotice | null>(null)
+/** Counts the dialog's openings, so a send that ends after a newer one opened leaves it alone. */
+export const reportDialogOpening = ref(0)
+
+/**
+ * Opens the report dialog, for a caught error or, without one, for a problem the person
+ * describes; `notice` is the toast that offered it.
+ */
+export function openReportDialog(
+ exceptions: ReportException[] | null = null,
+ notice: ReportNotice | null = null
+): void {
+ reportDialogError.value = exceptions
+ reportDialogNotice.value = notice
+ reportDialogOpening.value++
+ reportDialogOpen.value = true
+}
+
+/** A toast action that opens the report dialog for `exceptions`. */
+export function reportAction(exceptions: ReportException[]): ToastAction {
+ const action: ToastAction = {
+ label: diagnosticsMessages.get().reportError,
+ run: (toastId) => openReportDialog(exceptions, { toastId, action })
+ }
+ return action
+}
+
+/**
+ * The Report action for an uncaught error's notice, or none when this build sends nothing or the
+ * error came from an extension or a page script rather than OpenPencil. The stack is read now,
+ * while the code that threw is still the code running.
+ */
+export function reportErrorAction(
+ error: unknown,
+ source: ReportErrorSource
+): ToastAction | undefined {
+ if (!REPORTS_ENABLED) return undefined
+ const exceptions = reportExceptions(error, source)
+ if (!isOwnError(exceptions, location.origin)) return undefined
+ return reportAction(exceptions)
+}
diff --git a/src/app/reports/steps.ts b/src/app/reports/steps.ts
new file mode 100644
index 000000000..2c9e2a5c1
--- /dev/null
+++ b/src/app/reports/steps.ts
@@ -0,0 +1,38 @@
+import { REPORT_STEPS_LIMIT, type ReportStep } from '@open-pencil/feedback/contract'
+
+import type { DiagnosticEvent } from '@/app/diagnostics'
+
+const MAX_ATTRIBUTES = 24
+const MAX_TEXT_LENGTH = 4000
+const STEP_NAME = /^[a-z][a-z0-9_.]{0,63}$/
+const ATTRIBUTE_KEY = /^[A-Za-z][\w.]{0,63}$/
+
+function toStep(event: DiagnosticEvent): ReportStep | null {
+ if (!STEP_NAME.test(event.name) || !/^[a-z]{1,32}$/.test(event.category)) return null
+ return {
+ name: event.name,
+ category: event.category,
+ level: event.level,
+ timestamp: new Date(event.timestamp).toISOString(),
+ attributes: Object.fromEntries(
+ Object.entries(event.attributes)
+ .filter(([key]) => ATTRIBUTE_KEY.test(key))
+ .slice(0, MAX_ATTRIBUTES)
+ .map(([key, value]) => [
+ key,
+ typeof value === 'string' ? value.slice(0, MAX_TEXT_LENGTH) : value
+ ])
+ )
+ }
+}
+
+/**
+ * The most recent diagnostics events, oldest first, as a report's steps. The log scrubbed them
+ * when it recorded them and never holds chat messages or tool payloads.
+ */
+export function reportSteps(recentFirst: DiagnosticEvent[]): ReportStep[] {
+ return recentFirst
+ .slice(0, REPORT_STEPS_LIMIT)
+ .flatMap((event) => toStep(event) ?? [])
+ .reverse()
+}
diff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.ts
index 7282c4419..f8de35273 100644
--- a/src/app/shell/menu/app-menu.ts
+++ b/src/app/shell/menu/app-menu.ts
@@ -26,6 +26,7 @@ import type {
import { openTour } from '@/app/demo/document'
import { useEditorStore } from '@/app/editor/active-store'
+import { openReportDialog } from '@/app/reports/state'
import { openSettingsDialog } from '@/app/settings/dialog'
import {
setCommentsOnCanvas,
@@ -110,6 +111,7 @@ export function useAppMenu() {
open: 'open',
'open-tour': 'openTour',
diagnostics: 'diagnostics',
+ 'report-problem': 'reportProblem',
save: 'save',
'save-as': 'saveAs',
'save-to': 'saveTo',
@@ -193,6 +195,7 @@ export function useAppMenu() {
'next-tab': () => switchAdjacentTab(1),
settings: openSettingsDialog,
diagnostics: () => openSettingsDialog('diagnostics'),
+ 'report-problem': () => openReportDialog(),
'export-png': () => exportSelection('png'),
'export-svg': () => exportSelection('svg'),
'export-pptx': () => exportSelection('pptx'),
diff --git a/src/app/shell/menu/features.ts b/src/app/shell/menu/features.ts
index f530f21be..aa9308678 100644
--- a/src/app/shell/menu/features.ts
+++ b/src/app/shell/menu/features.ts
@@ -3,6 +3,7 @@ import { computed, watch } from 'vue'
import { isCloudBinding } from '@/app/cloud/integration'
import { useEditorStore } from '@/app/editor/active-store'
+import { REPORTS_ENABLED } from '@/app/reports/state'
import { showsDocument } from '@/app/tabs'
import { isTauri } from '@/app/tauri/env'
@@ -16,7 +17,8 @@ const available: Record<AppMenuFeature, () => boolean> = {
// Cloud and storage documents always save; auto-save is a choice only for a file on disk.
'local-file': () => store.hasWritableSource() && !store.getStorageBinding(),
// Version history lives on the Cloud server that keeps the document.
- 'cloud-document': () => isCloudBinding(store.getStorageBinding())
+ 'cloud-document': () => isCloudBinding(store.getStorageBinding()),
+ reports: () => REPORTS_ENABLED
}
/** Whether a menu item that waits for a feature shows; items without one always do. */
diff --git a/src/app/shell/menu/schema/index.ts b/src/app/shell/menu/schema/index.ts
index 60b1848d0..a028abf76 100644
--- a/src/app/shell/menu/schema/index.ts
+++ b/src/app/shell/menu/schema/index.ts
@@ -37,6 +37,13 @@ export const APP_MENU_SCHEMA = [
handler: 'shell',
palette: { keywords: ['log', 'report', 'bug', 'problem', 'troubleshoot'] }
},
+ {
+ id: 'report-problem',
+ feature: 'reports',
+ label: 'Report a Problem…',
+ handler: 'shell',
+ palette: { keywords: ['bug', 'issue', 'feedback', 'crash', 'support'] }
+ },
{ type: 'separator' },
{ id: 'save', feature: 'document', label: 'Save', shortcut: 'MOD+S' },
{ id: 'save-as', feature: 'document', label: 'Save As…', shortcut: 'MOD+SHIFT+S' },
diff --git a/src/app/shell/menu/schema/types.ts b/src/app/shell/menu/schema/types.ts
index 09b115649..041e8152b 100644
--- a/src/app/shell/menu/schema/types.ts
+++ b/src/app/shell/menu/schema/types.ts
@@ -38,9 +38,9 @@ export type AppMenuHandler = 'editor' | 'shell'
* A feature an item or a whole menu waits for: it shows only while the feature is available
* (`./features`). `document`: the tab in front holds a document, not Home or a New file tab;
* `local-file`: that document is backed by a file on disk; `cloud-document`: it is kept by a
- * Cloud server.
+ * Cloud server; `reports`: the build sends problem reports, which only official releases do.
*/
-export type AppMenuFeature = 'document' | 'local-file' | 'cloud-document'
+export type AppMenuFeature = 'document' | 'local-file' | 'cloud-document' | 'reports'
export interface AppMenuActionItem {
type?: 'item'
diff --git a/src/app/shell/menu/shell.ts b/src/app/shell/menu/shell.ts
index 3ed8f412d..577a2fea4 100644
--- a/src/app/shell/menu/shell.ts
+++ b/src/app/shell/menu/shell.ts
@@ -3,6 +3,7 @@ import { useI18n } from '@open-pencil/vue/i18n'
import { openTour } from '@/app/demo/document'
import { requestAppExit } from '@/app/document/close/exit'
import { useActiveEditorStoreRef } from '@/app/editor/active-store'
+import { openReportDialog } from '@/app/reports/state'
import { openSettingsDialog } from '@/app/settings/dialog'
import { setDesignIssuesOnCanvas, setSnappingPreference } from '@/app/settings/preferences/apply'
import {
@@ -61,6 +62,7 @@ export function useShellMenu() {
},
settings: openSettingsDialog,
diagnostics: () => openSettingsDialog('diagnostics'),
+ 'report-problem': () => openReportDialog(),
'snap-geometry': () => {
const current = appPreferences.value.editing.snapping.geometry
setSnappingPreference('geometry', !current)
diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.ts
index 576edaadb..1bb2044bd 100644
--- a/src/app/shell/ui.ts
+++ b/src/app/shell/ui.ts
@@ -1,10 +1,11 @@
import { invoke } from '@tauri-apps/api/core'
import { useEventListener } from '@vueuse/core'
-import { ref } from 'vue'
+import { ref, toRaw } from 'vue'
import { ReadOnlyDocumentError } from '@open-pencil/core'
import { recordRuntimeError } from '@/app/diagnostics'
+import { reportErrorAction } from '@/app/reports/state'
import { isTauri } from '@/app/tauri/env'
import type { ProgressAmount } from '@/components/ui/feedback/progress'
import type { ToastVariant } from '@/components/ui/feedback/toast'
@@ -13,7 +14,8 @@ export type { ToastVariant } from '@/components/ui/feedback/toast'
export interface ToastAction {
label: string
- run: () => void
+ /** Gets the toast it was clicked on, for actions that close it once their work is done. */
+ run: (toastId: number) => void
}
export interface Toast {
@@ -135,6 +137,14 @@ function remove(id: number) {
toasts.value = toasts.value.filter((t) => t.id !== id)
}
+/**
+ * Removes the toast once its action is done, unless a later message merged into it and brought
+ * an action of its own, which stays on offer.
+ */
+function removeOffer(id: number, action: ToastAction) {
+ toasts.value = toasts.value.filter((t) => t.id !== id || toRaw(t.action) !== action)
+}
+
function setupGlobalErrorHandler() {
if (errorHandlersInitialized) return
errorHandlersInitialized = true
@@ -146,7 +156,10 @@ function setupGlobalErrorHandler() {
return
}
recordRuntimeError(e.error ?? e.message, 'window')
- error(e.message || 'An unexpected error occurred')
+ error(
+ e.message || 'An unexpected error occurred',
+ reportErrorAction(e.error ?? e.message, 'window')
+ )
})
useEventListener(window, 'unhandledrejection', (e) => {
if (e.reason instanceof ReadOnlyDocumentError) {
@@ -155,7 +168,7 @@ function setupGlobalErrorHandler() {
}
recordRuntimeError(e.reason, 'rejection')
const msg = e.reason instanceof Error ? e.reason.message : String(e.reason)
- error(msg || 'An unexpected error occurred')
+ error(msg || 'An unexpected error occurred', reportErrorAction(e.reason, 'rejection'))
})
}
@@ -165,6 +178,7 @@ export const toast = {
error,
startProgress,
remove,
+ removeOffer,
toasts,
setupGlobalErrorHandler,
TOAST_DURATION,
diff --git a/src/boot.ts b/src/boot.ts
index f5668cbbd..f0f52a523 100644
--- a/src/boot.ts
+++ b/src/boot.ts
@@ -2,6 +2,7 @@ import { createHead } from '@unhead/vue/client'
import { createApp, nextTick } from 'vue'
import { ReadOnlyDocumentError } from '@open-pencil/core'
+import { diagnosticsMessages } from '@open-pencil/vue/i18n'
import { createRetainedScopePlugin } from '@open-pencil/vue/lifecycle/retention'
import './app.css'
@@ -10,8 +11,10 @@ import { installNativeFigArchives } from '@/app/document/io/native-fig'
import { installCanvasKitBinary, preloadCanvasKit } from '@/app/editor/canvas/canvaskit'
import { preloadFonts } from '@/app/editor/fonts'
import { installBundledFonts } from '@/app/editor/fonts/bundled'
+import { reportErrorAction } from '@/app/reports/state'
import { observeBootErrors } from '@/app/shell/support/boot'
import { reportBootFailure } from '@/app/shell/support/gate'
+import { toast } from '@/app/shell/ui'
import { IS_TAURI } from '@/constants'
import App from './App.vue'
@@ -46,6 +49,9 @@ export async function boot(): Promise<void> {
if (error instanceof ReadOnlyDocumentError) return
recordRuntimeError(error, 'vue', info)
console.error(error)
+ // Official builds offer to report it; others keep it in the console and the diagnostics log.
+ const report = reportErrorAction(error, 'vue')
+ if (report) toast.error(diagnosticsMessages.get().reportUnexpectedError, report)
}
if (!IS_TAURI) {
diff --git a/src/components/reports/ReportDialog.stories.ts b/src/components/reports/ReportDialog.stories.ts
new file mode 100644
index 000000000..88e157686
--- /dev/null
+++ b/src/components/reports/ReportDialog.stories.ts
@@ -0,0 +1,121 @@
+import type { Meta, StoryObj } from '@storybook/vue3-vite'
+import { expect, fn, waitFor } from 'storybook/test'
+import { ref } from 'vue'
+
+import type { ReportSendFailure } from '@/app/reports/send'
+
+import ReportDialog from './ReportDialog.vue'
+
+type Args = {
+ kind: 'error' | 'problem'
+ note: string
+ hasDocument: boolean
+ preparingDocument: boolean
+ documentFailed: boolean
+ canSend: boolean
+ sending: boolean
+ failure: ReportSendFailure | null
+ onSend: () => void
+}
+
+const errorPreview = JSON.stringify(
+ {
+ kind: 'error',
+ exceptions: [
+ {
+ type: 'TypeError',
+ value: 'nodes.map is not a function',
+ mechanism: { handled: false, synthetic: false, type: 'window' },
+ stacktrace: {
+ type: 'raw',
+ frames: [
+ {
+ platform: 'web:javascript',
+ filename: 'tauri://localhost/assets/index-a1b2c3d4.js',
+ function: 'Le',
+ lineno: 1,
+ colno: 52114,
+ in_app: true
+ }
+ ]
+ }
+ }
+ ],
+ version: '0.17.0',
+ platform: 'macos',
+ arch: 'arm64',
+ app: 'desktop',
+ browser: 'unknown'
+ },
+ null,
+ 2
+)
+
+const meta = {
+ title: 'App/Reports/Dialog',
+ tags: ['autodocs'],
+ args: {
+ kind: 'error',
+ note: '',
+ hasDocument: true,
+ preparingDocument: false,
+ documentFailed: false,
+ canSend: true,
+ sending: false,
+ failure: null,
+ onSend: fn()
+ },
+ render: (args) => ({
+ components: { ReportDialog },
+ setup: () => ({
+ args,
+ note: ref(args.note),
+ email: ref(''),
+ includeActivity: ref(true),
+ attachDocument: ref(false),
+ preview: errorPreview
+ }),
+ template: `
+ <div class="h-170">
+ <ReportDialog
+ :open="true"
+ v-model:note="note"
+ v-model:email="email"
+ v-model:include-activity="includeActivity"
+ v-model:attach-document="attachDocument"
+ :kind="args.kind"
+ :has-document="args.hasDocument"
+ :preparing-document="args.preparingDocument"
+ :document-failed="args.documentFailed"
+ :preview="preview"
+ :can-send="args.canSend"
+ :sending="args.sending"
+ :failure="args.failure"
+ @send="args.onSend"
+ />
+ </div>`
+ })
+} satisfies Meta<Args>
+
+export default meta
+type Story = StoryObj<typeof meta>
+
+export const Error: Story = {}
+export const Problem: Story = {
+ args: { kind: 'problem', note: 'Text jumps when I resize the frame.' }
+}
+export const ProblemWithoutDescription: Story = {
+ args: { kind: 'problem', canSend: false },
+ play: async ({ canvasElement }) => {
+ // The dialog renders in a portal on the document body.
+ await waitFor(() =>
+ expect(
+ canvasElement.ownerDocument.querySelector('[data-test-id="report-send"]')
+ ).toBeDisabled()
+ )
+ }
+}
+export const Sending: Story = { args: { sending: true } }
+export const ReportFailed: Story = { args: { failure: 'report' } }
+export const UploadFailed: Story = { args: { failure: 'files' } }
+export const DocumentFailed: Story = { args: { documentFailed: true } }
diff --git a/src/components/reports/ReportDialog.vue b/src/components/reports/ReportDialog.vue
new file mode 100644
index 000000000..69bcf8cda
--- /dev/null
+++ b/src/components/reports/ReportDialog.vue
@@ -0,0 +1,134 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { computed, useId } from 'vue'
+
+import { useI18n } from '@open-pencil/vue/i18n'
+
+import type { ReportSendFailure } from '@/app/reports/send'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'
+import {
+ AppDialogBody,
+ AppDialogFooter,
+ AppDialogHeader,
+ AppDialogRoot
+} from '@/components/ui/dialog'
+import AppAlert from '@/components/ui/feedback/AppAlert.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import AppTextarea from '@/components/ui/input/AppTextarea.vue'
+import AppCheckboxCard from '@/components/ui/toggle/AppCheckboxCard.vue'
+import reportsTheme from '@/theme/reports'
+
+const {
+ kind,
+ emailInvalid = false,
+ hasDocument = false,
+ preparingDocument = false,
+ documentFailed = false,
+ preview,
+ canSend,
+ sending = false,
+ failure = null
+} = defineProps<{
+ kind: 'error' | 'problem'
+ emailInvalid?: boolean
+ /** Whether the active tab holds a document to attach. */
+ hasDocument?: boolean
+ preparingDocument?: boolean
+ documentFailed?: boolean
+ /** The exact body that would be sent. */
+ preview: string
+ canSend: boolean
+ sending?: boolean
+ failure?: ReportSendFailure | null
+}>()
+
+const emit = defineEmits<{ send: [] }>()
+
+const open = defineModel<boolean>('open', { default: false })
+const note = defineModel<string>('note', { default: '' })
+const email = defineModel<string>('email', { default: '' })
+const includeActivity = defineModel<boolean>('includeActivity', { default: true })
+const attachDocument = defineModel<boolean>('attachDocument', { default: false })
+
+const { common, diagnostics: messages } = useI18n()
+const ui = tv(reportsTheme)()
+const id = useId()
+
+const heading = computed(() =>
+ kind === 'error' ? messages.value.reportErrorTitle : messages.value.reportProblemTitle
+)
+const description = computed(() =>
+ kind === 'error' ? messages.value.reportErrorDescription : messages.value.reportProblemDescription
+)
+</script>
+
+<template>
+ <AppDialogRoot v-model:open="open" size="md" data-test-id="report-dialog">
+ <AppDialogHeader :heading="heading" :description="description" />
+ <form novalidate class="flex min-h-0 flex-1 flex-col" @submit.prevent="emit('send')">
+ <AppDialogBody :ui="{ body: ui.body() }">
+ <div :class="ui.field()">
+ <label :for="`${id}-note`" :class="ui.label()">
+ {{ kind === 'error' ? messages.reportNoteError : messages.reportNoteProblem }}
+ </label>
+ <AppTextarea
+ :id="`${id}-note`"
+ v-model="note"
+ :rows="4"
+ :placeholder="messages.reportNotePlaceholder"
+ data-test-id="report-note"
+ />
+ </div>
+ <div :class="ui.field()">
+ <label :for="`${id}-email`" :class="ui.label()">{{ messages.reportEmail }}</label>
+ <AppInput
+ :id="`${id}-email`"
+ v-model="email"
+ type="email"
+ size="md"
+ :state="emailInvalid ? 'invalid' : 'idle'"
+ :aria-invalid="emailInvalid"
+ :aria-describedby="`${id}-email-hint`"
+ autocomplete="email"
+ />
+ <p :id="`${id}-email-hint`" :class="ui.hint()">{{ messages.reportEmailHint }}</p>
+ </div>
+ <AppCheckboxCard
+ v-model="includeActivity"
+ :label="messages.reportActivity"
+ :description="messages.reportActivityDescription"
+ />
+ <AppCheckboxCard
+ v-if="hasDocument"
+ v-model="attachDocument"
+ :label="messages.reportDocument"
+ :description="messages.reportDocumentDescription"
+ />
+ <AppCollapsible :label="messages.reportPreview">
+ <pre :class="ui.preview()" data-test-id="report-preview">{{ preview }}</pre>
+ </AppCollapsible>
+ <AppAlert v-if="documentFailed" tone="error" :heading="messages.reportDocumentFailed" />
+ <AppAlert
+ v-if="failure"
+ tone="error"
+ :heading="failure === 'files' ? messages.reportFilesFailed : messages.reportFailed"
+ />
+ </AppDialogBody>
+ <AppDialogFooter>
+ <AppButton type="button" size="md" @click="open = false">{{ common.cancel }}</AppButton>
+ <AppButton
+ type="submit"
+ size="md"
+ color="primary"
+ variant="solid"
+ :loading="sending"
+ :disabled="!canSend || preparingDocument"
+ data-test-id="report-send"
+ >
+ {{ messages.reportSend }}
+ </AppButton>
+ </AppDialogFooter>
+ </form>
+ </AppDialogRoot>
+</template>
diff --git a/src/components/reports/ReportDialogHost.vue b/src/components/reports/ReportDialogHost.vue
new file mode 100644
index 000000000..6aef2653d
--- /dev/null
+++ b/src/components/reports/ReportDialogHost.vue
@@ -0,0 +1,44 @@
+<script setup lang="ts">
+import { useReportDialog } from '@/app/reports/dialog'
+import { reportDialogOpen } from '@/app/reports/state'
+
+import ReportDialog from './ReportDialog.vue'
+
+/** The report dialog, driven by the report the app has open. */
+const {
+ kind,
+ note,
+ email,
+ emailInvalid,
+ includeActivity,
+ attachDocument,
+ hasDocument,
+ preparingDocument,
+ documentFailed,
+ report,
+ preview,
+ sending,
+ failure,
+ send
+} = useReportDialog()
+</script>
+
+<template>
+ <ReportDialog
+ v-model:open="reportDialogOpen"
+ v-model:note="note"
+ v-model:email="email"
+ v-model:include-activity="includeActivity"
+ v-model:attach-document="attachDocument"
+ :kind="kind"
+ :email-invalid="emailInvalid"
+ :has-document="hasDocument"
+ :preparing-document="preparingDocument"
+ :document-failed="documentFailed"
+ :preview="preview"
+ :can-send="report !== null"
+ :sending="sending"
+ :failure="failure"
+ @send="send"
+ />
+</template>
diff --git a/src/components/shell/AppToaster.vue b/src/components/shell/AppToaster.vue
index 3a76aee50..c0039595d 100644
--- a/src/components/shell/AppToaster.vue
+++ b/src/components/shell/AppToaster.vue
@@ -26,7 +26,7 @@ const { common, settings } = useI18n()
:copied-label="common.copiedExclamation"
:close-label="common.close"
@close="toast.remove(t.id)"
- @action="t.action?.run()"
+ @action="t.action?.run(t.id)"
/>
<ToastViewport
:label="`${settings.notifications} (F8)`"
diff --git a/src/theme/reports.ts b/src/theme/reports.ts
new file mode 100644
index 000000000..fc305d62c
--- /dev/null
+++ b/src/theme/reports.ts
@@ -0,0 +1,11 @@
+/** The report dialog: its fields, and the body it shows before sending. */
+export default {
+ slots: {
+ body: 'flex flex-col gap-3',
+ field: 'flex flex-col gap-1.5',
+ label: 'text-2xs font-medium text-muted',
+ hint: 'text-2xs text-muted',
+ preview:
+ 'scrollbar-thin max-h-64 overflow-auto rounded-md border border-border bg-input p-2 font-mono text-3xs whitespace-pre-wrap text-surface'
+ }
+} as const
diff --git a/tests/app/diagnostics/events/runtime.test.ts b/tests/app/diagnostics/events/runtime.test.ts
index e5d04efec..7f9040d29 100644
--- a/tests/app/diagnostics/events/runtime.test.ts
+++ b/tests/app/diagnostics/events/runtime.test.ts
@@ -3,6 +3,8 @@ import { beforeEach, expect, test } from 'bun:test'
import { diagnostics } from '@/app/diagnostics'
import { recordRuntimeError } from '@/app/diagnostics/events/runtime'
+import { recoverySessionId } from '@/app/document/recovery/session'
+import { APP_VERSION } from '@/app/runtime/version'
beforeEach(async () => {
await diagnostics.clear()
@@ -21,7 +23,9 @@ test('records an uncaught error with its details', async () => {
source: 'vue',
errorName: 'TypeError',
message: 'Attempting to define property on object that is not extensible.',
- info: 'render function'
+ info: 'render function',
+ appSession: recoverySessionId,
+ appVersion: APP_VERSION
}
})
expect(event.attributes.stack).toContain('TypeError')
diff --git a/tests/app/document/recovery/session.test.ts b/tests/app/document/recovery/session.test.ts
index 3efedc615..a8b79f94d 100644
--- a/tests/app/document/recovery/session.test.ts
+++ b/tests/app/document/recovery/session.test.ts
@@ -3,10 +3,12 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import {
endRecoverySession,
recoverySessionId,
+ recoverySessionStates,
sessionStates,
startRecoverySession
} from '@/app/document/recovery/session'
import {
+ markSessionStarted,
setSessionRegistryForTests,
startedSessionIds
} from '@/app/document/recovery/session/storage'
@@ -62,4 +64,20 @@ describe('recovery sessions', () => {
endRecoverySession()
expect(startedSessionIds()).toEqual([])
})
+
+ test('a window that closes while the locks are read is not a crash', async () => {
+ markSessionStarted('crashed', true)
+ markSessionStarted('closing', true)
+ const locks = {
+ query: async () => {
+ // The closing window leaves the registry, then lets its lock go, before the answer.
+ markSessionStarted('closing', false)
+ return { held: [], pending: [] }
+ },
+ request: (() => Promise.resolve()) as LockManager['request']
+ }
+ const { crashed } = await recoverySessionStates(locks)
+ expect([...crashed]).toEqual(['crashed'])
+ markSessionStarted('crashed', false)
+ })
})
diff --git a/tests/app/reports/build.test.ts b/tests/app/reports/build.test.ts
new file mode 100644
index 000000000..8b9ecf9c1
--- /dev/null
+++ b/tests/app/reports/build.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, expect, test } from 'bun:test'
+
+import { REPORT_BODY_MAX_BYTES, type Build } from '@open-pencil/feedback/contract'
+
+import type { DiagnosticEvent } from '@/app/diagnostics'
+import { buildReport, type ReportDraft } from '@/app/reports/build'
+import { reportExceptions } from '@/app/reports/exception'
+
+const BUILD: Build = {
+ version: '0.17.0',
+ platform: 'macos',
+ arch: 'arm64',
+ app: 'desktop',
+ browser: 'unknown'
+}
+const RELEASE = '01a19e69-fdef-0000-e554-4733f3a5a77c'
+
+const draft = (overrides: Partial<ReportDraft> = {}): ReportDraft => ({
+ exceptions: null,
+ note: '',
+ email: '',
+ activity: null,
+ attachments: [],
+ ...overrides
+})
+
+afterEach(() => {
+ Reflect.deleteProperty(globalThis, '_posthogReleaseId')
+})
+
+test('a problem needs a description', () => {
+ expect(buildReport(draft({ note: ' ' }), { build: BUILD, installId: null })).toBeNull()
+ expect(
+ buildReport(draft({ note: 'Text jumps on resize' }), { build: BUILD, installId: null })
+ ).toMatchObject({ kind: 'problem', note: 'Text jumps on resize', ...BUILD })
+})
+
+test('an error carries the release its chunks were built in', () => {
+ Reflect.set(globalThis, '_posthogReleaseId', RELEASE)
+ const exceptions = reportExceptions(new TypeError('failed'), 'window')
+
+ expect(buildReport(draft({ exceptions }), { build: BUILD, installId: null })).toMatchObject({
+ kind: 'error',
+ release: RELEASE,
+ exceptions
+ })
+})
+
+test('the install ID goes along only when the context has one', () => {
+ const installId = '0123456789abcdef0123456789abcdef'
+ const report = buildReport(draft({ note: 'Broken' }), { build: BUILD, installId })
+ expect(report?.installId).toBe(installId)
+ expect(
+ buildReport(draft({ note: 'Broken' }), { build: BUILD, installId: null })?.installId
+ ).toBeUndefined()
+})
+
+test('attachments are declared by name and size', () => {
+ const bytes = new Uint8Array([1, 2, 3])
+ const report = buildReport(
+ draft({ note: 'Broken', attachments: [{ name: 'document.fig', bytes }] }),
+ { build: BUILD, installId: null }
+ )
+ expect(report?.files).toEqual([{ name: 'document.fig', size: 3 }])
+})
+
+test('an invalid email keeps the report from being sent', () => {
+ expect(
+ buildReport(draft({ note: 'Broken', email: 'not an address' }), {
+ build: BUILD,
+ installId: null
+ })
+ ).toBeNull()
+})
+
+test('the oldest steps are left out to keep the body within the service’s limit', () => {
+ const attributes = Object.fromEntries(
+ Array.from({ length: 24 }, (_, index) => [`field${index}`, 'x'.repeat(4000)])
+ )
+ const activity = Array.from({ length: 50 }, (_, index): DiagnosticEvent => ({
+ id: `event-${index}`,
+ timestamp: Date.UTC(2026, 10, 3, 9, 0, 50 - index),
+ category: 'document',
+ level: 'info',
+ name: 'document.saved',
+ attributes
+ }))
+ const report = buildReport(draft({ note: 'Broken', activity }), { build: BUILD, installId: null })
+ const steps = report?.steps ?? []
+
+ expect(new TextEncoder().encode(JSON.stringify(report)).byteLength).toBeLessThanOrEqual(
+ REPORT_BODY_MAX_BYTES
+ )
+ expect(steps.length).toBeGreaterThan(0)
+ expect(steps.length).toBeLessThan(50)
+ expect(steps.at(-1)?.timestamp).toBe(new Date(Date.UTC(2026, 10, 3, 9, 0, 50)).toISOString())
+})
diff --git a/tests/app/reports/crash.test.ts b/tests/app/reports/crash.test.ts
new file mode 100644
index 000000000..4a2f1e118
--- /dev/null
+++ b/tests/app/reports/crash.test.ts
@@ -0,0 +1,68 @@
+import { expect, test } from 'bun:test'
+
+import type { DiagnosticEvent } from '@/app/diagnostics'
+import { crashErrors, panicExceptions, storedErrorExceptions } from '@/app/reports/crash'
+import { APP_VERSION } from '@/app/runtime/version'
+
+function runtimeError(
+ session: string,
+ timestamp: number,
+ overrides: Partial<DiagnosticEvent['attributes']> = {}
+): DiagnosticEvent {
+ return {
+ id: `${session}-${timestamp}`,
+ timestamp,
+ category: 'runtime',
+ level: 'error',
+ name: 'runtime.error',
+ attributes: {
+ source: 'window',
+ errorName: 'TypeError',
+ errorCode: null,
+ message: `failed at ${timestamp}`,
+ stack: `TypeError: failed\n at Le (tauri://localhost/assets/index-a1.js:1:${timestamp})`,
+ info: null,
+ appSession: session,
+ appVersion: APP_VERSION,
+ ...overrides
+ }
+ }
+}
+
+test('the crashed sessions’ errors come most recent first', () => {
+ const events = [
+ runtimeError('crashed', 10),
+ runtimeError('crashed', 30),
+ runtimeError('closed', 40),
+ runtimeError('crashed', 50, { appVersion: '0.1.0' }),
+ { ...runtimeError('crashed', 60), name: 'chat.failed' }
+ ]
+
+ const errors = crashErrors(events, new Set(['crashed']))
+ expect(errors.map((error) => error.at)).toEqual([30, 10])
+})
+
+test('a stored error becomes an exception with its frames again', () => {
+ const [error] = crashErrors([runtimeError('crashed', 20)], new Set(['crashed']))
+ const [exception] = storedErrorExceptions(error)
+
+ expect(exception.type).toBe('TypeError')
+ expect(exception.mechanism.type).toBe('window')
+ expect(exception.stacktrace?.frames.at(-1)).toMatchObject({
+ filename: 'tauri://localhost/assets/index-a1.js',
+ colno: 20
+ })
+})
+
+test('a panic is reported with where it happened, without the home folder', () => {
+ const [exception] = panicExceptions({
+ message: 'called `Option::unwrap()` on a `None` value',
+ location: '/Users/jane/.cargo/registry/src/tauri-2.0.0/src/app.rs:12:5',
+ version: APP_VERSION
+ })
+
+ expect(exception.type).toBe('panic')
+ expect(exception.mechanism.type).toBe('panic')
+ expect(exception.value).toContain('app.rs:12:5')
+ expect(exception.value).not.toContain('jane')
+})
diff --git a/tests/app/reports/exception.test.ts b/tests/app/reports/exception.test.ts
new file mode 100644
index 000000000..56c1956ab
--- /dev/null
+++ b/tests/app/reports/exception.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { isOwnError, reportExceptions } from '@/app/reports/exception'
+
+const CHUNK = '849ab7be-6ab8-5c38-8851-ee4992cad3e5'
+
+afterEach(() => {
+ Reflect.deleteProperty(globalThis, '_posthogChunkIds')
+})
+
+describe('reportExceptions', () => {
+ test('describes an uncaught error with its frames', () => {
+ const [exception] = reportExceptions(new TypeError('nodes.map is not a function'), 'window')
+
+ expect(exception.type).toBe('TypeError')
+ expect(exception.value).toBe('nodes.map is not a function')
+ expect(exception.mechanism).toEqual({ handled: false, synthetic: false, type: 'window' })
+ expect(exception.stacktrace?.frames.length).toBeGreaterThan(0)
+ for (const frame of exception.stacktrace?.frames ?? []) {
+ expect(frame.platform).toBe('web:javascript')
+ }
+ })
+
+ test('points frames at the chunk the release build injected an ID into', () => {
+ // A chunk registers the stack of an error made at its own top level, as the injected snippet does.
+ Reflect.set(globalThis, '_posthogChunkIds', { [new Error('chunk').stack ?? '']: CHUNK })
+
+ const [exception] = reportExceptions(new Error('failed'), 'vue')
+ expect(exception.stacktrace?.frames.some((frame) => frame.chunk_id === CHUNK)).toBe(true)
+ })
+
+ test('scrubs credentials and home folders from messages', () => {
+ const [exception] = reportExceptions(
+ new Error('Could not read /Users/jane/Designs/app.fig with api_key=abc123secret'),
+ 'rejection'
+ )
+ expect(exception.value).not.toContain('jane')
+ expect(exception.value).not.toContain('abc123secret')
+ })
+
+ test('keeps no message from a chain where any error may quote prompts', () => {
+ const error = new Error('The model refused: "Draw my secret project"')
+ error.name = 'AI_APICallError'
+ const exceptions = reportExceptions(new Error('Reply failed', { cause: error }), 'rejection')
+ const quoting = reportExceptions(error, 'rejection')
+
+ expect(exceptions.length).toBe(2)
+ expect(exceptions.every((exception) => exception.value === undefined)).toBe(true)
+ expect(quoting.every((exception) => exception.value === undefined)).toBe(true)
+ })
+
+ test('follows the cause chain', () => {
+ const exceptions = reportExceptions(
+ new Error('Could not open the file', {
+ cause: new RangeError('Offset is outside the bounds')
+ }),
+ 'window'
+ )
+ expect(exceptions.map((exception) => exception.type).toSorted()).toEqual([
+ 'Error',
+ 'RangeError'
+ ])
+ })
+})
+
+describe('isOwnError', () => {
+ const exceptions = reportExceptions(new Error('failed'), 'window')
+ const filename = exceptions[0].stacktrace?.frames.at(-1)?.filename ?? ''
+
+ test('accepts an error with a frame from the app’s origin', () => {
+ const own = exceptions.map((exception) => ({
+ ...exception,
+ stacktrace: {
+ type: 'raw' as const,
+ frames: [{ platform: 'web:javascript' as const, filename: 'tauri://localhost/assets/a.js' }]
+ }
+ }))
+ expect(isOwnError(own, 'tauri://localhost')).toBe(true)
+ })
+
+ test('refuses an error thrown elsewhere, such as by an extension', () => {
+ expect(filename).not.toStartWith('chrome-extension://')
+ expect(isOwnError(exceptions, 'chrome-extension://abcdef')).toBe(false)
+ })
+})
diff --git a/tests/app/reports/send.test.ts b/tests/app/reports/send.test.ts
new file mode 100644
index 000000000..3d0719b84
--- /dev/null
+++ b/tests/app/reports/send.test.ts
@@ -0,0 +1,91 @@
+import { expect, test } from 'bun:test'
+
+import { createFeedbackClient } from '@open-pencil/feedback/client'
+import type { Report } from '@open-pencil/feedback/contract'
+
+import { sendReport } from '@/app/reports/send'
+
+const REPORT: Report = {
+ kind: 'problem',
+ version: '0.17.0',
+ platform: 'macos',
+ arch: 'arm64',
+ app: 'desktop',
+ browser: 'unknown',
+ note: 'Text jumps on resize',
+ files: [{ name: 'document.fig', size: 3 }]
+}
+const REPORT_ID = '6f1c1f9e-7b8a-4c7d-9e3f-2a1b0c9d8e7f'
+const FILE = { name: 'document.fig' as const, bytes: new Uint8Array([1, 2, 3]) }
+
+interface Sent {
+ method: string
+ path: string
+ authorization: string | null
+ body: Uint8Array
+}
+
+/** A client whose requests the test answers, recording what each carried. */
+function fakeService(answer: (request: Request) => Response) {
+ const sent: Sent[] = []
+ const client = createFeedbackClient({
+ origin: 'https://feedback.test',
+ fetch: async (input: RequestInfo | URL, init?: RequestInit) => {
+ const request = new Request(input, init)
+ sent.push({
+ method: request.method,
+ path: new URL(request.url).pathname,
+ authorization: request.headers.get('authorization'),
+ body: new Uint8Array(await request.clone().arrayBuffer())
+ })
+ return answer(request)
+ }
+ })
+ return { client, sent }
+}
+
+const receipt = (uploadToken: string | null) =>
+ Response.json({ reportId: REPORT_ID, uploadToken }, { status: 201 })
+
+test('sends the report, then each file with its upload token', async () => {
+ const { client, sent } = fakeService((request) =>
+ request.method === 'POST' ? receipt('token') : new Response(null, { status: 204 })
+ )
+
+ expect(await sendReport(REPORT, [FILE], { client })).toEqual({ ok: true, reportId: REPORT_ID })
+ expect(sent.map(({ method, path }) => `${method} ${path}`)).toEqual([
+ 'POST /reports',
+ `PUT /reports/${REPORT_ID}/files/document.fig`
+ ])
+ expect(sent[1].authorization).toBe('Bearer token')
+ expect([...sent[1].body]).toEqual([1, 2, 3])
+})
+
+test('a refused report sends no files', async () => {
+ const { client, sent } = fakeService(() => new Response(null, { status: 502 }))
+
+ expect(await sendReport(REPORT, [FILE], { client })).toEqual({ ok: false, failure: 'report' })
+ expect(sent).toHaveLength(1)
+})
+
+test('a failed upload keeps the receipt, and sending with it uploads only the files', async () => {
+ let uploads = 0
+ const { client, sent } = fakeService((request) => {
+ if (request.method === 'POST') return receipt('token')
+ uploads++
+ return new Response(null, { status: uploads === 1 ? 503 : 204 })
+ })
+
+ const first = await sendReport(REPORT, [FILE], { client })
+ expect(first).toEqual({
+ ok: false,
+ failure: 'files',
+ receipt: { reportId: REPORT_ID, uploadToken: 'token' }
+ })
+ const delivered = first.ok || first.failure !== 'files' ? null : first.receipt
+ expect(await sendReport(REPORT, [FILE], { client, delivered })).toEqual({
+ ok: true,
+ reportId: REPORT_ID
+ })
+ expect(sent.map(({ method }) => method)).toEqual(['POST', 'PUT', 'PUT'])
+})
diff --git a/tests/app/reports/steps.test.ts b/tests/app/reports/steps.test.ts
new file mode 100644
index 000000000..980176ae3
--- /dev/null
+++ b/tests/app/reports/steps.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from 'bun:test'
+
+import type { DiagnosticEvent } from '@/app/diagnostics'
+import { reportSteps } from '@/app/reports/steps'
+
+function event(index: number, attributes: DiagnosticEvent['attributes'] = {}): DiagnosticEvent {
+ return {
+ id: `event-${index}`,
+ timestamp: Date.UTC(2026, 10, 3, 9, 0, index),
+ category: 'document',
+ level: 'error',
+ name: 'document.operation.failed',
+ attributes
+ }
+}
+
+test('steps run oldest first and keep only the most recent events', () => {
+ const recentFirst = Array.from({ length: 80 }, (_, index) => event(80 - index))
+ const steps = reportSteps(recentFirst)
+
+ expect(steps).toHaveLength(50)
+ expect(steps[0].timestamp).toBe(new Date(Date.UTC(2026, 10, 3, 9, 0, 31)).toISOString())
+ expect(steps.at(-1)?.timestamp).toBe(new Date(Date.UTC(2026, 10, 3, 9, 0, 80)).toISOString())
+})
+
+test('steps keep attributes the service accepts and bound long text', () => {
+ const [step] = reportSteps([
+ event(1, { operation: 'open', 'not a key': 'dropped', stack: 'x'.repeat(5000), ok: false })
+ ])
+
+ expect(Object.keys(step.attributes)).toEqual(['operation', 'stack', 'ok'])
+ expect(String(step.attributes.stack)).toHaveLength(4000)
+})
+
+test('events under names the service would refuse are left out', () => {
+ expect(reportSteps([{ ...event(1), name: 'Legacy Event' }])).toEqual([])
+})
diff --git a/tests/engine/app/shell/menu/schema.test.ts b/tests/engine/app/shell/menu/schema.test.ts
index 9db2dbdf7..f7fd18a34 100644
--- a/tests/engine/app/shell/menu/schema.test.ts
+++ b/tests/engine/app/shell/menu/schema.test.ts
@@ -51,6 +51,7 @@ describe('APP_MENU_SCHEMA', () => {
expect(shellEntries.map((entry) => ('type' in entry ? '' : entry.id))).toEqual([
'open-tour',
'diagnostics',
+ 'report-problem',
'settings',
'view-design-issues',
'theme-light',
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index 927494526..83ebcf9ef 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -37,6 +37,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
- Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports use `dist`. Release preparation must preserve resolution maps. Prepared publish directories receive the root `LICENSE` when a package has none of its own, and every package needs a `README.md` because npm renders it. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks; never publish package directories manually. `test:packages` first runs the packaging guards in `tools/checks/package-quality/src/smoke/guards.ts`: fixture manifests packed with the real `npm pack` that must trip the tarball inspector and the Node/Bun consumer checks before those checks vouch for real packages.
- Pre-releases are only `vX.Y.Z-beta.N`: they publish to npm's `next` dist-tag, draft as a GitHub pre-release that is never latest, install on Windows as MSI `X.Y.Z.N`, and skip the app and docs deploys (`tools/release/release-packages/src/version.ts`).
- A beta's changelog section opens with the pre-release note and lists changes since the previous beta. The final `X.Y.Z` replaces its beta sections with one section written against the previous stable release, opened by a short highlights paragraph, with fixes to new features folded into their bullets; the GitHub pre-releases keep the beta notes (`CHANGELOG.md`).
+- Official builds (`VITE_OPENPENCIL_FEEDBACK=on`) emit hidden source maps; `app.yml` and the `build.yml` frontend job inject PostHog chunk IDs, upload the maps to PostHog error tracking as release `openpencil@<version>`, and strip them from `dist`, and `build.yml` attaches them as `OpenPencil_<version>_sourcemaps.tar.gz`. Both need the `POSTHOG_CLI_API_KEY` secret, a personal key with error tracking write and organization read (`tools/release/release-packages/src/sourcemaps/publish.ts`).
- Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title, body, and artifacts, then publish. Release titles are exactly the tag (`vX.Y.Z`) without a product-name prefix.
- Homebrew's `openpencil` cask is managed upstream: BrewTestBot proposes bumps and Homebrew merges them. Check the upstream cask PR after publication; do not push to the archived custom tap or add bump automation. Users install the app with `brew install --cask openpencil` and the CLI through npm or Bun.
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index e5709e10d..590c9a3af 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -599,9 +599,21 @@ ja:ai.notificationsAllowHint
ja:ai.notificationsSystemHint
ja:ai.notifyReplyFinished
ja:ai.notifyReplyFailed
+ja:diagnostics.reportCrashed
+ja:diagnostics.reportDocumentDescription
+ja:diagnostics.reportErrorDescription
+ja:diagnostics.reportPanic
+ja:diagnostics.reportProblemDescription
+ja:diagnostics.reportUnexpectedError
zh-cn:ai.skillsDescription
zh-cn:ai.notificationsHint
zh-cn:ai.notificationsAllowHint
zh-cn:ai.notificationsSystemHint
zh-cn:ai.notifyReplyFinished
zh-cn:ai.notifyReplyFailed
+zh-cn:diagnostics.reportCrashed
+zh-cn:diagnostics.reportDocumentDescription
+zh-cn:diagnostics.reportErrorDescription
+zh-cn:diagnostics.reportPanic
+zh-cn:diagnostics.reportProblemDescription
+zh-cn:diagnostics.reportUnexpectedError
diff --git a/tools/release/release-packages/package.json b/tools/release/release-packages/package.json
index c7b386515..21388ee00 100644
--- a/tools/release/release-packages/package.json
+++ b/tools/release/release-packages/package.json
@@ -16,6 +16,7 @@
"dependencies": {
"@open-pencil/package-artifacts-tools": "workspace:*",
"@open-pencil/package-quality-tools": "workspace:*",
+ "@posthog/cli": "0.18.12",
"@sigstore/bundle": "^5.0.0",
"citty": "^0.1.6",
"es-toolkit": "^1.52.0",
diff --git a/tools/release/release-packages/src/native/assemble.ts b/tools/release/release-packages/src/native/assemble.ts
index 7b81dd7a7..3fc4ccca7 100644
--- a/tools/release/release-packages/src/native/assemble.ts
+++ b/tools/release/release-packages/src/native/assemble.ts
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { readReleaseNotes } from '#release/release-notes'
+import { sourceMapsAssetName } from '#release/sourcemaps/bundle'
import { isEqual } from 'es-toolkit'
import { decode, toUint8Array } from 'js-base64'
import * as v from 'valibot'
@@ -90,6 +91,10 @@ try {
await rm(temporary, { recursive: true, force: true })
}
+// The frontend job archived the source maps PostHog symbolicates error reports with.
+const sourceMaps = sourceMapsAssetName(version)
+await copyFile(join(paths.root, sourceMaps), join(output, sourceMaps))
+
const pubDate = new Date().toISOString()
await writeFile(
join(output, 'latest.json'),
diff --git a/tools/release/release-packages/src/sourcemaps/bundle.ts b/tools/release/release-packages/src/sourcemaps/bundle.ts
new file mode 100644
index 000000000..fdec1f681
--- /dev/null
+++ b/tools/release/release-packages/src/sourcemaps/bundle.ts
@@ -0,0 +1,38 @@
+import { readdir, readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+
+/** The PostHog release every OpenPencil build's chunks are associated with, by version. */
+export const POSTHOG_RELEASE_NAME = 'openpencil'
+
+/** The release asset holding a version's source maps, beside its installers. */
+export function sourceMapsAssetName(version: string): string {
+ return `OpenPencil_${version}_sourcemaps.tar.gz`
+}
+
+/** Every `.map` file under `dist`, as paths relative to it, sorted. */
+export async function listSourceMaps(dist: string): Promise<string[]> {
+ const entries = await readdir(dist, { recursive: true, withFileTypes: true })
+ return entries
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.map'))
+ .map((entry) => join(entry.parentPath, entry.name).slice(dist.length + 1))
+ .sort()
+}
+
+const CHUNK_ID_COMMENT = /\n\/\/# chunkId=\S+\s*$/
+const SOURCE_MAPPING_URL = /\/\/# sourceMappingURL=/
+
+/**
+ * Checks that every chunk with a map carries the chunk ID PostHog matches stack frames by, and no
+ * `sourceMappingURL`: the maps leave the build, so a browser must never be told to fetch them.
+ */
+export async function assertInjectedChunks(dist: string, maps: string[]): Promise<void> {
+ if (maps.length === 0) {
+ throw new Error(`No source maps in ${dist}; release builds need VITE_OPENPENCIL_FEEDBACK=on`)
+ }
+ for (const map of maps) {
+ const chunk = map.slice(0, -'.map'.length)
+ const code = await readFile(join(dist, chunk), 'utf8')
+ if (SOURCE_MAPPING_URL.test(code)) throw new Error(`${chunk} links its source map`)
+ if (!CHUNK_ID_COMMENT.test(code)) throw new Error(`${chunk} has no PostHog chunk ID`)
+ }
+}
diff --git a/tools/release/release-packages/src/sourcemaps/publish.ts b/tools/release/release-packages/src/sourcemaps/publish.ts
new file mode 100644
index 000000000..7ba2e7e3c
--- /dev/null
+++ b/tools/release/release-packages/src/sourcemaps/publish.ts
@@ -0,0 +1,87 @@
+#!/usr/bin/env bun
+
+import { rm } from 'node:fs/promises'
+import { join } from 'node:path'
+
+import { defineCommand, runMain } from 'citty'
+import * as v from 'valibot'
+
+import {
+ readPackageManifest,
+ resolveWorkspaceRoot,
+ runCommand
+} from '@open-pencil/package-artifacts-tools'
+
+import {
+ assertInjectedChunks,
+ listSourceMaps,
+ POSTHOG_RELEASE_NAME,
+ sourceMapsAssetName
+} from './bundle.ts'
+
+const POSTHOG_TIMEOUT_MS = 10 * 60_000
+const ARCHIVE_TIMEOUT_MS = 5 * 60_000
+
+const credentialsSchema = v.object({
+ POSTHOG_CLI_API_KEY: v.pipe(v.string(), v.minLength(1)),
+ POSTHOG_CLI_PROJECT_ID: v.pipe(v.string(), v.regex(/^\d+$/))
+})
+
+/** The pinned CLI's launcher, which fetches its binary on first run; Bun skips install scripts. */
+const posthogCLI = Bun.resolveSync('@posthog/cli/run-posthog-cli.js', import.meta.dir)
+
+/**
+ * Prepares a release build's `dist` for error reports: injects the chunk IDs and release that
+ * PostHog symbolicates stack frames by, uploads the source maps, optionally archives them as the
+ * release asset, and removes them so neither the web deploy nor the desktop bundle ships them.
+ */
+export async function publishSourceMaps(root: string, options: { archive: boolean }) {
+ v.parse(credentialsSchema, process.env)
+ const { version } = await readPackageManifest(join(root, 'package.json'))
+ const dist = join(root, 'dist')
+ const release = ['--release-name', POSTHOG_RELEASE_NAME, '--release-version', version]
+
+ async function posthog(...args: string[]) {
+ await runCommand({
+ command: process.execPath,
+ args: [posthogCLI, ...args],
+ cwd: root,
+ output: 'inherit',
+ timeoutMs: POSTHOG_TIMEOUT_MS
+ })
+ }
+
+ await posthog('sourcemap', 'inject', '--directory', dist, ...release)
+ const maps = await listSourceMaps(dist)
+ await assertInjectedChunks(dist, maps)
+ await posthog('sourcemap', 'upload', '--directory', dist, ...release)
+
+ if (options.archive) {
+ await runCommand({
+ command: 'tar',
+ args: ['-czf', join(root, sourceMapsAssetName(version)), '-C', dist, ...maps],
+ cwd: root,
+ timeoutMs: ARCHIVE_TIMEOUT_MS
+ })
+ }
+ await Promise.all(maps.map((map) => rm(join(dist, map))))
+ if ((await listSourceMaps(dist)).length > 0) throw new Error('Source maps left in dist')
+ console.log(`Uploaded ${maps.length} source maps for ${POSTHOG_RELEASE_NAME}@${version}`)
+}
+
+if (import.meta.main) {
+ await runMain(
+ defineCommand({
+ meta: { name: 'sourcemaps', description: 'Upload a release build’s source maps to PostHog' },
+ args: {
+ root: { type: 'string', description: 'Explicit workspace root' },
+ archive: { type: 'boolean', description: 'Also archive the maps as the release asset' }
+ },
+ async run({ args }) {
+ await publishSourceMaps(await resolveWorkspaceRoot(process.cwd(), args.root), {
+ archive: args.archive
+ })
+ }
+ })
+ )
+}
diff --git a/tools/release/release-packages/tests/sourcemaps/bundle.test.ts b/tools/release/release-packages/tests/sourcemaps/bundle.test.ts
new file mode 100644
index 000000000..c945e7234
--- /dev/null
+++ b/tools/release/release-packages/tests/sourcemaps/bundle.test.ts
@@ -0,0 +1,72 @@
+import { expect, test } from 'bun:test'
+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { classifyAsset } from '#docs-config/theme/landing/download/releases'
+import {
+ assertInjectedChunks,
+ listSourceMaps,
+ sourceMapsAssetName
+} from '#release/sourcemaps/bundle'
+
+const CHUNK_ID = '\n//# chunkId=849ab7be-6ab8-5c38-8851-ee4992cad3e5\n'
+
+async function withDist(files: Record<string, string>, run: (dist: string) => Promise<void>) {
+ const dist = await mkdtemp(join(tmpdir(), 'release-sourcemaps-'))
+ try {
+ for (const [name, content] of Object.entries(files)) {
+ await mkdir(join(dist, name, '..'), { recursive: true })
+ await writeFile(join(dist, name), content)
+ }
+ await run(dist)
+ } finally {
+ await rm(dist, { recursive: true, force: true })
+ }
+}
+
+test('source maps are listed relative to dist, nested ones included', async () => {
+ await withDist(
+ {
+ 'assets/index-a1.js': 'x',
+ 'assets/index-a1.js.map': '{}',
+ 'assets/workers/render-b2.js.map': '{}',
+ 'index.html': ''
+ },
+ async (dist) => {
+ expect(await listSourceMaps(dist)).toEqual([
+ 'assets/index-a1.js.map',
+ 'assets/workers/render-b2.js.map'
+ ])
+ }
+ )
+})
+
+test('an injected chunk without a source map link passes', async () => {
+ await withDist({ 'assets/a.js': `run()${CHUNK_ID}`, 'assets/a.js.map': '{}' }, async (dist) => {
+ await assertInjectedChunks(dist, await listSourceMaps(dist))
+ })
+})
+
+test.each([
+ ['no maps', {}, /No source maps/],
+ ['no chunk ID', { 'a.js': 'run()', 'a.js.map': '{}' }, /no PostHog chunk ID/],
+ [
+ 'a linked map',
+ { 'a.js': `run()\n//# sourceMappingURL=a.js.map${CHUNK_ID}`, 'a.js.map': '{}' },
+ /links its source map/
+ ]
+])('a build with %s is refused', async (_scenario, files, message) => {
+ await withDist(files, async (dist) => {
+ const error: unknown = await assertInjectedChunks(dist, await listSourceMaps(dist)).catch(
+ (caught: unknown) => caught
+ )
+ expect(error).toBeInstanceOf(Error)
+ expect(String(error)).toMatch(message)
+ })
+})
+
+test('the download page does not offer the source maps archive', () => {
+ const name = sourceMapsAssetName('0.17.0')
+ expect(classifyAsset({ name, url: `https://example.com/${name}`, size: 1 })).toBeNull()
+})
diff --git a/vite.config.ts b/vite.config.ts
index 17e410ad8..8e7242ebd 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -91,6 +91,9 @@ export default defineConfig(async ({ command, mode }) => {
// Syntax is lowered to the supported browser baseline; APIs are not polyfilled.
target: viteBuildTarget(),
chunkSizeWarningLimit: 2500,
+ // Official releases upload their maps to PostHog for error reports, then remove them
+ // (`tools/release/release-packages/src/sourcemaps/publish.ts`); no chunk links one.
+ sourcemap: !metrics && env.VITE_OPENPENCIL_FEEDBACK === 'on' ? 'hidden' : false,
outDir: metrics ? 'dist-metrics/admin' : cloudSite ? 'dist-cloud' : 'dist',
rolldownOptions: {
// The desktop Software Update window is its own page; a Cloud server adds its own
diff --git a/vite/pwa.ts b/vite/pwa.ts
index 4fd879b5c..98c02fbab 100644
--- a/vite/pwa.ts
+++ b/vite/pwa.ts
@@ -19,6 +19,9 @@ export function openPencilPwaPlugin() {
devOptions: { enabled: false },
workbox: {
maximumFileSizeToCacheInBytes: 12 * 1024 * 1024,
+ // Workbox follows `build.sourcemap` and would link a map the release then removes; the
+ // service worker's errors never reach error reports anyway.
+ sourcemap: false,
globPatterns: ['**/*.{js,css,html,wasm,png,svg,ico,ttf,webmanifest}'],
navigateFallback: '/index.html',
navigateFallbackDenylist: NOT_EDITOR_PAGES