Skip to content

armgit / boop

Public Imported from GitHub
0

A tiny, self-hosted notification inbox for developers. Something happened in one of your apps; Boop tells you on your phone.

HTML

feat: v1.2.0 — grouping, actions, copy for agent, read-only MCP

Chris Gregori17bc8ce3152f
diff --git a/.env.example b/.env.example
index 0af8096..fc80b6c 100644
--- a/.env.example
+++ b/.env.example
@@ -9,6 +9,10 @@ BOOP_LOG_LEVEL=info
BOOP_ADMIN_USER=chris
BOOP_ADMIN_PASSWORD=change-me-please
+# Bearer token for the read-only MCP endpoint (/mcp) that AI agents connect to.
+# 16+ characters; leave blank to allow only device credentials / admin login.
+BOOP_MCP_TOKEN=
+
# Apple Push Notifications. Leave blank until you have created an APNs key;
# Boop runs without them, but pushes are skipped.
APNS_TEAM_ID=
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..51f298b
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,41 @@
+# Changelog
+
+All notable changes to Boop are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [Semantic Versioning](https://semver.org/). The server, web UI and iOS app share one version number.
+
+## [Unreleased]
+
+## [1.2.0] — 2026-08-29
+
+### Added
+- **Grouping by fingerprint.** `GET /api/v1/events?grouped=true` collapses events that share a `fingerprint` within a project into their latest occurrence, annotated with `group: {count, first_seen, last_seen}`. The web inbox and the iOS app show one row per fingerprint (`KeyError ×47 · First seen 09:31 · Last seen 10:42`) with a **Group repeats** toggle; opening a grouped row lists the occurrences (web: `/groups/:project/:fingerprint`; iOS: a pushed screen). Filters apply inside a group; fingerprints never merge across projects.
+- **Actions on events.** `POST /api/v1/events` accepts `actions: [{label, url}]` (up to 3; label ≤ 40 chars; absolute URL, `javascript:`/`data:`/`file:` refused). Actions render as buttons in the web and iOS event detail and as buttons on the push notification. New `BoopNotificationService` extension target in the iOS project registers the buttons per notification; tapping one opens its URL.
+- **Copy for an agent (iOS).** The share button on an event is now a menu: **Copy** (plain text), **Copy as Markdown** (sectioned: exception, environment, stack trace, context, breadcrumbs, data, links) and **Share**.
+- **MCP endpoint (read-only).** `/mcp` speaks the Model Context Protocol over Streamable HTTP using the official Go SDK. Tools: `list_projects`, `list_events`, `search_events`, `get_event`, `get_event_group`. Auth: `BOOP_MCP_TOKEN` bearer, a device credential, or the admin login; project keys are refused. **Settings → MCP** switch (`mcp_enabled`) turns the endpoint off.
+- `GET /api/v1/events` filters: `fingerprint`, `since`, `until` (RFC 3339, on `created_at`).
+- `BOOP_MCP_TOKEN` configuration variable (16+ characters).
+- `GET /api/v1/settings` reports `mcp_enabled` and `mcp_token_set`.
+
+### Changed
+- Projects page: each project is a compact row with its settings button inline.
+- Inbox: level chips share one width and titles/bodies truncate before the level column.
+- Database migration `0003_actions_groups`: adds `events.actions_json` and an index on `(project_id, fingerprint, created_at)`. Applied automatically on start.
+- iOS: the project file is regenerated from `project.yml` and now contains the notification service extension; its bundle id must be `<app bundle id>.NotificationService`.
+
+## [1.1.0] — 2026-08-28
+
+### Added
+- **Silences.** Rules that stop matching events (by fingerprint, title or source, per project or global) from being pushed while still storing them. Create from an event's page or **Settings → Silences**; filter the inbox to silenced events; unsilence and push on demand. `GET/POST/DELETE /api/v1/silences`, `POST /api/v1/events/:id/unsilence`, `silenced` filter on `GET /api/v1/events`.
+- README: integrations section covering `boop_ex`, `boop_error_tracker` and `@boop/node`.
+
+## [1.0.0] — 2026-08-23
+
+### Added
+- Go server with SQLite storage, embedded Svelte web UI, direct APNs delivery (ES256 token auth), project API keys, device pairing by QR, redaction of sensitive keys, admin login (`BOOP_ADMIN_USER`/`BOOP_ADMIN_PASSWORD`), setup wizard and test notifications.
+- Event retention managed from Settings and persisted; `BOOP_RETENTION_DAYS` overrides it on every start when set.
+- iOS app (SwiftUI, iOS 26): inbox with filters and cursor pagination, rich event detail (exception, stacktrace, tags, context, breadcrumbs, raw JSON), notification tap-through, Keychain-stored device credential.
+- Docker image, compose file and a Dokploy-specific compose file; architecture diagram (`docs/architecture`); `integration-llms.md` client spec.
+
+[Unreleased]: https://github.com/chrisgreg/boop/compare/v1.2.0...HEAD
+[1.2.0]: https://github.com/chrisgreg/boop/compare/v1.1.0...v1.2.0
+[1.1.0]: https://github.com/chrisgreg/boop/compare/v1.0.0...v1.1.0
+[1.0.0]: https://github.com/chrisgreg/boop/releases/tag/v1.0.0
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 70756eb..ec0bfe8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,12 +1,12 @@
# Contributing
-Boop is intentionally small. Before adding a feature, check the non-goals in `prd.md`; anything that needs another infrastructure service is unlikely to be accepted.
+Boop is intentionally small: one Go binary, one SQLite file, direct APNs. Anything that needs another infrastructure service (a queue, a hosted relay, an external database) is unlikely to be accepted.
## Layout
- `server/` — Go server. `cmd/boop` is the entry point; `internal/` holds one package per concern (api, apns, auth, config, database, delivery, devices, events, pairing, projects, settings, web). `migrations/` holds SQL applied in filename order.
- `server/web/` — Svelte + Vite frontend. `npm run build` writes into `server/internal/web/dist`, which `go:embed` picks up.
-- `Design System/` — the design tokens and reference components the UI follows.
+- `ios/` — the SwiftUI app; `project.yml` generates `Boop.xcodeproj` with XcodeGen. Web colours and type live as CSS variables in `server/web/src/app.css`; the iOS equivalents are in `ios/Boop/Design/DS.swift`.
## Working locally
@@ -32,3 +32,7 @@ Go tests spin up the real HTTP handler against a temporary SQLite file. Add a te
- Log with `slog` and dotted event names (`event.created`, `push.failed`). Never log keys, credentials, or full payloads.
- Sentence case in the UI, no exclamation marks, no emoji in copy.
- Use the design tokens (`--up-*`) rather than hard-coded colours.
+
+## Changelog
+
+Add a line under **Unreleased** in [CHANGELOG.md](CHANGELOG.md) for anything a user would notice: new endpoints or fields, UI changes, configuration, migrations. Bump the version in `server/internal/api/api.go`, `server/Dockerfile` and `ios/project.yml` (then `xcodegen generate`) when cutting a release, and tag it `vX.Y.Z`.
diff --git a/README.md b/README.md
index 56e3483..f9f08e4 100644
--- a/README.md
+++ b/README.md
@@ -36,7 +36,7 @@ Your apps POST events with a project API key. The Go server redacts and stores t
| --- | --- |
| Go server (API, SQLite, APNs, embedded web UI) | `server/` |
| Web UI (Svelte, built into the binary) | `server/web/` |
-| iOS app (SwiftUI, iOS 26, you build and sign it) | `ios/` — see [ios/README.md](ios/README.md) |
+| iOS app (SwiftUI, iOS 26, you build and sign it) + notification service extension | `ios/` — see [ios/README.md](ios/README.md) |
| Client libraries | separate repos — see [Integrations](#integrations) |
| Native desktop client | planned |
@@ -81,6 +81,22 @@ curl http://localhost:8080/api/v1/events \
Levels: `info`, `success`, `warning`, `error`, `critical`. Anything in `data` is kept as-is (recognised sections such as `exception`, `stacktrace`, `tags`, `context` and `breadcrumbs` get a nicer rendering) after sensitive keys are redacted.
+**Actions.** Up to three buttons that open a URL — on the notification itself (long-press or pull down) and in the event detail:
+
+```bash
+curl http://localhost:8080/api/v1/events \
+ -H "Authorization: Bearer boop_proj_..." -H "Content-Type: application/json" \
+ -d '{"title": "Payment received", "body": "£19.99", "level": "success",
+ "actions": [{"label": "Open in Stripe", "url": "https://dashboard.stripe.com/payments/pi_1"},
+ {"label": "Open order", "url": "myshop://orders/42"}]}'
+```
+
+Labels are 40 characters or fewer; URLs must be absolute (`https://…` or an app scheme). Tapping the notification body still opens the event in Boop.
+
+**Grouping.** Send the same `fingerprint` for the same problem and the inbox (web and phone) shows one row per fingerprint — `KeyError ×47 · First seen 09:31 · Last seen 10:42` — that opens the individual occurrences. Toggle it with "Group repeats". `GET /api/v1/events?grouped=true` is the API behind it. Grouping only affects display; every occurrence is stored and pushed (use a [silence](#silences) to stop pushes).
+
+**Copy for an agent.** On the phone, the share button on an event offers *Copy*, *Copy as Markdown* and *Share*. The Markdown version lays the event out as sections — exception, environment, stack trace, context, breadcrumbs, data, links — ready to paste into Claude, ChatGPT or whatever you use. *Share* hands it straight to the assistant's app without the clipboard.
+
From a shell script:
```bash
@@ -165,7 +181,7 @@ All endpoints are under `/api/v1`. Errors are JSON: `{"error": "code", "message"
| --- | --- | --- | --- |
| GET | `/health` | none | `{"status":"ok"}` |
| POST | `/api/v1/events` | project key | Create event, returns `{id, created_at}` |
-| GET | `/api/v1/events?project=&level=&source=&silenced=&before=&limit=` | device or none | List, newest first; `next_cursor` feeds `before`; `silenced=true\|false` filters |
+| GET | `/api/v1/events?project=&level=&source=&fingerprint=&since=&until=&silenced=&grouped=&before=&limit=` | device or none | List, newest first; `next_cursor` feeds `before`; `silenced=true\|false` filters; `grouped=true` collapses repeated fingerprints into one row with `group: {count, first_seen, last_seen}` |
| GET | `/api/v1/events/:id` | device or none | Full event |
| GET | `/api/v1/events/:id/deliveries` | device or none | Push attempts for an event |
| GET/POST | `/api/v1/projects` | admin | List / create (returns `api_key` once) |
@@ -178,17 +194,34 @@ All endpoints are under `/api/v1`. Errors are JSON: `{"error": "code", "message"
| PATCH/DELETE | `/api/v1/devices/:id` | device (self) or admin | Update / remove |
| GET | `/api/v1/devices` | admin | List paired devices |
| GET | `/api/v1/status` | admin | Health, APNs state, counts, last push |
-| GET/PATCH | `/api/v1/settings` | admin | `retention_days`, `redact_keys`, `setup_completed` |
+| GET/PATCH | `/api/v1/settings` | admin | `retention_days`, `redact_keys`, `setup_completed`, `mcp_enabled` (read-only `mcp_token_set` says whether `BOOP_MCP_TOKEN` is configured) |
| GET/POST | `/api/v1/silences` | admin | Rules that stop matching events from being pushed: `{field: fingerprint\|title\|source, value, project_id?, note?}` |
| GET | `/api/v1/silences/:id` | admin | One rule |
| DELETE | `/api/v1/silences/:id` | admin | Remove a rule (already-silenced events keep their flag) |
| POST | `/api/v1/events/:id/unsilence` | admin | Clear the flag and push the event now |
| POST | `/api/v1/test` | admin | Create a test event and push it |
+| POST | `/mcp` | MCP token, device, or admin | Read-only [MCP](#mcp-for-ai-agents) endpoint (Streamable HTTP); `404 mcp_disabled` when switched off in Settings |
+
+Event fields on `POST /api/v1/events`: `title` (required), `body`, `level`, `source`, `type`, `external_id`, `fingerprint`, `occurred_at`, `data`, `actions` — see [`integration-llms.md`](integration-llms.md) for limits.
Credentials: project keys (`boop_proj_...`) can only create events; device credentials (`boop_dev_...`) can only read events and manage their own device. Only SHA-256 hashes are stored.
**Admin auth.** Set `BOOP_ADMIN_USER` and `BOOP_ADMIN_PASSWORD` and the web UI shows a sign-in screen; admin endpoints then need the session cookie it sets (`POST /api/v1/auth/login`) or HTTP Basic credentials (`curl -u user:pass …`). Sessions last 30 days and live in memory, so a restart signs everyone out. Leave both unset and everything is open — only do that behind your own proxy, Tailscale, or VPN. Either way, project and device credentials are refused on admin endpoints, so a leaked client secret never grants admin rights.
+## MCP (for AI agents)
+
+Boop speaks the [Model Context Protocol](https://modelcontextprotocol.io) at `/mcp` (Streamable HTTP), read-only. Point the agent you already use at it and ask things like *"what errors happened overnight?"*, *"show me critical events from Infra"*, *"what started failing after 14:00?"* or *"get the full context for the latest KeyError"*. There is no LLM inside Boop; it just serves structured context.
+
+Tools: `list_projects`, `list_events` (filters, time window, `grouped`), `search_events`, `get_event` (full payload), `get_event_group` (every occurrence of a fingerprint).
+
+Set `BOOP_MCP_TOKEN` (16+ characters) and use it as a bearer token. A device credential works too, and so does the admin login; with admin auth off and no token the endpoint is open, like the rest of the read API. Project keys are refused. **Settings → MCP** has a switch that turns the endpoint off entirely.
+
+```bash
+claude mcp add --transport http boop https://boop.example.com/mcp --header "Authorization: Bearer $BOOP_MCP_TOKEN"
+```
+
+Any client that supports Streamable HTTP with a custom header can connect the same way.
+
## Configuration
| Variable | Default | Notes |
@@ -200,6 +233,7 @@ Credentials: project keys (`boop_proj_...`) can only create events; device crede
| `BOOP_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` |
| `BOOP_ADMIN_USER` | | Web UI / admin API username; set together with the password |
| `BOOP_ADMIN_PASSWORD` | | 8+ characters. Unset = no login |
+| `BOOP_MCP_TOKEN` | | Bearer token for the read-only [MCP endpoint](#mcp-for-ai-agents); 16+ characters |
| `APNS_TEAM_ID` | | Apple Developer team id |
| `APNS_KEY_ID` | | Id of the APNs auth key |
| `APNS_BUNDLE_ID` | | Bundle id of your Boop iOS build |
@@ -244,6 +278,10 @@ The app posts the token to `/api/v1/pairing/exchange`, stores the returned devic
Some events you want stored but not on your phone: a known flaky job, a noisy warning. On any event's page click **Silence events like this** and pick what to match — its fingerprint, its title, or its source — for that project or every project. Matching events still arrive in the inbox (marked *silenced*) and in the iOS app, but no push is sent. Filter the inbox to **Silenced only** to review them; a silenced event's page shows the rule that caught it with **Remove rule** and **Unsilence and push now**. Manage all rules under **Settings → Silences**. Fingerprint and source match exactly; title ignores case.
+## Grouping and actions
+
+Events that share a `fingerprint` within a project are shown as one row (`KeyError ×47 · First seen 09:31 · Last seen 10:42`) in the web inbox and on the phone; open it for the individual occurrences, or untick **Group repeats** to see every row. Events can also carry up to three `actions` (`{label, url}`) that appear as buttons on the push notification and in the event detail — open the deploy, the Stripe payment, the error in your tracker. See [Send an event](#send-an-event).
+
## Redaction
Values under these keys are replaced with `[REDACTED]` anywhere in `data` before storage: `password`, `password_confirmation`, `secret`, `token`, `access_token`, `refresh_token`, `api_key`, `authorization`, `cookie`, `set-cookie`, `private_key`. Matching is case-insensitive and treats `-` and `_` alike. Add your own keys in Settings.
@@ -259,6 +297,10 @@ make build # bin/boop w
Requires Go 1.27 and Node 24 (see `.tool-versions`). The SQLite driver is pure Go, so `CGO_ENABLED=0` builds work everywhere.
+## Changelog
+
+See [CHANGELOG.md](CHANGELOG.md). Releases are tagged `vX.Y.Z`; the server, web UI and iOS app share the version.
+
## Licence
MIT.
diff --git a/integration-llms.md b/integration-llms.md
index d76f070..6cbced5 100644
--- a/integration-llms.md
+++ b/integration-llms.md
@@ -40,9 +40,10 @@ Send a JSON object. Only `title` is required.
| `source` | string | Optional, ≤ 200. What produced the event: `"cron"`, `"error_tracker"`, `"github_actions"`, your library's name. Used for filtering. |
| `type` | string | Optional, ≤ 200. A category within the source, e.g. `"error"`, `"deploy"`. |
| `external_id` | string | Optional, ≤ 200. Your own id for the event (for cross-referencing). Not used for deduplication. |
-| `fingerprint` | string | Optional, ≤ 200. A stable grouping key for "the same thing happening again". Stored and indexed; not used for deduplication in v1. |
+| `fingerprint` | string | Optional, ≤ 200. A stable grouping key for "the same thing happening again". The inbox collapses events sharing a fingerprint into one row with a count and first/last seen, and silence rules can match on it. Every occurrence is still stored and pushed; it is not deduplication. |
| `occurred_at` | string | Optional RFC 3339 timestamp (`2026-08-28T12:51:44Z`). Defaults to receipt time. |
| `data` | object | Optional free-form JSON object, ≤ 256 KB. Anything you like; unknown keys are preserved verbatim. Arrays at the top level are rejected — it must be an object. |
+| `actions` | array | Optional, at most 3 of `{"label": string, "url": string}`. Buttons on the notification and in the event detail that open the URL. Label 1–40 characters; URL absolute with a scheme (`https://…` or an app scheme like `myapp://…`; `javascript:`, `data:`, `file:` are rejected). A client should expose this as a simple list, e.g. `actions: [{label: "Open deploy", url: run_url}]`. |
### `data` conventions the UI renders specially
diff --git a/ios/Boop.xcodeproj/project.pbxproj b/ios/Boop.xcodeproj/project.pbxproj
index 913efd0..2ac41b0 100644
--- a/ios/Boop.xcodeproj/project.pbxproj
+++ b/ios/Boop.xcodeproj/project.pbxproj
@@ -25,25 +25,42 @@
4B9FC07E7380A1D0D1780C87 /* Figtree-Bold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = AC2789EE28600895E168A3DE /* Figtree-Bold.ttf */; };
51C449052FF42A30B7B69DF2 /* DS.swift in Sources */ = {isa = PBXBuildFile; fileRef = 642012CF305FC80DD79E1EE9 /* DS.swift */; };
5B96FF0FC9128CBF085B34F3 /* Components.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58DD3023423348952188CABE /* Components.swift */; };
+ 5CF2392A2F8839F4BE2AA73A /* EventAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BB2856E6C1D288CFF4C6C50 /* EventAction.swift */; };
5FE88931427EC015D8FB7FED /* PairingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = ABDD09C39E086828C3B7F7B8 /* PairingView.swift */; };
60BB7FF986BB5AD43C26827F /* KeychainStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9D5F31603EA140B870E759A /* KeychainStore.swift */; };
6BD0F44D0081D1C112A35286 /* Level.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DC224EA686BB5FE8B77B253 /* Level.swift */; };
76ECCCF1BB162E57F2D9A9A4 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 762667ADB3E12735F13061EE /* RootView.swift */; };
+ 78C37125D8D4A518824B1D6A /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = D01935F3CE94F56DCBA5D9F8 /* NotificationService.swift */; };
7D38875E1C25CF5F210CE31E /* JSONTreeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A6DFD4F3DE0BE4C3C517172 /* JSONTreeView.swift */; };
8A478E244646BC70067B23D0 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0727DAA2D68B5283AA8FF472 /* AppDelegate.swift */; };
+ 91A16E0E8F24CFE7DF9B7E43 /* NotificationActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0789EA53290C184D9E003D27 /* NotificationActions.swift */; };
+ 954342F259F3CC534FCD5266 /* BoopNotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 7F4162435984712AF1C11ABA /* BoopNotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
A56E6785C64B08EDBD2EA85B /* Figtree-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = CBFB36C2F43E768891C23AF6 /* Figtree-Regular.ttf */; };
+ A64F7BAFF134E3C2DCA93B82 /* NotificationActionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28B4DE5F8303B626E92C21A2 /* NotificationActionsTests.swift */; };
+ AB9C00965FCA0B89D77C4B6B /* EventMarkdownTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B5E5922218E13C67A9F91BE /* EventMarkdownTests.swift */; };
+ B3783D763567AA39715B9A2C /* NotificationActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0789EA53290C184D9E003D27 /* NotificationActions.swift */; };
B77F82FCC3B2DE3D93F03FC3 /* PairingPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7CB15AD497B172787C42AAC /* PairingPayload.swift */; };
B9BD74FB187CA5C560B897A8 /* APIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 117AE79DD532EB1BA1963F37 /* APIClient.swift */; };
+ C0307974F77B38C42BFC1F4B /* GroupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 796F84D4D1DA4921AD64F5DB /* GroupView.swift */; };
+ C7D0640A5F71A18A0B3BDE18 /* EventAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BB2856E6C1D288CFF4C6C50 /* EventAction.swift */; };
C8EF442E2029DFA06AF9EACD /* EventTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79BB01E3425BF57186501B5B /* EventTests.swift */; };
CB5FE8B95AE1C857776CCAFF /* PairingPayloadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C744AEF422D9779F59D6D9B /* PairingPayloadTests.swift */; };
CCB52AD25863617AEF10B183 /* BoopApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28C1391E032AE6F632E3CF80 /* BoopApp.swift */; };
D4A8AF3E6AEB42BEC66E3A4D /* JSONValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C780959D77481AA196BF961 /* JSONValue.swift */; };
+ D6A2467551FF8A0C65A63B96 /* EventMarkdown.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF31DD5C9E15C54024975A49 /* EventMarkdown.swift */; };
DCEEBEADFA8C0BC736BFD319 /* Formatting.swift in Sources */ = {isa = PBXBuildFile; fileRef = 88B0894F62AB1E64E25A027E /* Formatting.swift */; };
F6A184D98CA3DF0C48990DA0 /* ProjectIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = C17EDE92A930BB8F749FF023 /* ProjectIcon.swift */; };
FAB9084713A2A313274E6A65 /* Figtree-Medium.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 3186689D326577B56F291E27 /* Figtree-Medium.ttf */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
+ 2B4F22AEA0B3AC6E026E54D9 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = D75B1A06897BCC5F7CE8A239 /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = FE559C429519CF6E4219B404;
+ remoteInfo = BoopNotificationService;
+ };
AA1C1E6C95462B31838C8FA7 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = D75B1A06897BCC5F7CE8A239 /* Project object */;
@@ -60,17 +77,35 @@
};
/* End PBXContainerItemProxy section */
+/* Begin PBXCopyFilesBuildPhase section */
+ 5EABD3B77F28B7B632D0F4EA /* Embed Foundation Extensions */ = {
+ isa = PBXCopyFilesBuildPhase;
+ buildActionMask = 2147483647;
+ dstPath = "";
+ dstSubfolderSpec = 13;
+ files = (
+ 954342F259F3CC534FCD5266 /* BoopNotificationService.appex in Embed Foundation Extensions */,
+ );
+ name = "Embed Foundation Extensions";
+ runOnlyForDeploymentPostprocessing = 0;
+ };
+/* End PBXCopyFilesBuildPhase section */
+
/* Begin PBXFileReference section */
0129157CD73EBECB84F69C22 /* FormattingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FormattingTests.swift; sourceTree = "<group>"; };
0727DAA2D68B5283AA8FF472 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
+ 0789EA53290C184D9E003D27 /* NotificationActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationActions.swift; sourceTree = "<group>"; };
0A125D20CA61763DBACF3EF2 /* EventDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventDetailView.swift; sourceTree = "<group>"; };
0A743627697D04F4516567DD /* OFL.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = OFL.txt; sourceTree = "<group>"; };
0DC224EA686BB5FE8B77B253 /* Level.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Level.swift; sourceTree = "<group>"; };
117AE79DD532EB1BA1963F37 /* APIClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIClient.swift; sourceTree = "<group>"; };
21A9F07E87F33B74A2C52C05 /* Boop.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Boop.app; sourceTree = BUILT_PRODUCTS_DIR; };
24071F31542EBB6E9AF56D3B /* QRScannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QRScannerView.swift; sourceTree = "<group>"; };
+ 28B4DE5F8303B626E92C21A2 /* NotificationActionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationActionsTests.swift; sourceTree = "<group>"; };
28C1391E032AE6F632E3CF80 /* BoopApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoopApp.swift; sourceTree = "<group>"; };
3186689D326577B56F291E27 /* Figtree-Medium.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "Figtree-Medium.ttf"; sourceTree = "<group>"; };
+ 3A4A99E1519FCA5523A1A85A /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
+ 4B5E5922218E13C67A9F91BE /* EventMarkdownTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventMarkdownTests.swift; sourceTree = "<group>"; };
58DD3023423348952188CABE /* Components.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Components.swift; sourceTree = "<group>"; };
5A790977C54183FCA8A2CF4E /* Figtree-SemiBold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "Figtree-SemiBold.ttf"; sourceTree = "<group>"; };
609791CD0E38060E89CCBFF6 /* NotificationTapUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationTapUITests.swift; sourceTree = "<group>"; };
@@ -78,8 +113,11 @@
75122E3FEFADBFE389DB9C21 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
762667ADB3E12735F13061EE /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = "<group>"; };
78F17F7F004605058FFA2618 /* ScreenshotUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScreenshotUITests.swift; sourceTree = "<group>"; };
+ 796F84D4D1DA4921AD64F5DB /* GroupView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupView.swift; sourceTree = "<group>"; };
79BB01E3425BF57186501B5B /* EventTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventTests.swift; sourceTree = "<group>"; };
+ 7BB2856E6C1D288CFF4C6C50 /* EventAction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventAction.swift; sourceTree = "<group>"; };
7C744AEF422D9779F59D6D9B /* PairingPayloadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingPayloadTests.swift; sourceTree = "<group>"; };
+ 7F4162435984712AF1C11ABA /* BoopNotificationService.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = BoopNotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; };
8063BF0B2841D7A9E8DA3624 /* InboxView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InboxView.swift; sourceTree = "<group>"; };
88B0894F62AB1E64E25A027E /* Formatting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Formatting.swift; sourceTree = "<group>"; };
8A6DFD4F3DE0BE4C3C517172 /* JSONTreeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONTreeView.swift; sourceTree = "<group>"; };
@@ -95,10 +133,12 @@
C17EDE92A930BB8F749FF023 /* ProjectIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectIcon.swift; sourceTree = "<group>"; };
C9D5F31603EA140B870E759A /* KeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainStore.swift; sourceTree = "<group>"; };
CBFB36C2F43E768891C23AF6 /* Figtree-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = "Figtree-Regular.ttf"; sourceTree = "<group>"; };
+ D01935F3CE94F56DCBA5D9F8 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };
DECFDC77D38E3DB104B3B6E6 /* PairingFlowUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PairingFlowUITests.swift; sourceTree = "<group>"; };
DF7CEEF38A16624007E14E93 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };
E19A870C0CFD9BA00298449D /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
E554071AD342FB99DF3BA5D0 /* Event.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Event.swift; sourceTree = "<group>"; };
+ EF31DD5C9E15C54024975A49 /* EventMarkdown.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventMarkdown.swift; sourceTree = "<group>"; };
F49CA3B7C9B215A290E252AF /* BoopUITests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = BoopUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
F5F4E385D82C57FCAE48CDDC /* APIClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIClientTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
@@ -116,6 +156,7 @@
isa = PBXGroup;
children = (
21A9F07E87F33B74A2C52C05 /* Boop.app */,
+ 7F4162435984712AF1C11ABA /* BoopNotificationService.appex */,
9EF3C782D6E451C365D85AE5 /* BoopTests.xctest */,
F49CA3B7C9B215A290E252AF /* BoopUITests.xctest */,
);
@@ -145,8 +186,10 @@
isa = PBXGroup;
children = (
F5F4E385D82C57FCAE48CDDC /* APIClientTests.swift */,
+ 4B5E5922218E13C67A9F91BE /* EventMarkdownTests.swift */,
79BB01E3425BF57186501B5B /* EventTests.swift */,
0129157CD73EBECB84F69C22 /* FormattingTests.swift */,
+ 28B4DE5F8303B626E92C21A2 /* NotificationActionsTests.swift */,
7C744AEF422D9779F59D6D9B /* PairingPayloadTests.swift */,
);
path = BoopTests;
@@ -155,6 +198,7 @@
370EF1C7641E9E8489B97A6C /* Notifications */ = {
isa = PBXGroup;
children = (
+ 0789EA53290C184D9E003D27 /* NotificationActions.swift */,
B66C8112F0031F188AD85583 /* PushManager.swift */,
);
path = Notifications;
@@ -192,6 +236,7 @@
isa = PBXGroup;
children = (
0A125D20CA61763DBACF3EF2 /* EventDetailView.swift */,
+ 796F84D4D1DA4921AD64F5DB /* GroupView.swift */,
8063BF0B2841D7A9E8DA3624 /* InboxView.swift */,
ABDD09C39E086828C3B7F7B8 /* PairingView.swift */,
762667ADB3E12735F13061EE /* RootView.swift */,
@@ -204,12 +249,22 @@
isa = PBXGroup;
children = (
2EBC1B59859E4A07AF4B257A /* Boop */,
+ 9F134A8A9C55760CDE7B0028 /* BoopNotificationService */,
3069089B1315C8F05F333E33 /* BoopTests */,
D910B7B1AE503AB1CA23FB95 /* BoopUITests */,
1176C791D5E10B4FEE7029DD /* Products */,
);
sourceTree = "<group>";
};
+ 9F134A8A9C55760CDE7B0028 /* BoopNotificationService */ = {
+ isa = PBXGroup;
+ children = (
+ 3A4A99E1519FCA5523A1A85A /* Info.plist */,
+ D01935F3CE94F56DCBA5D9F8 /* NotificationService.swift */,
+ );
+ path = BoopNotificationService;
+ sourceTree = "<group>";
+ };
B1A3B1EAC582757D46F99295 /* Networking */ = {
isa = PBXGroup;
children = (
@@ -244,6 +299,8 @@
children = (
ACD0500F93373A2432EC73D8 /* Device.swift */,
E554071AD342FB99DF3BA5D0 /* Event.swift */,
+ 7BB2856E6C1D288CFF4C6C50 /* EventAction.swift */,
+ EF31DD5C9E15C54024975A49 /* EventMarkdown.swift */,
8C780959D77481AA196BF961 /* JSONValue.swift */,
0DC224EA686BB5FE8B77B253 /* Level.swift */,
);
@@ -307,10 +364,12 @@
buildPhases = (
CA78EF33ADFE16A279159C50 /* Sources */,
70545B44BD6C495CCF4CE230 /* Resources */,
+ 5EABD3B77F28B7B632D0F4EA /* Embed Foundation Extensions */,
);
buildRules = (
);
dependencies = (
+ 03321C7861D2717B9C7F1DA8 /* PBXTargetDependency */,
);
name = Boop;
packageProductDependencies = (
@@ -319,6 +378,23 @@
productReference = 21A9F07E87F33B74A2C52C05 /* Boop.app */;
productType = "com.apple.product-type.application";
};
+ FE559C429519CF6E4219B404 /* BoopNotificationService */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = 54B5E2FCEF08F002E537997D /* Build configuration list for PBXNativeTarget "BoopNotificationService" */;
+ buildPhases = (
+ 17A474132356EA060963F57F /* Sources */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = BoopNotificationService;
+ packageProductDependencies = (
+ );
+ productName = BoopNotificationService;
+ productReference = 7F4162435984712AF1C11ABA /* BoopNotificationService.appex */;
+ productType = "com.apple.product-type.app-extension";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -341,6 +417,10 @@
DevelopmentTeam = "";
ProvisioningStyle = Automatic;
};
+ FE559C429519CF6E4219B404 = {
+ DevelopmentTeam = "";
+ ProvisioningStyle = Automatic;
+ };
};
};
buildConfigurationList = D2C7A418F16CBD03DB918192 /* Build configuration list for PBXProject "Boop" */;
@@ -358,6 +438,7 @@
projectRoot = "";
targets = (
A8738A21A24E7E622C597C1C /* Boop */,
+ FE559C429519CF6E4219B404 /* BoopNotificationService */,
133AB7E3837B87BD56434B0E /* BoopTests */,
0F7CC37BAA4A164C74F66E10 /* BoopUITests */,
);
@@ -380,6 +461,16 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
+ 17A474132356EA060963F57F /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ 5CF2392A2F8839F4BE2AA73A /* EventAction.swift in Sources */,
+ 91A16E0E8F24CFE7DF9B7E43 /* NotificationActions.swift in Sources */,
+ 78C37125D8D4A518824B1D6A /* NotificationService.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
79A1CB032A5A8142B061F121 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
@@ -395,8 +486,10 @@
buildActionMask = 2147483647;
files = (
0A5E700A1862667E236E6005 /* APIClientTests.swift in Sources */,
+ AB9C00965FCA0B89D77C4B6B /* EventMarkdownTests.swift in Sources */,
C8EF442E2029DFA06AF9EACD /* EventTests.swift in Sources */,
1454903D0DB084517DAA7359 /* FormattingTests.swift in Sources */,
+ A64F7BAFF134E3C2DCA93B82 /* NotificationActionsTests.swift in Sources */,
CB5FE8B95AE1C857776CCAFF /* PairingPayloadTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -413,13 +506,17 @@
51C449052FF42A30B7B69DF2 /* DS.swift in Sources */,
40DAF9AD8EE9227AB85A4161 /* Device.swift in Sources */,
05C3BF86490C9B9181AD8426 /* Event.swift in Sources */,
+ C7D0640A5F71A18A0B3BDE18 /* EventAction.swift in Sources */,
021583DF5827CD9A311ABA73 /* EventDetailView.swift in Sources */,
+ D6A2467551FF8A0C65A63B96 /* EventMarkdown.swift in Sources */,
DCEEBEADFA8C0BC736BFD319 /* Formatting.swift in Sources */,
+ C0307974F77B38C42BFC1F4B /* GroupView.swift in Sources */,
0CE510E367D7351D023FB764 /* InboxView.swift in Sources */,
7D38875E1C25CF5F210CE31E /* JSONTreeView.swift in Sources */,
D4A8AF3E6AEB42BEC66E3A4D /* JSONValue.swift in Sources */,
60BB7FF986BB5AD43C26827F /* KeychainStore.swift in Sources */,
6BD0F44D0081D1C112A35286 /* Level.swift in Sources */,
+ B3783D763567AA39715B9A2C /* NotificationActions.swift in Sources */,
B77F82FCC3B2DE3D93F03FC3 /* PairingPayload.swift in Sources */,
5FE88931427EC015D8FB7FED /* PairingView.swift in Sources */,
F6A184D98CA3DF0C48990DA0 /* ProjectIcon.swift in Sources */,
@@ -433,6 +530,11 @@
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
+ 03321C7861D2717B9C7F1DA8 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = FE559C429519CF6E4219B404 /* BoopNotificationService */;
+ targetProxy = 2B4F22AEA0B3AC6E026E54D9 /* PBXContainerItemProxy */;
+ };
53DC373C2B292831FF5347CF /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = A8738A21A24E7E622C597C1C /* Boop */;
@@ -446,6 +548,23 @@
/* End PBXTargetDependency section */
/* Begin XCBuildConfiguration section */
+ 0D23E65DBA9D29F38ED521FC /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ GENERATE_INFOPLIST_FILE = NO;
+ INFOPLIST_FILE = BoopNotificationService/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.example.Boop.NotificationService;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ TARGETED_DEVICE_FAMILY = 1;
+ };
+ name = Debug;
+ };
1F7AB9551BC1D788ACF480CA /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -513,7 +632,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
- MARKETING_VERSION = 1.1.0;
+ MARKETING_VERSION = 1.2.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -526,6 +645,23 @@
};
name = Release;
};
+ BCCDFC81596A832D7D4EA0D0 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ GENERATE_INFOPLIST_FILE = NO;
+ INFOPLIST_FILE = BoopNotificationService/Info.plist;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ PRODUCT_BUNDLE_IDENTIFIER = com.example.Boop.NotificationService;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ TARGETED_DEVICE_FAMILY = 1;
+ };
+ name = Release;
+ };
C98988CA0E29F9720A1773B1 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
@@ -603,7 +739,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.0;
- MARKETING_VERSION = 1.1.0;
+ MARKETING_VERSION = 1.2.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -701,6 +837,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Debug;
};
+ 54B5E2FCEF08F002E537997D /* Build configuration list for PBXNativeTarget "BoopNotificationService" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ 0D23E65DBA9D29F38ED521FC /* Debug */,
+ BCCDFC81596A832D7D4EA0D0 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Debug;
+ };
65E6615BBFC8E407FFC9B9B7 /* Build configuration list for PBXNativeTarget "BoopUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
diff --git a/ios/Boop.xcodeproj/project.xcworkspace/xcuserdata/chris.xcuserdatad/UserInterfaceState.xcuserstate b/ios/Boop.xcodeproj/project.xcworkspace/xcuserdata/chris.xcuserdatad/UserInterfaceState.xcuserstate
new file mode 100644
index 0000000..b65d693
Binary files /dev/null and b/ios/Boop.xcodeproj/project.xcworkspace/xcuserdata/chris.xcuserdatad/UserInterfaceState.xcuserstate differ
diff --git a/ios/Boop.xcodeproj/xcshareddata/xcschemes/Boop.xcscheme b/ios/Boop.xcodeproj/xcshareddata/xcschemes/Boop.xcscheme
index a83df47..c29f210 100644
--- a/ios/Boop.xcodeproj/xcshareddata/xcschemes/Boop.xcscheme
+++ b/ios/Boop.xcodeproj/xcshareddata/xcschemes/Boop.xcscheme
@@ -21,6 +21,20 @@
ReferencedContainer = "container:Boop.xcodeproj">
</BuildableReference>
</BuildActionEntry>
+ <BuildActionEntry
+ buildForTesting = "YES"
+ buildForRunning = "YES"
+ buildForProfiling = "YES"
+ buildForArchiving = "YES"
+ buildForAnalyzing = "YES">
+ <BuildableReference
+ BuildableIdentifier = "primary"
+ BlueprintIdentifier = "FE559C429519CF6E4219B404"
+ BuildableName = "BoopNotificationService.appex"
+ BlueprintName = "BoopNotificationService"
+ ReferencedContainer = "container:Boop.xcodeproj">
+ </BuildableReference>
+ </BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
diff --git a/ios/Boop/Components/Formatting.swift b/ios/Boop/Components/Formatting.swift
index eedac5f..eb5b44d 100644
--- a/ios/Boop/Components/Formatting.swift
+++ b/ios/Boop/Components/Formatting.swift
@@ -25,6 +25,18 @@ enum Formatting {
return "\(d) · \(t)"
}
+ /// "09:31" on the same day as `now`, otherwise "Aug 12 09:31".
+ static func clock(_ date: Date, now: Date = .now, calendar: Calendar = .current) -> String {
+ let t = date.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits))
+ if calendar.isDate(date, inSameDayAs: now) { return t }
+ return "\(shortDate(date)) \(t)"
+ }
+
+ /// "First seen 09:31 · Last seen 10:42" for a grouped row.
+ static func seenRange(_ group: GroupInfo, now: Date = .now, calendar: Calendar = .current) -> String {
+ "First seen \(clock(group.firstSeen, now: now, calendar: calendar)) · Last seen \(clock(group.lastSeen, now: now, calendar: calendar))"
+ }
+
/// "Today", "Yesterday", or a short date.
static func dayGroup(_ date: Date, now: Date = .now, calendar: Calendar = .current) -> String {
if calendar.isDate(date, inSameDayAs: now) { return "Today" }
diff --git a/ios/Boop/Design/DS.swift b/ios/Boop/Design/DS.swift
index 2eed842..dbbcdc2 100644
--- a/ios/Boop/Design/DS.swift
+++ b/ios/Boop/Design/DS.swift
@@ -1,6 +1,6 @@
import SwiftUI
-/// Design tokens, ported from `Design System/tokens/*.css`.
+/// Design tokens, mirroring the CSS variables in `server/web/src/app.css`.
enum DS {
// MARK: Colors
enum Colors {
@@ -91,7 +91,7 @@ enum DS {
static var title: Font { .figtree(28, .bold) }
}
- /// Restrained motion: the design system wants near-instant state changes.
+ /// Restrained motion: state changes should feel near-instant.
enum Motion {
static let snappy = Animation.spring(response: 0.32, dampingFraction: 0.86)
static let gentle = Animation.easeOut(duration: 0.18)
diff --git a/ios/Boop/Models/Event.swift b/ios/Boop/Models/Event.swift
index 2b97011..a86332d 100644
--- a/ios/Boop/Models/Event.swift
+++ b/ios/Boop/Models/Event.swift
@@ -18,6 +18,10 @@ struct Event: Codable, Identifiable, Hashable, Sendable {
let createdAt: Date
/// True when a silence rule stopped this event from being pushed.
let silenced: Bool
+ /// Buttons that open a URL, shown on the notification and in the detail.
+ let actions: [EventAction]
+ /// Present in grouped listings: this event is the latest of `group.count` occurrences.
+ let group: GroupInfo?
enum CodingKeys: String, CodingKey {
case id
@@ -29,7 +33,7 @@ struct Event: Codable, Identifiable, Hashable, Sendable {
case source, type, level, title, body, fingerprint, data
case occurredAt = "occurred_at"
case createdAt = "created_at"
- case silenced
+ case silenced, actions, group
}
init(from decoder: any Decoder) throws {
@@ -50,11 +54,13 @@ struct Event: Codable, Identifiable, Hashable, Sendable {
occurredAt = try c.decode(Date.self, forKey: .occurredAt)
createdAt = try c.decode(Date.self, forKey: .createdAt)
silenced = try c.decodeIfPresent(Bool.self, forKey: .silenced) ?? false
+ actions = try c.decodeIfPresent([EventAction].self, forKey: .actions) ?? []
+ group = try c.decodeIfPresent(GroupInfo.self, forKey: .group)
}
init(id: String, projectID: String, projectName: String, projectIcon: String = "", source: String = "", type: String = "",
level: Level, title: String, body: String = "", fingerprint: String = "", data: JSONValue = .object([:]),
- occurredAt: Date, createdAt: Date, silenced: Bool = false) {
+ occurredAt: Date, createdAt: Date, silenced: Bool = false, actions: [EventAction] = [], group: GroupInfo? = nil) {
self.id = id
self.externalID = nil
self.projectID = projectID
@@ -71,8 +77,13 @@ struct Event: Codable, Identifiable, Hashable, Sendable {
self.occurredAt = occurredAt
self.createdAt = createdAt
self.silenced = silenced
+ self.actions = actions
+ self.group = group
}
+ /// True when this row stands for more than one occurrence.
+ var isRepeated: Bool { (group?.count ?? 1) > 1 }
+
func hash(into hasher: inout Hasher) { hasher.combine(id) }
static func == (a: Event, b: Event) -> Bool { a.id == b.id && a.createdAt == b.createdAt }
@@ -80,6 +91,18 @@ struct Event: Codable, Identifiable, Hashable, Sendable {
var sections: EventSections { EventSections(data: data) }
}
+struct GroupInfo: Codable, Hashable, Sendable {
+ let count: Int
+ let firstSeen: Date
+ let lastSeen: Date
+
+ enum CodingKeys: String, CodingKey {
+ case count
+ case firstSeen = "first_seen"
+ case lastSeen = "last_seen"
+ }
+}
+
struct EventPage: Codable, Sendable {
let events: [Event]
let nextCursor: String?
diff --git a/ios/Boop/Models/EventAction.swift b/ios/Boop/Models/EventAction.swift
new file mode 100644
index 0000000..f2e5d27
--- /dev/null
+++ b/ios/Boop/Models/EventAction.swift
@@ -0,0 +1,9 @@
+import Foundation
+
+/// A button attached to an event: on the notification and in the detail view.
+struct EventAction: Codable, Hashable, Sendable {
+ let label: String
+ let url: String
+
+ var destination: URL? { URL(string: url) }
+}
diff --git a/ios/Boop/Models/EventMarkdown.swift b/ios/Boop/Models/EventMarkdown.swift
new file mode 100644
index 0000000..2959258
--- /dev/null
+++ b/ios/Boop/Models/EventMarkdown.swift
@@ -0,0 +1,122 @@
+import Foundation
+
+/// Text renderings of an event for copying and sharing. `agentMarkdown` is
+/// meant to be pasted straight into an AI assistant: everything the server
+/// knows, in a shape a model reads well.
+extension Event {
+ /// Short plain text: what happened, where, when.
+ var plainText: String {
+ var lines = [title]
+ if !body.isEmpty { lines.append(body) }
+ lines.append("")
+ var meta = [projectName, level.label]
+ if !source.isEmpty { meta.append(source) }
+ meta.append(Formatting.full(occurredAt))
+ lines.append(meta.joined(separator: " · "))
+ for a in actions { lines.append("\(a.label): \(a.url)") }
+ return lines.joined(separator: "\n")
+ }
+
+ /// Markdown with a section per recognised part of `data`.
+ var agentMarkdown: String {
+ var out: [String] = ["# \(title)"]
+ if !body.isEmpty { out.append(""); out.append(body) }
+
+ var facts: [String] = ["- Project: \(projectName)", "- Level: \(level.rawValue)"]
+ if !source.isEmpty { facts.append("- Source: \(source)") }
+ if !type.isEmpty { facts.append("- Type: \(type)") }
+ facts.append("- Occurred: \(Self.iso.string(from: occurredAt))")
+ if let g = group, g.count > 1 {
+ facts.append("- Occurrences: \(g.count) (first \(Self.iso.string(from: g.firstSeen)), last \(Self.iso.string(from: g.lastSeen)))")
+ }
+ if !fingerprint.isEmpty { facts.append("- Fingerprint: \(fingerprint)") }
+ if let ext = externalID, !ext.isEmpty { facts.append("- External id: \(ext)") }
+ facts.append("- Event id: \(id)")
+ out.append(contentsOf: ["", "## Event", ""] + facts)
+
+ let s = sections
+ if let exc = s.exception {
+ out.append(contentsOf: ["", "## Exception", ""])
+ let t = exc["type"]?.display ?? ""
+ let m = exc["message"]?.display ?? ""
+ switch (t.isEmpty, m.isEmpty) {
+ case (false, false): out.append("**\(t)**: \(m)")
+ case (false, true): out.append("**\(t)**")
+ case (true, false): out.append(m)
+ default: break
+ }
+ for k in exc.keys.filter({ $0 != "type" && $0 != "message" }).sorted() {
+ out.append("- \(k): \(exc[k]!.inline)")
+ }
+ }
+
+ if let tags = s.tags, !tags.isEmpty {
+ if let env = tags.first(where: { $0.0 == "environment" || $0.0 == "env" }) {
+ out.append(contentsOf: ["", "## Environment", "", env.1.display])
+ }
+ let others = tags.filter { $0.0 != "environment" && $0.0 != "env" }
+ if !others.isEmpty {
+ out.append(contentsOf: ["", "## Tags", ""])
+ out.append(contentsOf: others.map { "- \($0.0): \($0.1.inline)" })
+ }
+ }
+
+ if let frames = s.frames, !frames.isEmpty {
+ out.append(contentsOf: ["", "## Stack trace", "", "```"])
+ for f in frames {
+ var loc = f.file
+ if let line = f.line, !loc.isEmpty { loc += ":\(line)" }
+ var line = f.inApp ? "* " : " "
+ line += f.function
+ if !loc.isEmpty { line += " (\(loc))" }
+ out.append(line)
+ }
+ out.append("```")
+ if frames.contains(where: \.inApp) { out.append("`*` marks frames in the application's own code.") }
+ }
+
+ if let ctx = s.context, !ctx.isEmpty {
+ out.append(contentsOf: ["", "## Context", ""])
+ out.append(contentsOf: ctx.map { "- \($0.0): \($0.1.inline)" })
+ }
+
+ if let bcs = s.breadcrumbs, !bcs.isEmpty {
+ out.append(contentsOf: ["", "## Breadcrumbs", ""])
+ for b in bcs {
+ var parts: [String] = []
+ if !b.timestamp.isEmpty { parts.append(b.timestamp) }
+ if !b.category.isEmpty { parts.append("[\(b.category)]") }
+ parts.append(b.message)
+ out.append("- " + parts.joined(separator: " "))
+ }
+ }
+
+ if !s.rest.isEmpty {
+ out.append(contentsOf: ["", "## Data", "", "```json", JSONValue.object(Dictionary(uniqueKeysWithValues: s.rest)).pretty, "```"])
+ }
+
+ if !actions.isEmpty {
+ out.append(contentsOf: ["", "## Links", ""])
+ out.append(contentsOf: actions.map { "- [\($0.label)](\($0.url))" })
+ }
+ return out.joined(separator: "\n") + "\n"
+ }
+
+ nonisolated(unsafe) private static let iso: ISO8601DateFormatter = {
+ let f = ISO8601DateFormatter()
+ f.formatOptions = [.withInternetDateTime]
+ return f
+ }()
+}
+
+extension JSONValue {
+ /// Scalars as-is; containers as compact JSON on one line.
+ var inline: String {
+ if isContainer {
+ let enc = JSONEncoder()
+ enc.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
+ if let d = try? enc.encode(self), let s = String(data: d, encoding: .utf8) { return s }
+ }
+ return display
+ }
+}
diff --git a/ios/Boop/Networking/APIClient.swift b/ios/Boop/Networking/APIClient.swift
index b9e2c10..9e3e0d6 100644
--- a/ios/Boop/Networking/APIClient.swift
+++ b/ios/Boop/Networking/APIClient.swift
@@ -58,10 +58,12 @@ struct APIClient: Sendable {
let _: Empty = try await request("DELETE", "/api/v1/devices/\(id)")
}
- func events(project: String? = nil, level: Level? = nil, before: String? = nil, limit: Int = 50) async throws -> EventPage {
+ func events(project: String? = nil, level: Level? = nil, fingerprint: String? = nil, grouped: Bool = false, before: String? = nil, limit: Int = 50) async throws -> EventPage {
var items = [URLQueryItem(name: "limit", value: String(limit))]
if let project, !project.isEmpty { items.append(.init(name: "project", value: project)) }
if let level { items.append(.init(name: "level", value: level.rawValue)) }
+ if let fingerprint, !fingerprint.isEmpty { items.append(.init(name: "fingerprint", value: fingerprint)) }
+ if grouped { items.append(.init(name: "grouped", value: "true")) }
if let before { items.append(.init(name: "before", value: before)) }
return try await request("GET", "/api/v1/events", query: items)
}
diff --git a/ios/Boop/Notifications/NotificationActions.swift b/ios/Boop/Notifications/NotificationActions.swift
new file mode 100644
index 0000000..0464dba
--- /dev/null
+++ b/ios/Boop/Notifications/NotificationActions.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// The action buttons carried in a push payload. Shared by the app (which
+/// opens the URL when a button is tapped) and the notification service
+/// extension (which registers the buttons before the alert is shown).
+enum NotificationActions {
+ /// The `aps.category` the server sets on pushes that carry actions.
+ static let serverCategory = "boop.event.actions"
+ /// Prefix of the per-event category the extension registers.
+ static let categoryPrefix = "boop.event.actions."
+ /// Prefix of action identifiers; the suffix is the index into `actions`.
+ static let actionPrefix = "boop.action."
+ static let maxActions = 3
+
+ /// Actions from a push `userInfo` (`actions: [{label, url}]`). Malformed entries are dropped.
+ static func parse(_ userInfo: [AnyHashable: Any]) -> [EventAction] {
+ guard let raw = userInfo["actions"] as? [Any] else { return [] }
+ var out: [EventAction] = []
+ for item in raw {
+ if out.count == maxActions { break }
+ guard let dict = item as? [String: Any],
+ let label = (dict["label"] as? String)?.trimmingCharacters(in: .whitespaces), !label.isEmpty,
+ let url = (dict["url"] as? String)?.trimmingCharacters(in: .whitespaces), URL(string: url) != nil
+ else { continue }
+ out.append(EventAction(label: label, url: url))
+ }
+ return out
+ }
+
+ /// Category identifier for one event's buttons.
+ static func categoryID(eventID: String) -> String { categoryPrefix + eventID }
+
+ static func actionID(index: Int) -> String { actionPrefix + String(index) }
+
+ /// The index encoded in an action identifier, if it is one of ours.
+ static func actionIndex(_ identifier: String) -> Int? {
+ guard identifier.hasPrefix(actionPrefix) else { return nil }
+ return Int(identifier.dropFirst(actionPrefix.count))
+ }
+
+ /// The URL a tapped action should open, given the push's userInfo.
+ static func url(for identifier: String, userInfo: [AnyHashable: Any]) -> URL? {
+ guard let i = actionIndex(identifier) else { return nil }
+ let actions = parse(userInfo)
+ guard actions.indices.contains(i) else { return nil }
+ return actions[i].destination
+ }
+}
diff --git a/ios/Boop/Notifications/PushManager.swift b/ios/Boop/Notifications/PushManager.swift
index 3d48f04..cd6c301 100644
--- a/ios/Boop/Notifications/PushManager.swift
+++ b/ios/Boop/Notifications/PushManager.swift
@@ -64,6 +64,11 @@ final class PushManager: NSObject, UNUserNotificationCenterDelegate {
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let info = response.notification.request.content.userInfo
+ // An action button: open its URL and stay out of the way.
+ if let url = NotificationActions.url(for: response.actionIdentifier, userInfo: info) {
+ await MainActor.run { UIApplication.shared.open(url) }
+ return
+ }
let eventID = info["event_id"] as? String
let title = response.notification.request.content.title
let body = response.notification.request.content.body
diff --git a/ios/Boop/Screens/EventDetailView.swift b/ios/Boop/Screens/EventDetailView.swift
index 0c49894..5c38bd9 100644
--- a/ios/Boop/Screens/EventDetailView.swift
+++ b/ios/Boop/Screens/EventDetailView.swift
@@ -21,9 +21,16 @@ struct EventDetailView: View {
}
if let event {
ToolbarItem(placement: .topBarTrailing) {
- ShareLink(item: event.data.pretty, subject: Text(event.title)) {
+ Menu {
+ Button("Copy", systemImage: "doc.on.doc") { copy(event.plainText) }
+ Button("Copy as Markdown", systemImage: "text.document") { copy(event.agentMarkdown) }
+ ShareLink(item: event.agentMarkdown, subject: Text(event.title)) {
+ Label("Share", systemImage: "square.and.arrow.up")
+ }
+ } label: {
Image(systemName: "square.and.arrow.up")
}
+ .accessibilityIdentifier("event.share")
}
}
}
@@ -34,10 +41,14 @@ struct EventDetailView: View {
ScrollView {
VStack(alignment: .leading, spacing: DS.Space.s4) {
if let event {
+ if copied {
+ Notice(tone: .good, text: "Copied.").transition(.opacity.combined(with: .move(edge: .top)))
+ }
if event.silenced {
Notice(tone: .info, text: "Matched a silence rule, so it was not pushed. Manage silences in the web UI.")
}
summary(event)
+ actions(event)
sections(event)
raw(event)
} else if let error {
@@ -54,6 +65,42 @@ struct EventDetailView: View {
// MARK: Pieces
+ @State private var copied = false
+
+ private func copy(_ text: String) {
+ UIPasteboard.general.string = text
+ withAnimation(DS.Motion.snappy) { copied = true }
+ Task {
+ try? await Task.sleep(for: .seconds(2.5))
+ withAnimation(DS.Motion.gentle) { copied = false }
+ }
+ }
+
+ @ViewBuilder
+ private func actions(_ e: Event) -> some View {
+ if !e.actions.isEmpty {
+ Card(title: "Actions") {
+ FlowLayout(spacing: 8) {
+ ForEach(e.actions, id: \.self) { a in
+ if let url = a.destination {
+ Link(destination: url) {
+ HStack(spacing: 6) {
+ Text(a.label)
+ Image(systemName: "arrow.up.right").font(.system(size: 11, weight: .semibold))
+ }
+ .font(DS.Text.ui)
+ .foregroundStyle(DS.Colors.textOnDark)
+ .padding(.horizontal, 14)
+ .frame(height: 34)
+ .background(DS.Colors.accent, in: RoundedRectangle(cornerRadius: DS.Radius.control, style: .continuous))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
private func summary(_ e: Event) -> some View {
Card {
VStack(alignment: .leading, spacing: 8) {
diff --git a/ios/Boop/Screens/GroupView.swift b/ios/Boop/Screens/GroupView.swift
new file mode 100644
index 0000000..4fe8d73
--- /dev/null
+++ b/ios/Boop/Screens/GroupView.swift
@@ -0,0 +1,192 @@
+import SwiftUI
+
+/// Navigation target for the occurrences of one fingerprint within a project.
+struct GroupRoute: Hashable {
+ let projectID: String
+ let projectName: String
+ let projectIcon: String
+ let fingerprint: String
+ let title: String
+
+ init(event: Event) {
+ projectID = event.projectID
+ projectName = event.projectName
+ projectIcon = event.projectIcon
+ fingerprint = event.fingerprint
+ title = event.title
+ }
+}
+
+@MainActor
+@Observable
+final class GroupModel {
+ var head: Event?
+ var events: [Event] = []
+ var cursor: String?
+ var loading = false
+ var loadingMore = false
+ var error: String?
+
+ func refresh(_ client: APIClient, route: GroupRoute) async {
+ loading = true
+ error = nil
+ defer { loading = false }
+ do {
+ async let headPage = client.events(project: route.projectID, fingerprint: route.fingerprint, grouped: true, limit: 1)
+ async let page = client.events(project: route.projectID, fingerprint: route.fingerprint)
+ head = try await headPage.events.first
+ let p = try await page
+ withAnimation(DS.Motion.settle) {
+ events = p.events
+ cursor = p.nextCursor
+ }
+ } catch {
+ self.error = (error as? APIError)?.message ?? error.localizedDescription
+ }
+ }
+
+ func loadMore(_ client: APIClient, route: GroupRoute) async {
+ guard let cursor, !loadingMore else { return }
+ loadingMore = true
+ defer { loadingMore = false }
+ do {
+ let page = try await client.events(project: route.projectID, fingerprint: route.fingerprint, before: cursor)
+ let known = Set(events.map(\.id))
+ withAnimation(DS.Motion.settle) {
+ events += page.events.filter { !known.contains($0.id) }
+ self.cursor = page.nextCursor
+ }
+ } catch {
+ self.error = (error as? APIError)?.message ?? error.localizedDescription
+ }
+ }
+}
+
+/// Every occurrence of a fingerprint, newest first. Pushed from a grouped inbox row.
+struct GroupView: View {
+ @Environment(AppSession.self) private var session
+ let route: GroupRoute
+ @Binding var selected: EventRoute?
+ @State private var model = GroupModel()
+
+ var body: some View {
+ List {
+ Section {
+ header
+ .listRowInsets(EdgeInsets(top: 4, leading: DS.Space.s4, bottom: 8, trailing: DS.Space.s4))
+ .listRowSeparator(.hidden)
+ .listRowBackground(DS.Colors.bg)
+ }
+ Section {
+ if let error = model.error, model.events.isEmpty {
+ VStack(spacing: DS.Space.s3) {
+ Notice(tone: .bad, text: error)
+ Button("Retry") { Task { await reload() } }.buttonStyle(.boopGhost)
+ }
+ .listRowBackground(DS.Colors.bg)
+ .listRowSeparator(.hidden)
+ } else if model.events.isEmpty && !model.loading {
+ EmptyState(title: "No occurrences", message: "Nothing with this fingerprint in this project.", systemImage: "square.stack.3d.up.slash")
+ .listRowBackground(DS.Colors.bg)
+ .listRowSeparator(.hidden)
+ }
+ ForEach(model.events) { event in
+ Button {
+ selected = EventRoute(id: event.id, summary: nil)
+ } label: {
+ OccurrenceRow(event: event)
+ }
+ .buttonStyle(RowButtonStyle())
+ .listRowInsets(EdgeInsets(top: 0, leading: DS.Space.s4, bottom: 0, trailing: DS.Space.s4))
+ .listRowSeparatorTint(DS.Colors.borderHairline)
+ .listRowBackground(DS.Colors.bg)
+ }
+ if model.cursor != nil {
+ HStack {
+ Spacer()
+ ProgressView().tint(DS.Colors.accent)
+ Spacer()
+ }
+ .listRowBackground(DS.Colors.bg)
+ .listRowSeparator(.hidden)
+ .task { if let c = session.client { await model.loadMore(c, route: route) } }
+ }
+ } header: {
+ Text("Occurrences")
+ .font(DS.Text.caption)
+ .foregroundStyle(DS.Colors.textFaint)
+ .textCase(nil)
+ }
+ }
+ .listStyle(.plain)
+ .scrollContentBackground(.hidden)
+ .background(DS.Colors.bg)
+ .navigationTitle(route.title)
+ .navigationBarTitleDisplayMode(.inline)
+ .refreshable { await reload() }
+ .task { await reload() }
+ }
+
+ private var header: some View {
+ Card {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ ProjectIcon(icon: route.projectIcon, size: 14)
+ Text(route.projectName).font(DS.Text.meta).foregroundStyle(DS.Colors.textSecondary)
+ if let h = model.head {
+ Text("·").foregroundStyle(DS.Colors.textFaint)
+ LevelBadge(level: h.level)
+ }
+ }
+ HStack(alignment: .firstTextBaseline, spacing: 8) {
+ Text(route.title).font(DS.Text.metric).foregroundStyle(DS.Colors.ink)
+ if let g = model.head?.group { CountPill(count: g.count) }
+ }
+ if let g = model.head?.group {
+ Text(Formatting.seenRange(g)).font(DS.Text.statusLine).foregroundStyle(DS.Colors.textSecondary)
+ }
+ Rectangle().fill(DS.Colors.borderHairline).frame(height: 1).padding(.vertical, 6)
+ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], alignment: .leading, spacing: 12) {
+ Fact(label: "Fingerprint", value: route.fingerprint, mono: true)
+ if let g = model.head?.group {
+ Fact(label: "First seen", value: Formatting.full(g.firstSeen))
+ Fact(label: "Last seen", value: Formatting.full(g.lastSeen))
+ }
+ }
+ }
+ }
+ }
+
+ private func reload() async {
+ guard let client = session.client else { return }
+ await model.refresh(client, route: route)
+ }
+}
+
+struct OccurrenceRow: View {
+ let event: Event
+
+ var body: some View {
+ HStack(alignment: .top, spacing: 12) {
+ VStack(alignment: .leading, spacing: 3) {
+ HStack(spacing: 6) {
+ LevelBadge(level: event.level)
+ if event.silenced {
+ Text("· silenced").font(DS.Text.caption).foregroundStyle(DS.Colors.textInactive)
+ }
+ }
+ Text(event.title).font(DS.Text.rowTitle).foregroundStyle(DS.Colors.ink).lineLimit(1)
+ if !event.body.isEmpty {
+ Text(event.body).font(DS.Text.meta).foregroundStyle(DS.Colors.textMuted).lineLimit(2)
+ }
+ }
+ Spacer(minLength: 8)
+ VStack(alignment: .trailing, spacing: 3) {
+ Text(Formatting.relative(event.createdAt)).font(DS.Text.caption).foregroundStyle(DS.Colors.textMuted).monospacedDigit()
+ Text(Formatting.clock(event.createdAt)).font(DS.Text.caption).foregroundStyle(DS.Colors.textFaint).monospacedDigit()
+ }
+ }
+ .padding(.vertical, 12)
+ .contentShape(Rectangle())
+ }
+}
diff --git a/ios/Boop/Screens/InboxView.swift b/ios/Boop/Screens/InboxView.swift
index fbdc4df..4c42d02 100644
--- a/ios/Boop/Screens/InboxView.swift
+++ b/ios/Boop/Screens/InboxView.swift
@@ -10,8 +10,16 @@ final class InboxModel {
var error: String?
var level: Level?
var project: String?
+ /// Collapse repeats of the same fingerprint into one row. Remembered across launches.
+ var grouped: Bool {
+ didSet { UserDefaults.standard.set(grouped, forKey: "boop.inbox.grouped") }
+ }
private(set) var loadedOnce = false
+ init() {
+ grouped = UserDefaults.standard.object(forKey: "boop.inbox.grouped") as? Bool ?? true
+ }
+
var projects: [Project] {
var seen = Set<String>()
return events.compactMap { e in
@@ -44,7 +52,7 @@ final class InboxModel {
error = nil
defer { loading = false; loadedOnce = true }
do {
- let page = try await client.events(project: project, level: level)
+ let page = try await client.events(project: project, level: level, grouped: grouped)
withAnimation(DS.Motion.settle) {
events = page.events
cursor = page.nextCursor
@@ -59,7 +67,7 @@ final class InboxModel {
loadingMore = true
defer { loadingMore = false }
do {
- let page = try await client.events(project: project, level: level, before: cursor)
+ let page = try await client.events(project: project, level: level, grouped: grouped, before: cursor)
let known = Set(events.map(\.id))
withAnimation(DS.Motion.settle) {
events += page.events.filter { !known.contains($0.id) }
@@ -75,9 +83,10 @@ struct InboxView: View {
@Environment(AppSession.self) private var session
@Binding var selected: EventRoute?
@State private var model = InboxModel()
+ @State private var path: [GroupRoute] = []
var body: some View {
- NavigationStack {
+ NavigationStack(path: $path) {
list
.background(DS.Colors.bg)
.navigationTitle("Inbox")
@@ -94,6 +103,10 @@ struct InboxView: View {
.task { if !model.loadedOnce { await reload() } }
.onChange(of: model.level) { Task { await reload() } }
.onChange(of: model.project) { Task { await reload() } }
+ .onChange(of: model.grouped) { Task { await reload() } }
+ .navigationDestination(for: GroupRoute.self) { route in
+ GroupView(route: route, selected: $selected)
+ }
}
}
@@ -120,7 +133,11 @@ struct InboxView: View {
Section {
ForEach(group.events) { event in
Button {
- selected = EventRoute(id: event.id, summary: nil)
+ if event.isRepeated {
+ path.append(GroupRoute(event: event))
+ } else {
+ selected = EventRoute(id: event.id, summary: nil)
+ }
} label: {
EventRow(event: event)
}
@@ -177,6 +194,7 @@ struct InboxView: View {
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .topBarTrailing) {
Menu {
+ Toggle("Group repeats", systemImage: "square.stack.3d.up", isOn: $model.grouped)
Picker("Level", selection: $model.level) {
Text("All levels").tag(Level?.none)
ForEach(Level.allCases) { l in
@@ -225,11 +243,21 @@ struct EventRow: View {
Text("· silenced").font(DS.Text.caption).foregroundStyle(DS.Colors.textInactive)
}
}
- Text(event.title)
- .font(DS.Text.rowTitle)
- .foregroundStyle(DS.Colors.ink)
- .lineLimit(1)
- if !event.body.isEmpty {
+ HStack(spacing: 8) {
+ Text(event.title)
+ .font(DS.Text.rowTitle)
+ .foregroundStyle(DS.Colors.ink)
+ .lineLimit(1)
+ if let g = event.group, g.count > 1 {
+ CountPill(count: g.count)
+ }
+ }
+ if let g = event.group, g.count > 1 {
+ Text(Formatting.seenRange(g))
+ .font(DS.Text.meta)
+ .foregroundStyle(DS.Colors.textSecondary)
+ .lineLimit(1)
+ } else if !event.body.isEmpty {
Text(event.body)
.font(DS.Text.meta)
.foregroundStyle(DS.Colors.textMuted)
@@ -237,16 +265,39 @@ struct EventRow: View {
}
}
Spacer(minLength: 8)
- Text(Formatting.relative(event.createdAt))
- .font(DS.Text.caption)
- .foregroundStyle(DS.Colors.textMuted)
- .monospacedDigit()
+ VStack(alignment: .trailing, spacing: 6) {
+ Text(Formatting.relative(event.createdAt))
+ .font(DS.Text.caption)
+ .foregroundStyle(DS.Colors.textMuted)
+ .monospacedDigit()
+ if event.isRepeated {
+ Image(systemName: "chevron.right")
+ .font(.system(size: 11, weight: .semibold))
+ .foregroundStyle(DS.Colors.textFaint)
+ .accessibilityHidden(true)
+ }
+ }
}
.padding(.vertical, 12)
.contentShape(Rectangle())
}
}
+/// "×47" pill for grouped rows.
+struct CountPill: View {
+ let count: Int
+
+ var body: some View {
+ Text("×\(count)")
+ .font(DS.Text.small)
+ .foregroundStyle(DS.Colors.accentHover)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 1)
+ .background(DS.Colors.accentTint, in: Capsule())
+ .monospacedDigit()
+ }
+}
+
/// Rows tint to bg-hover on press, no scale.
struct RowButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
diff --git a/ios/BoopNotificationService/Info.plist b/ios/BoopNotificationService/Info.plist
new file mode 100644
index 0000000..66ae3d5
--- /dev/null
+++ b/ios/BoopNotificationService/Info.plist
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>en</string>
+ <key>CFBundleDisplayName</key>
+ <string>Boop Notification Service</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>XPC!</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.usernotifications.service</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
+ </dict>
+</dict>
+</plist>
diff --git a/ios/BoopNotificationService/NotificationService.swift b/ios/BoopNotificationService/NotificationService.swift
new file mode 100644
index 0000000..d84fcf7
--- /dev/null
+++ b/ios/BoopNotificationService/NotificationService.swift
@@ -0,0 +1,41 @@
+import UserNotifications
+
+/// Runs before a push with `mutable-content` is shown. Boop uses it for one
+/// thing: turning the `actions` in the payload into real notification buttons.
+/// iOS only shows buttons for categories registered ahead of time, and the
+/// labels are per-event, so the category is registered here, just in time.
+final class NotificationService: UNNotificationServiceExtension {
+ private var handler: ((UNNotificationContent) -> Void)?
+ private var content: UNMutableNotificationContent?
+
+ override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
+ handler = contentHandler
+ let mutable = request.content.mutableCopy() as? UNMutableNotificationContent
+ content = mutable
+ guard let mutable else { return contentHandler(request.content) }
+
+ let info = request.content.userInfo
+ let actions = NotificationActions.parse(info)
+ guard !actions.isEmpty, let eventID = info["event_id"] as? String else { return contentHandler(mutable) }
+
+ let categoryID = NotificationActions.categoryID(eventID: eventID)
+ let buttons = actions.enumerated().map { i, a in
+ UNNotificationAction(identifier: NotificationActions.actionID(index: i), title: a.label, options: [.foreground])
+ }
+ let category = UNNotificationCategory(identifier: categoryID, actions: buttons, intentIdentifiers: [], options: [])
+ let center = UNUserNotificationCenter.current()
+ center.getNotificationCategories { existing in
+ // setNotificationCategories replaces the whole set, so keep what is there
+ // (minus stale per-event categories, which pile up otherwise).
+ var keep = existing.filter { !$0.identifier.hasPrefix(NotificationActions.categoryPrefix) }
+ keep.insert(category)
+ center.setNotificationCategories(keep)
+ mutable.categoryIdentifier = categoryID
+ contentHandler(mutable)
+ }
+ }
+
+ override func serviceExtensionTimeWillExpire() {
+ if let handler, let content { handler(content) }
+ }
+}
diff --git a/ios/BoopTests/EventMarkdownTests.swift b/ios/BoopTests/EventMarkdownTests.swift
new file mode 100644
index 0000000..5595796
--- /dev/null
+++ b/ios/BoopTests/EventMarkdownTests.swift
@@ -0,0 +1,82 @@
+import XCTest
+@testable import Boop
+
+final class EventMarkdownTests: XCTestCase {
+ func decode(_ json: String) throws -> Event {
+ try APIClient.decoder.decode(Event.self, from: Data(json.utf8))
+ }
+
+ func testRichErrorRendersEverySection() throws {
+ let e = try decode("""
+ {
+ "id": "evt_1", "project_id": "prj_1", "project_name": "Uini", "source": "error_tracker", "level": "error",
+ "title": "KeyError", "body": "key :can_palette? not found", "fingerprint": "uini-keyerror",
+ "data": {
+ "exception": {"type": "KeyError", "message": "key :can_palette? not found", "module": "Elixir.KeyError"},
+ "stacktrace": [
+ {"file": "lib/uini_web/live/widget_settings_live.ex", "line": 49, "function": "handle_event/3", "in_app": true},
+ {"file": "lib/phoenix_live_view.ex", "line": 12, "function": "Phoenix.LiveView.mount/2", "in_app": false}
+ ],
+ "tags": {"environment": "production", "runtime": "elixir 1.19"},
+ "context": {"user_id": "123", "password": "[REDACTED]", "request": {"path": "/x", "method": "POST"}},
+ "breadcrumbs": [{"timestamp": "12:51:40", "category": "navigation", "message": "GET /sites/1"}],
+ "custom": {"deep": [1, 2]}
+ },
+ "actions": [{"label": "Open in ErrorTracker", "url": "https://uini.app/errors/1"}],
+ "occurred_at": "2026-08-28T12:51:44Z", "created_at": "2026-08-28T12:51:45Z"
+ }
+ """)
+ let md = e.agentMarkdown
+ let expectedOrder = ["# KeyError", "key :can_palette? not found", "## Event", "- Project: Uini", "- Level: error", "- Source: error_tracker",
+ "- Occurred: 2026-08-28T12:51:44Z", "- Fingerprint: uini-keyerror", "- Event id: evt_1",
+ "## Exception", "**KeyError**: key :can_palette? not found", "- module: Elixir.KeyError",
+ "## Environment", "production", "## Tags", "- runtime: elixir 1.19",
+ "## Stack trace", "```", "* handle_event/3 (lib/uini_web/live/widget_settings_live.ex:49)", " Phoenix.LiveView.mount/2 (lib/phoenix_live_view.ex:12)", "```",
+ "## Context", "- password: [REDACTED]", "- request: {\"method\":\"POST\",\"path\":\"/x\"}", "- user_id: 123",
+ "## Breadcrumbs", "- 12:51:40 [navigation] GET /sites/1",
+ "## Data", "```json", "\"custom\"", "```",
+ "## Links", "- [Open in ErrorTracker](https://uini.app/errors/1)"]
+ var cursor = md.startIndex
+ for needle in expectedOrder {
+ guard let r = md.range(of: needle, range: cursor..<md.endIndex) else {
+ return XCTFail("missing or out of order: \(needle)\n\n\(md)")
+ }
+ cursor = r.upperBound
+ }
+ XCTAssertTrue(md.hasSuffix("\n"))
+ // The environment tag is not repeated under Tags.
+ XCTAssertNil(md.range(of: "- environment: production"))
+ }
+
+ func testMinimalEventKeepsOnlyWhatExists() throws {
+ let e = try decode(#"{"id":"evt_2","project_id":"prj_1","project_name":"Infra","title":"Backup complete","level":"success","occurred_at":"2026-08-28T12:51:44Z","created_at":"2026-08-28T12:51:44Z"}"#)
+ let md = e.agentMarkdown
+ XCTAssertEqual(md, """
+ # Backup complete
+
+ ## Event
+
+ - Project: Infra
+ - Level: success
+ - Occurred: 2026-08-28T12:51:44Z
+ - Event id: evt_2
+
+ """)
+ for absent in ["## Exception", "## Stack trace", "## Context", "## Breadcrumbs", "## Data", "## Links", "## Environment"] {
+ XCTAssertNil(md.range(of: absent), absent)
+ }
+ }
+
+ func testGroupInfoAndPlainText() throws {
+ let e = try decode(#"{"id":"evt_3","project_id":"prj_1","project_name":"Uini","title":"Timeout","body":"upstream 504","level":"warning","source":"cron","fingerprint":"t","group":{"count":47,"first_seen":"2026-08-28T09:31:00Z","last_seen":"2026-08-28T10:42:00Z"},"actions":[{"label":"Open","url":"https://x"}],"occurred_at":"2026-08-28T10:42:00Z","created_at":"2026-08-28T10:42:00Z"}"#)
+ XCTAssertTrue(e.agentMarkdown.contains("- Occurrences: 47 (first 2026-08-28T09:31:00Z, last 2026-08-28T10:42:00Z)"))
+ let plain = e.plainText
+ XCTAssertTrue(plain.hasPrefix("Timeout\nupstream 504\n\nUini · Warning · cron · "))
+ XCTAssertTrue(plain.hasSuffix("\nOpen: https://x"))
+ }
+
+ func testInlineJSON() {
+ XCTAssertEqual(JSONValue.string("a/b").inline, "a/b")
+ XCTAssertEqual(JSONValue.object(["b": .number(1), "a": .array([.string("x/y")])]).inline, #"{"a":["x/y"],"b":1}"#)
+ }
+}
diff --git a/ios/BoopTests/EventTests.swift b/ios/BoopTests/EventTests.swift
index 4baa481..1193a36 100644
--- a/ios/BoopTests/EventTests.swift
+++ b/ios/BoopTests/EventTests.swift
@@ -14,6 +14,8 @@ final class EventTests: XCTestCase {
"breadcrumbs": [{"timestamp": "12:51", "category": "nav", "message": "GET /"}],
"custom": {"deep": [1, 2, {"k": "v"}]}
},
+ "actions": [{"label": "Open", "url": "https://uini.app/errors/1"}, {"label": "App", "url": "uini://errors/1"}],
+ "group": {"count": 47, "first_seen": "2026-08-28T09:31:00Z", "last_seen": "2026-08-28T10:42:00Z"},
"occurred_at": "2026-08-28T12:51:44Z",
"created_at": "2026-08-28T14:10:46.627043000Z",
"silenced": true
@@ -25,6 +27,11 @@ final class EventTests: XCTestCase {
XCTAssertEqual(e.level, .error)
XCTAssertTrue(e.silenced)
XCTAssertEqual(e.externalID, "4f9d")
+ XCTAssertEqual(e.actions.map(\.label), ["Open", "App"])
+ XCTAssertEqual(e.actions[1].destination?.scheme, "uini")
+ XCTAssertEqual(e.group?.count, 47)
+ XCTAssertTrue(e.isRepeated)
+ XCTAssertEqual(e.group?.lastSeen.timeIntervalSince(e.group!.firstSeen), 71 * 60)
XCTAssertEqual(Calendar(identifier: .gregorian).component(.year, from: e.createdAt), 2026)
// Nanosecond timestamps are accepted and keep millisecond precision.
XCTAssertEqual(e.createdAt.timeIntervalSince1970, 1_787_926_246.627, accuracy: 0.001)
@@ -48,6 +55,9 @@ final class EventTests: XCTestCase {
let e = try APIClient.decoder.decode(Event.self, from: Data(json.utf8))
XCTAssertEqual(e.level, .info)
XCTAssertFalse(e.silenced)
+ XCTAssertEqual(e.actions, [])
+ XCTAssertNil(e.group)
+ XCTAssertFalse(e.isRepeated)
XCTAssertEqual(e.body, "")
XCTAssertEqual(e.data, .object([:]))
XCTAssertTrue(e.sections.isEmpty)
diff --git a/ios/BoopTests/FormattingTests.swift b/ios/BoopTests/FormattingTests.swift
index d44c606..2bf33e0 100644
--- a/ios/BoopTests/FormattingTests.swift
+++ b/ios/BoopTests/FormattingTests.swift
@@ -19,4 +19,19 @@ final class FormattingTests: XCTestCase {
XCTAssertEqual(Formatting.dayGroup(now.addingTimeInterval(-3600), now: now.addingTimeInterval(7200), calendar: cal), "Yesterday")
XCTAssertNotEqual(Formatting.dayGroup(now.addingTimeInterval(-10 * 86400), now: now, calendar: cal), "Today")
}
+
+ func testClockAndSeenRange() {
+ var cal = Calendar(identifier: .gregorian)
+ cal.timeZone = TimeZone(identifier: "UTC")!
+ let first = now.addingTimeInterval(9 * 3600 + 31 * 60)
+ let last = now.addingTimeInterval(10 * 3600 + 42 * 60)
+ let today = now.addingTimeInterval(12 * 3600)
+ // Time components are formatted in the current locale/zone; compare against the same formatter.
+ let hm = { (d: Date) in d.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute(.twoDigits)) }
+ XCTAssertEqual(Formatting.clock(first, now: today, calendar: cal), hm(first))
+ XCTAssertTrue(Formatting.clock(first, now: now.addingTimeInterval(5 * 86400), calendar: cal).hasSuffix(hm(first)))
+ XCTAssertTrue(Formatting.clock(first, now: now.addingTimeInterval(5 * 86400), calendar: cal).count > hm(first).count)
+ let g = GroupInfo(count: 47, firstSeen: first, lastSeen: last)
+ XCTAssertEqual(Formatting.seenRange(g, now: today, calendar: cal), "First seen \(hm(first)) · Last seen \(hm(last))")
+ }
}
diff --git a/ios/BoopTests/NotificationActionsTests.swift b/ios/BoopTests/NotificationActionsTests.swift
new file mode 100644
index 0000000..b27d0bf
--- /dev/null
+++ b/ios/BoopTests/NotificationActionsTests.swift
@@ -0,0 +1,42 @@
+import XCTest
+@testable import Boop
+
+final class NotificationActionsTests: XCTestCase {
+ let info: [AnyHashable: Any] = [
+ "event_id": "evt_1",
+ "actions": [
+ ["label": " Open deploy ", "url": "https://github.com/x/y/actions/runs/1"],
+ ["label": "", "url": "https://dropped"],
+ ["label": "No url"],
+ ["label": "App", "url": "myapp://orders/42"],
+ ],
+ ]
+
+ func testParsesValidActionsOnly() {
+ let a = NotificationActions.parse(info)
+ XCTAssertEqual(a.map(\.label), ["Open deploy", "App"])
+ XCTAssertEqual(a[1].destination?.scheme, "myapp")
+ XCTAssertEqual(NotificationActions.parse([:]), [])
+ XCTAssertEqual(NotificationActions.parse(["actions": "nope"]), [])
+ }
+
+ func testCapsAtThree() {
+ let many: [AnyHashable: Any] = ["actions": (0..<5).map { ["label": "a\($0)", "url": "https://a/\($0)"] }]
+ XCTAssertEqual(NotificationActions.parse(many).count, 3)
+ }
+
+ func testIdentifiersRoundTrip() {
+ XCTAssertEqual(NotificationActions.categoryID(eventID: "evt_1"), "boop.event.actions.evt_1")
+ XCTAssertEqual(NotificationActions.actionID(index: 2), "boop.action.2")
+ XCTAssertEqual(NotificationActions.actionIndex("boop.action.2"), 2)
+ XCTAssertNil(NotificationActions.actionIndex("com.apple.UNNotificationDefaultActionIdentifier"))
+ XCTAssertNil(NotificationActions.actionIndex("boop.action.x"))
+ }
+
+ func testURLForTappedAction() {
+ XCTAssertEqual(NotificationActions.url(for: "boop.action.0", userInfo: info)?.absoluteString, "https://github.com/x/y/actions/runs/1")
+ XCTAssertEqual(NotificationActions.url(for: "boop.action.1", userInfo: info)?.absoluteString, "myapp://orders/42")
+ XCTAssertNil(NotificationActions.url(for: "boop.action.2", userInfo: info))
+ XCTAssertNil(NotificationActions.url(for: "com.apple.UNNotificationDefaultActionIdentifier", userInfo: info))
+ }
+}
diff --git a/ios/BoopUITests/PairingFlowUITests.swift b/ios/BoopUITests/PairingFlowUITests.swift
index 972639d..492ff64 100644
--- a/ios/BoopUITests/PairingFlowUITests.swift
+++ b/ios/BoopUITests/PairingFlowUITests.swift
@@ -52,10 +52,32 @@ final class PairingFlowUITests: XCTestCase {
XCTAssertTrue(app.navigationBars["Inbox"].waitForExistence(timeout: 10))
let row = app.staticTexts["KeyError"].firstMatch
XCTAssertTrue(row.waitForExistence(timeout: 10), "seeded event should be listed")
+
+ // Three seeded KeyErrors share a fingerprint: one grouped row that opens the occurrences.
+ XCTAssertTrue(app.staticTexts["×3"].firstMatch.waitForExistence(timeout: 5), "grouped row should show the count")
row.tap()
+ XCTAssertTrue(app.staticTexts["Occurrences"].waitForExistence(timeout: 5), "tapping a grouped row shows its occurrences")
+ XCTAssertTrue(app.staticTexts["uini-keyerror"].firstMatch.exists)
+ let occurrence = app.buttons.containing(.staticText, identifier: "KeyError").firstMatch
+ XCTAssertTrue(occurrence.waitForExistence(timeout: 5))
+ occurrence.tap()
+
XCTAssertTrue(app.staticTexts["Stacktrace"].waitForExistence(timeout: 5))
XCTAssertTrue(app.staticTexts["[REDACTED]"].firstMatch.exists)
+ XCTAssertTrue(app.staticTexts["Actions"].firstMatch.exists, "actions card")
+ XCTAssertTrue(app.buttons["Open in ErrorTracker"].firstMatch.exists || app.links["Open in ErrorTracker"].firstMatch.exists, "action button")
+
+ // Share menu: Copy / Copy as Markdown / Share.
+ app.buttons["event.share"].firstMatch.tap()
+ XCTAssertTrue(app.buttons["Copy as Markdown"].waitForExistence(timeout: 3))
+ XCTAssertTrue(app.buttons["Copy"].exists)
+ XCTAssertTrue(app.buttons["Share"].exists)
+ app.buttons["Copy as Markdown"].tap()
+ XCTAssertTrue(app.staticTexts["Copied."].waitForExistence(timeout: 5), "copy confirmation")
+
app.buttons["Close"].firstMatch.tap()
+ XCTAssertTrue(app.staticTexts["Occurrences"].waitForExistence(timeout: 5))
+ app.navigationBars.buttons.firstMatch.tap() // back
XCTAssertTrue(app.navigationBars["Inbox"].waitForExistence(timeout: 5))
}
}
diff --git a/ios/BoopUITests/ScreenshotUITests.swift b/ios/BoopUITests/ScreenshotUITests.swift
index 487dde4..b6dc0b4 100644
--- a/ios/BoopUITests/ScreenshotUITests.swift
+++ b/ios/BoopUITests/ScreenshotUITests.swift
@@ -12,6 +12,11 @@ final class ScreenshotUITests: XCTestCase {
sleep(1)
attach(app, "inbox")
app.staticTexts["KeyError"].firstMatch.tap()
+ // A grouped row opens the occurrences first; a single event opens the sheet directly.
+ if app.staticTexts["Occurrences"].waitForExistence(timeout: 3) {
+ attach(app, "group")
+ app.buttons.containing(.staticText, identifier: "KeyError").firstMatch.tap()
+ }
XCTAssertTrue(app.staticTexts["Stacktrace"].waitForExistence(timeout: 5))
sleep(1)
attach(app, "event-sheet")
@@ -19,6 +24,8 @@ final class ScreenshotUITests: XCTestCase {
sleep(1)
attach(app, "event-sheet-scrolled")
app.buttons["Close"].firstMatch.tap()
+ if app.staticTexts["Occurrences"].waitForExistence(timeout: 2) { app.navigationBars.buttons.firstMatch.tap() }
+ XCTAssertTrue(app.navigationBars["Inbox"].waitForExistence(timeout: 5))
app.navigationBars["Inbox"].buttons.firstMatch.tap()
sleep(1)
attach(app, "filter-menu")
diff --git a/ios/README.md b/ios/README.md
index 10361a5..e4c6f00 100644
--- a/ios/README.md
+++ b/ios/README.md
@@ -2,7 +2,7 @@
The native client for a self-hosted [Boop](../README.md) server. You build and sign it yourself with your own Apple Developer account; nothing is distributed through Boop infrastructure.
-Requires Xcode 26 and iOS 26.
+Requires Xcode 26 and iOS 26. App version 1.2.0 needs server 1.2.0 or newer for grouping, actions and the share menu (older servers still work; those features simply do not appear).
## Build it
@@ -14,7 +14,7 @@ Then in Xcode:
1. Select the **Boop** target → **Signing & Capabilities**.
2. Pick your **Team**.
-3. Change the **Bundle Identifier** from `com.example.Boop` to your own (for example `com.yourname.Boop`). This exact value must also be set as `APNS_BUNDLE_ID` on your server.
+3. Change the **Bundle Identifier** from `com.example.Boop` to your own (for example `com.yourname.Boop`). This exact value must also be set as `APNS_BUNDLE_ID` on your server. Do the same for the **BoopNotificationService** target: its identifier must be your app id plus `.NotificationService` (for example `com.yourname.Boop.NotificationService`).
4. Make sure the **Push Notifications** capability is present (it comes from `Boop.entitlements`). Xcode will register the App ID with Apple automatically when signing is set up.
5. Plug in your iPhone, select it as the run destination, and press Run. Push notifications do not work in the simulator.
@@ -34,7 +34,10 @@ The server address in the pairing code comes from `BOOP_BASE_URL`. It must be re
## What it does
- Inbox grouped by day, pull to refresh, cursor pagination, project and level filters.
-- Event detail with exception, stacktrace (in-app frames highlighted), tags, context, breadcrumbs, raw JSON, share.
+- Group repeats: events sharing a fingerprint show as one row (`KeyError ×47 · First seen 09:31 · Last seen 10:42`) that opens the occurrences. Toggle in the filter menu.
+- Event detail with exception, stacktrace (in-app frames highlighted), tags, context, breadcrumbs, raw JSON, and action buttons.
+- Share menu: **Copy** (plain text), **Copy as Markdown** (sectioned, ready for an AI assistant) and **Share** (straight into another app).
+- Notification actions: an event's `actions` become buttons on the push (long-press it). The `BoopNotificationService` extension registers them just in time; tapping one opens its URL.
- Notification tap opens the event and fetches the latest data; if the server is unreachable the push's title and body are shown with a retry.
- Device credential is stored in the Keychain. The app never sees project API keys or APNs keys.
- Re-registers with APNs on every launch and updates the server when the token changes.
@@ -52,6 +55,14 @@ cat > /tmp/push.json <<'JSON'
{"aps":{"alert":{"title":"Uini · KeyError","body":"key :can_palette? not found"},"sound":"default"},"event_id":"evt_REPLACE","project_id":"prj_REPLACE"}
JSON
xcrun simctl push booted com.example.Boop /tmp/push.json
+
+# With action buttons (long-press the banner; simctl does not run the service
+# extension, so on the simulator the buttons only appear on a real device):
+cat > /tmp/push-actions.json <<'JSON'
+{"aps":{"alert":{"title":"Shop · Payment received","body":"£19.99"},"sound":"default","category":"boop.event.actions","mutable-content":1},
+ "event_id":"evt_REPLACE","project_id":"prj_REPLACE","actions":[{"label":"Open in Stripe","url":"https://dashboard.stripe.com"}]}
+JSON
+xcrun simctl push booted com.example.Boop /tmp/push-actions.json
```
## Tests
diff --git a/ios/project.yml b/ios/project.yml
index ecc31ff..d22b510 100644
--- a/ios/project.yml
+++ b/ios/project.yml
@@ -9,7 +9,7 @@ options:
settings:
base:
SWIFT_VERSION: "6.0"
- MARKETING_VERSION: "1.1.0"
+ MARKETING_VERSION: "1.2.0"
CURRENT_PROJECT_VERSION: "1"
# Users set their own team in Xcode (Signing & Capabilities).
DEVELOPMENT_TEAM: ""
@@ -27,9 +27,12 @@ targets:
- "Resources/Fonts/OFL.txt"
- path: Boop/Resources/Fonts/OFL.txt
buildPhase: none
+ dependencies:
+ - target: BoopNotificationService
settings:
base:
# Change this to your own bundle identifier. It must match APNS_BUNDLE_ID on the server.
+ # The extension below must then be <your id>.NotificationService.
PRODUCT_BUNDLE_IDENTIFIER: com.example.Boop
CODE_SIGN_ENTITLEMENTS: Boop/Boop.entitlements
INFOPLIST_FILE: Boop/Info.plist
@@ -39,6 +42,21 @@ targets:
SUPPORTS_MACCATALYST: NO
INFOPLIST_KEY_UISupportedInterfaceOrientations: UIInterfaceOrientationPortrait
INFOPLIST_KEY_UILaunchScreen_Generation: YES
+ # Turns the `actions` in a push into notification buttons (see NotificationService.swift).
+ BoopNotificationService:
+ type: app-extension
+ platform: iOS
+ sources:
+ - path: BoopNotificationService
+ - path: Boop/Notifications/NotificationActions.swift
+ - path: Boop/Models/EventAction.swift
+ settings:
+ base:
+ PRODUCT_BUNDLE_IDENTIFIER: com.example.Boop.NotificationService
+ INFOPLIST_FILE: BoopNotificationService/Info.plist
+ GENERATE_INFOPLIST_FILE: NO
+ SKIP_INSTALL: YES
+ TARGETED_DEVICE_FAMILY: "1"
BoopTests:
type: bundle.unit-test
platform: iOS
@@ -65,6 +83,7 @@ schemes:
build:
targets:
Boop: all
+ BoopNotificationService: all
BoopTests: [test]
BoopUITests: [test]
run:
diff --git a/server/Dockerfile b/server/Dockerfile
index 5a90666..9730b60 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -16,7 +16,7 @@ COPY go.mod go.sum ./
RUN go mod download
COPY . .
COPY --from=web /internal/web/dist ./internal/web/dist
-ARG VERSION=1.1.0
+ARG VERSION=1.2.0
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X github.com/chrisgreg/boop/server/internal/api.Version=${VERSION}" -o /boop ./cmd/boop
# ---- runtime: binary + CA certificates only ----
diff --git a/server/go.mod b/server/go.mod
index 484c0f5..f357f18 100644
--- a/server/go.mod
+++ b/server/go.mod
@@ -2,15 +2,25 @@ module github.com/chrisgreg/boop/server
go 1.27.0
-require modernc.org/sqlite v1.57.0
+require (
+ github.com/modelcontextprotocol/go-sdk v1.7.0
+ modernc.org/sqlite v1.57.0
+)
require (
github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/google/jsonschema-go v0.4.3 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/segmentio/asm v1.1.3 // indirect
+ github.com/segmentio/encoding v0.5.4 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
+ golang.org/x/oauth2 v0.35.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.47.0 // indirect
+ golang.org/x/time v0.15.0 // indirect
modernc.org/libc v1.74.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
diff --git a/server/go.sum b/server/go.sum
index 3efffe8..d548106 100644
--- a/server/go.sum
+++ b/server/go.sum
@@ -1,5 +1,11 @@
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
+github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -8,16 +14,28 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
+github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
+github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
+github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
+golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
diff --git a/server/internal/api/api.go b/server/internal/api/api.go
index 4599a5e..c53cb38 100644
--- a/server/internal/api/api.go
+++ b/server/internal/api/api.go
@@ -21,6 +21,7 @@ import (
"github.com/chrisgreg/boop/server/internal/events"
"github.com/chrisgreg/boop/server/internal/events/levels"
"github.com/chrisgreg/boop/server/internal/events/redact"
+ "github.com/chrisgreg/boop/server/internal/mcp"
"github.com/chrisgreg/boop/server/internal/pairing"
"github.com/chrisgreg/boop/server/internal/projects"
"github.com/chrisgreg/boop/server/internal/settings"
@@ -28,7 +29,7 @@ import (
)
// Version is the server version, overridden at build time via -ldflags.
-var Version = "1.1.0"
+var Version = "1.2.0"
// Server holds every dependency the handlers need.
type Server struct {
@@ -97,6 +98,9 @@ func (s *Server) Handler() http.Handler {
mux.Handle("PATCH /api/v1/settings", s.adminAuth(s.updateSettings))
mux.Handle("POST /api/v1/test", s.adminAuth(s.testNotification))
+ // MCP (read-only) for AI agents: Streamable HTTP at /mcp.
+ mux.Handle("/mcp", s.mcpAuth(mcp.Handler(mcp.NewServer(mcp.Stores{Projects: s.Projects, Events: s.Events}, Version), s.Log)))
+
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "not_found", "no such endpoint")
})
@@ -192,6 +196,40 @@ func (s *Server) readerAuth(next http.HandlerFunc) http.Handler {
})
}
+// mcpAuth guards the MCP endpoint. It accepts the configured BOOP_MCP_TOKEN,
+// a device credential, or an admin session/HTTP Basic login (or nothing when
+// admin auth is off, like the rest of the read API). Project API keys are
+// refused: they are write-only ingestion credentials.
+func (s *Server) mcpAuth(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if on, err := s.mcpEnabled(r.Context()); err != nil {
+ s.fail(w, err)
+ return
+ } else if !on {
+ writeError(w, http.StatusNotFound, "mcp_disabled", "the MCP endpoint is turned off in Settings")
+ return
+ }
+ cred := auth.Bearer(r)
+ switch {
+ case cred == "":
+ if !s.Admin.Authorized(r) {
+ writeError(w, http.StatusUnauthorized, "unauthorized", "an MCP token (BOOP_MCP_TOKEN) or device credential is required: Authorization: Bearer ...")
+ return
+ }
+ case s.Config.MCPToken != "" && auth.Equal(auth.Hash(cred), auth.Hash(s.Config.MCPToken)):
+ case auth.HasPrefix(cred, auth.PrefixDevice):
+ if _, err := s.Devices.Authenticate(r.Context(), cred); err != nil {
+ writeError(w, http.StatusUnauthorized, "unauthorized", "invalid device credential")
+ return
+ }
+ default:
+ writeError(w, http.StatusUnauthorized, "unauthorized", "invalid MCP credential")
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
// adminAuth serves the web UI and admin API. When BOOP_ADMIN_USER/PASSWORD are
// set, a session cookie (from /auth/login) or HTTP Basic credentials are
// required; otherwise it is open and expected to sit behind the operator's own
@@ -436,12 +474,22 @@ type settingsResponse struct {
RedactKeys []string `json:"redact_keys"`
DefaultRedact []string `json:"default_redact_keys"`
SetupCompleted bool `json:"setup_completed"`
+ MCPEnabled bool `json:"mcp_enabled"`
+ // MCPTokenSet reports whether BOOP_MCP_TOKEN is configured (never the token itself).
+ MCPTokenSet bool `json:"mcp_token_set"`
}
type settingsInput struct {
RetentionDays *int `json:"retention_days"`
RedactKeys *[]string `json:"redact_keys"`
SetupCompleted *bool `json:"setup_completed"`
+ MCPEnabled *bool `json:"mcp_enabled"`
+}
+
+// mcpEnabled reads the MCP switch; it defaults to on.
+func (s *Server) mcpEnabled(ctx context.Context) (bool, error) {
+ v, err := s.Settings.Get(ctx, settings.KeyMCPEnabled, "true")
+ return v != "false" && v != "0", err
}
func (s *Server) readSettings(ctx context.Context) (settingsResponse, error) {
@@ -457,7 +505,11 @@ func (s *Server) readSettings(ctx context.Context) (settingsResponse, error) {
out.RedactKeys = []string{}
}
out.DefaultRedact = redact.DefaultKeys
- out.SetupCompleted, err = s.Settings.GetBool(ctx, settings.KeySetupCompleted)
+ if out.SetupCompleted, err = s.Settings.GetBool(ctx, settings.KeySetupCompleted); err != nil {
+ return out, err
+ }
+ out.MCPTokenSet = s.Config.MCPToken != ""
+ out.MCPEnabled, err = s.mcpEnabled(ctx)
return out, err
}
@@ -508,6 +560,13 @@ func (s *Server) updateSettings(w http.ResponseWriter, r *http.Request) {
return
}
}
+ if in.MCPEnabled != nil {
+ if err := s.Settings.Set(ctx, settings.KeyMCPEnabled, strconv.FormatBool(*in.MCPEnabled)); err != nil {
+ s.fail(w, err)
+ return
+ }
+ s.Log.Info("settings.mcp", "enabled", *in.MCPEnabled)
+ }
out, err := s.readSettings(ctx)
if err != nil {
s.fail(w, err)
@@ -538,7 +597,8 @@ func (s *Server) createEvent(w http.ResponseWriter, r *http.Request) {
func (s *Server) listEvents(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
- f := events.Filter{ProjectID: q.Get("project"), Level: q.Get("level"), Source: q.Get("source"), Before: q.Get("before")}
+ f := events.Filter{ProjectID: q.Get("project"), Level: q.Get("level"), Source: q.Get("source"), Fingerprint: q.Get("fingerprint"), Before: q.Get("before"),
+ Since: q.Get("since"), Until: q.Get("until"), Grouped: q.Get("grouped") == "true" || q.Get("grouped") == "1"}
if f.Level != "" && !levels.Valid(f.Level) {
writeError(w, http.StatusUnprocessableEntity, "invalid", "level must be one of "+strings.Join(levels.All, ", "))
return
diff --git a/server/internal/api/api_test.go b/server/internal/api/api_test.go
index 556d901..de022a7 100644
--- a/server/internal/api/api_test.go
+++ b/server/internal/api/api_test.go
@@ -971,3 +971,300 @@ func TestSilences(t *testing.T) {
t.Errorf("after unsilence: %s", r.raw)
}
}
+
+func TestEventActions(t *testing.T) {
+ e := newEnv(t)
+ _, key := e.createProject("Shop")
+ _, c1 := e.pairDevice("phone")
+ e.do("POST", "/api/v1/devices", c1, map[string]string{"device_token": "t1"})
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ e.server.Dispatcher.Start(ctx)
+
+ body := `{"title":"Payment received","body":"£19.99","level":"success","actions":[{"label":" Open in Stripe ","url":"https://dashboard.stripe.com/payments/pi_1"},{"label":"Open app","url":"myshop://orders/42"}]}`
+ r := e.do("POST", "/api/v1/events", key, body)
+ if r.status != 201 {
+ t.Fatalf("create: %d %s", r.status, r.raw)
+ }
+ id := r.body["id"].(string)
+ r = e.do("GET", "/api/v1/events/"+id, "", nil)
+ acts, _ := r.body["actions"].([]any)
+ if len(acts) != 2 || acts[0].(map[string]any)["label"] != "Open in Stripe" || acts[1].(map[string]any)["url"] != "myshop://orders/42" {
+ t.Fatalf("actions round trip: %s", r.raw)
+ }
+ // Events without actions omit the key entirely.
+ r = e.do("POST", "/api/v1/events", key, `{"title":"plain"}`)
+ r = e.do("GET", "/api/v1/events/"+r.body["id"].(string), "", nil)
+ if _, ok := r.body["actions"]; ok {
+ t.Errorf("plain event should omit actions: %s", r.raw)
+ }
+ // Grouped/ungrouped listings carry them too.
+ r = e.do("GET", "/api/v1/events?level=success", "", nil)
+ if ev := r.body["events"].([]any)[0].(map[string]any); len(ev["actions"].([]any)) != 2 {
+ t.Errorf("list actions: %s", r.raw)
+ }
+
+ // The push carries the actions and asks for the actions category.
+ deadline := time.Now().Add(3 * time.Second)
+ for len(e.sender.sent) < 1 && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if len(e.sender.sent) < 1 {
+ t.Fatal("no push sent")
+ }
+ n := e.sender.sent[0].n
+ if len(n.Actions) != 2 || n.Actions[0].Label != "Open in Stripe" {
+ t.Errorf("push actions = %+v", n.Actions)
+ }
+ payload, _ := apns.Payload(n)
+ var p map[string]any
+ _ = json.Unmarshal(payload, &p)
+ aps := p["aps"].(map[string]any)
+ if aps["category"] != apns.CategoryWithActions || aps["mutable-content"] != float64(1) || len(p["actions"].([]any)) != 2 {
+ t.Errorf("payload: %s", payload)
+ }
+ plain, _ := apns.Payload(apns.Notification{Title: "t", Body: "b"})
+ if strings.Contains(string(plain), "category") || strings.Contains(string(plain), "actions") {
+ t.Errorf("payload without actions must not set a category: %s", plain)
+ }
+
+ // Validation.
+ bad := []string{
+ `{"title":"x","actions":[{"label":"","url":"https://a"}]}`,
+ `{"title":"x","actions":[{"label":"a","url":""}]}`,
+ `{"title":"x","actions":[{"label":"a","url":"/relative"}]}`,
+ `{"title":"x","actions":[{"label":"a","url":"javascript:alert(1)"}]}`,
+ `{"title":"x","actions":[{"label":"a","url":"DATA:text/html,hi"}]}`,
+ `{"title":"x","actions":[{"label":"` + strings.Repeat("l", 41) + `","url":"https://a"}]}`,
+ `{"title":"x","actions":[{"label":"1","url":"https://a"},{"label":"2","url":"https://a"},{"label":"3","url":"https://a"},{"label":"4","url":"https://a"}]}`,
+ }
+ for _, b := range bad {
+ if r := e.do("POST", "/api/v1/events", key, b); r.status != 422 {
+ t.Errorf("%s: want 422, got %d %s", b, r.status, r.raw)
+ }
+ }
+}
+
+func TestGroupedListing(t *testing.T) {
+ e := newEnv(t)
+ p1, k1 := e.createProject("Uini")
+ _, k2 := e.createProject("Infra")
+ post := func(key, title, level, fp string) string {
+ t.Helper()
+ r := e.do("POST", "/api/v1/events", key, map[string]string{"title": title, "level": level, "fingerprint": fp})
+ if r.status != 201 {
+ t.Fatalf("post %s: %d %s", title, r.status, r.raw)
+ }
+ return r.body["id"].(string)
+ }
+ var keyErrIDs []string
+ for i := 0; i < 5; i++ {
+ keyErrIDs = append(keyErrIDs, post(k1, "KeyError", "error", "keyerror"))
+ }
+ post(k1, "Deploy done", "success", "") // no fingerprint: never grouped
+ post(k1, "Timeout", "warning", "timeout")
+ post(k1, "Timeout", "info", "timeout") // same fingerprint, different level, latest
+ post(k2, "KeyError", "error", "keyerror") // same fingerprint, other project
+ post(k1, "Deploy done", "success", "")
+
+ // Ungrouped: everything.
+ r := e.do("GET", "/api/v1/events", "", nil)
+ if n := len(r.body["events"].([]any)); n != 10 {
+ t.Fatalf("ungrouped: %d", n)
+ }
+ if _, ok := r.body["events"].([]any)[0].(map[string]any)["group"]; ok {
+ t.Errorf("ungrouped rows must not carry group info")
+ }
+
+ // Grouped: 5 KeyErrors collapse, the two Timeouts collapse, plain events stay, other project separate.
+ r = e.do("GET", "/api/v1/events?grouped=true", "", nil)
+ evs := r.body["events"].([]any)
+ var titles []string
+ byFp := map[string]map[string]any{}
+ for _, x := range evs {
+ ev := x.(map[string]any)
+ titles = append(titles, ev["title"].(string)+"@"+ev["project_name"].(string))
+ if fp, _ := ev["fingerprint"].(string); fp != "" {
+ byFp[ev["project_id"].(string)+"/"+fp] = ev
+ }
+ }
+ if len(evs) != 5 || strings.Join(titles, ",") != "Deploy done@Uini,KeyError@Infra,Timeout@Uini,Deploy done@Uini,KeyError@Uini" {
+ t.Fatalf("grouped rows: %v\n%s", titles, r.raw)
+ }
+ ke := byFp[p1+"/keyerror"]
+ g := ke["group"].(map[string]any)
+ if g["count"] != float64(5) || ke["id"] != keyErrIDs[4] {
+ t.Errorf("keyerror group: %v (id %v, want %s)", g, ke["id"], keyErrIDs[4])
+ }
+ if g["first_seen"].(string) >= g["last_seen"].(string) {
+ t.Errorf("first_seen %v should precede last_seen %v", g["first_seen"], g["last_seen"])
+ }
+ // The other project's identical fingerprint is its own group of one.
+ for _, x := range evs {
+ ev := x.(map[string]any)
+ if ev["project_name"] == "Infra" && ev["group"].(map[string]any)["count"] != float64(1) {
+ t.Errorf("cross-project grouping: %v", ev["group"])
+ }
+ if ev["fingerprint"] == "" {
+ if _, ok := ev["group"]; ok {
+ t.Errorf("unfingerprinted event carries group: %v", ev)
+ }
+ }
+ }
+ if byFp[p1+"/timeout"]["group"].(map[string]any)["count"] != float64(2) || byFp[p1+"/timeout"]["level"] != "info" {
+ t.Errorf("timeout group should be latest (info) of 2: %v", byFp[p1+"/timeout"])
+ }
+
+ // Filters apply inside the group: level=warning shows the warning Timeout with count 1.
+ r = e.do("GET", "/api/v1/events?grouped=true&level=warning", "", nil)
+ evs = r.body["events"].([]any)
+ if len(evs) != 1 || evs[0].(map[string]any)["level"] != "warning" || evs[0].(map[string]any)["group"].(map[string]any)["count"] != float64(1) {
+ t.Errorf("filtered group: %s", r.raw)
+ }
+
+ // Cursor pagination in grouped mode never repeats a group and reaches everything.
+ var seen []string
+ cursor := ""
+ for pages := 0; pages < 10; pages++ {
+ url := "/api/v1/events?grouped=true&limit=2"
+ if cursor != "" {
+ url += "&before=" + cursor
+ }
+ r = e.do("GET", url, "", nil)
+ for _, ev := range r.body["events"].([]any) {
+ m := ev.(map[string]any)
+ seen = append(seen, m["title"].(string)+"@"+m["project_name"].(string))
+ }
+ c, _ := r.body["next_cursor"].(string)
+ if c == "" {
+ break
+ }
+ cursor = c
+ }
+ if strings.Join(seen, ",") != strings.Join(titles, ",") {
+ t.Errorf("paged grouped: %v want %v", seen, titles)
+ }
+
+ // Occurrences: filter by fingerprint (and project) in ungrouped mode.
+ r = e.do("GET", "/api/v1/events?project="+p1+"&fingerprint=keyerror", "", nil)
+ if n := len(r.body["events"].([]any)); n != 5 {
+ t.Errorf("occurrences: %d %s", n, r.raw)
+ }
+ r = e.do("GET", "/api/v1/events?fingerprint=keyerror", "", nil)
+ if n := len(r.body["events"].([]any)); n != 6 {
+ t.Errorf("occurrences across projects: %d", n)
+ }
+
+ // since/until window on created_at.
+ mid := byFp[p1+"/keyerror"]["created_at"].(string)
+ r = e.do("GET", "/api/v1/events?since="+mid, "", nil)
+ if n := len(r.body["events"].([]any)); n != 6 { // the latest KeyError + 5 after it
+ t.Errorf("since: %d %s", n, r.raw)
+ }
+ r = e.do("GET", "/api/v1/events?until="+mid, "", nil)
+ if n := len(r.body["events"].([]any)); n != 4 {
+ t.Errorf("until: %d", n)
+ }
+ if r := e.do("GET", "/api/v1/events?since=yesterday", "", nil); r.status != 422 {
+ t.Errorf("bad since: %d", r.status)
+ }
+}
+
+// mcpCall performs a raw JSON-RPC tools/call against /mcp with the given bearer.
+func (e *env) mcpCall(bearer, tool string, args map[string]any) resp {
+ e.t.Helper()
+ body := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": map[string]any{"name": tool, "arguments": args}}
+ buf, _ := json.Marshal(body)
+ req, _ := http.NewRequest("POST", e.srv.URL+"/mcp", bytes.NewReader(buf))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ if bearer != "" {
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ }
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ e.t.Fatal(err)
+ }
+ defer res.Body.Close()
+ raw, _ := io.ReadAll(res.Body)
+ out := resp{status: res.StatusCode, raw: raw}
+ _ = json.Unmarshal(raw, &out.body)
+ return out
+}
+
+func TestMCPEndpointAuth(t *testing.T) {
+ e := newEnv(t)
+ _, projKey := e.createProject("Uini")
+ _, devCred := e.pairDevice("phone")
+ e.do("POST", "/api/v1/events", projKey, map[string]string{"title": "hello"})
+ // Lock the server down: admin login required, MCP token configured.
+ e.server.Config.MCPToken = "boop_mcp_test_token_1234"
+ e.server.Admin = auth.NewAdmin("admin", "correct horse battery")
+
+ cases := []struct {
+ name string
+ bearer string
+ want int
+ }{
+ {"no credential", "", 401},
+ {"junk", "nope", 401},
+ {"wrong mcp token", "boop_mcp_test_token_9999", 401},
+ {"project key is refused", projKey, 401},
+ {"mcp token", "boop_mcp_test_token_1234", 200},
+ {"device credential", devCred, 200},
+ }
+ for _, c := range cases {
+ r := e.mcpCall(c.bearer, "list_projects", nil)
+ if r.status != c.want {
+ t.Errorf("%s: %d %s", c.name, r.status, r.raw)
+ }
+ }
+ // A successful call really returns data.
+ r := e.mcpCall("boop_mcp_test_token_1234", "list_events", map[string]any{"limit": 5})
+ if !strings.Contains(string(r.raw), `"hello"`) || strings.Contains(string(r.raw), "isError") {
+ t.Errorf("mcp result: %s", r.raw)
+ }
+ // Admin HTTP Basic works on the endpoint when auth is enabled.
+ req, _ := http.NewRequest("POST", e.srv.URL+"/mcp", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ req.SetBasicAuth("admin", "correct horse battery")
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != 200 {
+ t.Errorf("basic auth: %d", res.StatusCode)
+ }
+
+ // With admin auth off and no token, /mcp is open like the rest of the read API.
+ e.server.Admin = auth.NewAdmin("", "")
+ e.server.Config.MCPToken = ""
+ if r := e.mcpCall("", "list_projects", nil); r.status != 200 {
+ t.Errorf("open mode: %d %s", r.status, r.raw)
+ }
+ if r := e.mcpCall(projKey, "list_projects", nil); r.status != 401 {
+ t.Errorf("project key must still be refused in open mode: %d", r.status)
+ }
+
+ // The Settings switch turns the endpoint off entirely (even with a valid credential).
+ r = e.do("GET", "/api/v1/settings", "", nil)
+ if r.body["mcp_enabled"] != true || r.body["mcp_token_set"] != false {
+ t.Errorf("settings default: %s", r.raw)
+ }
+ if r := e.do("PATCH", "/api/v1/settings", "", map[string]any{"mcp_enabled": false}); r.status != 200 || r.body["mcp_enabled"] != false {
+ t.Fatalf("disable: %d %s", r.status, r.raw)
+ }
+ if r := e.mcpCall(devCred, "list_projects", nil); r.status != 404 || r.body["error"] != "mcp_disabled" {
+ t.Errorf("disabled: %d %s", r.status, r.raw)
+ }
+ e.do("PATCH", "/api/v1/settings", "", map[string]any{"mcp_enabled": true})
+ if r := e.mcpCall(devCred, "list_projects", nil); r.status != 200 {
+ t.Errorf("re-enabled: %d", r.status)
+ }
+ e.server.Config.MCPToken = "boop_mcp_test_token_1234"
+ if r := e.do("GET", "/api/v1/settings", "", nil); r.body["mcp_token_set"] != true || strings.Contains(string(r.raw), "boop_mcp_test_token_1234") {
+ t.Errorf("token flag must be reported without the token: %s", r.raw)
+ }
+}
diff --git a/server/internal/apns/apns.go b/server/internal/apns/apns.go
index 0b15482..ba519b4 100644
--- a/server/internal/apns/apns.go
+++ b/server/internal/apns/apns.go
@@ -43,6 +43,41 @@ type Notification struct {
ProjectID string
// Prominent asks for a time-sensitive, high-priority alert (critical events).
Prominent bool
+ // Actions are shown as buttons on the notification (long press / pull down).
+ Actions []Action
+}
+
+// Action is a notification button that opens a URL.
+type Action struct {
+ Label string `json:"label"`
+ URL string `json:"url"`
+}
+
+// CategoryWithActions is the aps.category set when a notification carries
+// actions. The app's notification service extension registers a matching
+// category with the real labels before the alert is shown.
+const CategoryWithActions = "boop.event.actions"
+
+// Payload builds the APNs JSON body for n.
+func Payload(n Notification) ([]byte, error) {
+ aps := map[string]any{
+ "alert": map[string]string{"title": n.Title, "body": n.Body},
+ "sound": "default",
+ }
+ if n.Prominent {
+ aps["interruption-level"] = "time-sensitive"
+ }
+ payload := map[string]any{
+ "aps": aps,
+ "event_id": n.EventID,
+ "project_id": n.ProjectID,
+ }
+ if len(n.Actions) > 0 {
+ aps["category"] = CategoryWithActions
+ aps["mutable-content"] = 1
+ payload["actions"] = n.Actions
+ }
+ return json.Marshal(payload)
}
// Error is a non-2xx response from APNs.
@@ -182,18 +217,7 @@ func (c *Client) Send(ctx context.Context, deviceToken string, n Notification) (
}
func (c *Client) send(ctx context.Context, deviceToken string, n Notification) (string, error) {
- payload := map[string]any{
- "aps": map[string]any{
- "alert": map[string]string{"title": n.Title, "body": n.Body},
- "sound": "default",
- },
- "event_id": n.EventID,
- "project_id": n.ProjectID,
- }
- if n.Prominent {
- payload["aps"].(map[string]any)["interruption-level"] = "time-sensitive"
- }
- body, err := json.Marshal(payload)
+ body, err := Payload(n)
if err != nil {
return "", err
}
diff --git a/server/internal/config/config.go b/server/internal/config/config.go
index 75fd538..fc500b1 100644
--- a/server/internal/config/config.go
+++ b/server/internal/config/config.go
@@ -23,6 +23,10 @@ type Config struct {
AdminUser string
AdminPassword string
+ // MCPToken, when set, is a bearer token that grants read-only access to the
+ // MCP endpoint (/mcp). Device credentials and admin logins work there too.
+ MCPToken string
+
APNS APNS
}
@@ -69,6 +73,7 @@ func Load() (Config, error) {
LogLevel: env("BOOP_LOG_LEVEL", "info"),
AdminUser: env("BOOP_ADMIN_USER", ""),
AdminPassword: env("BOOP_ADMIN_PASSWORD", ""),
+ MCPToken: strings.TrimSpace(env("BOOP_MCP_TOKEN", "")),
APNS: APNS{
TeamID: env("APNS_TEAM_ID", ""),
KeyID: env("APNS_KEY_ID", ""),
@@ -100,6 +105,9 @@ func Load() (Config, error) {
if c.AdminPassword != "" && len(c.AdminPassword) < 8 {
return c, fmt.Errorf("BOOP_ADMIN_PASSWORD must be at least 8 characters")
}
+ if c.MCPToken != "" && len(c.MCPToken) < 16 {
+ return c, fmt.Errorf("BOOP_MCP_TOKEN must be at least 16 characters")
+ }
if c.APNS.Environment != "production" && c.APNS.Environment != "sandbox" {
return c, fmt.Errorf("APNS_ENVIRONMENT must be production or sandbox, got %q", c.APNS.Environment)
}
diff --git a/server/internal/delivery/delivery.go b/server/internal/delivery/delivery.go
index 68a56d7..28a0c6e 100644
--- a/server/internal/delivery/delivery.go
+++ b/server/internal/delivery/delivery.go
@@ -112,6 +112,9 @@ func (d *Dispatcher) Deliver(ctx context.Context, e events.Event, p projects.Pro
ProjectID: p.ID,
Prominent: e.Level == levels.Critical,
}
+ for _, a := range e.Actions {
+ n.Actions = append(n.Actions, apns.Action{Label: a.Label, URL: a.URL})
+ }
if n.Body == "" {
n.Body = e.Title
n.Title = p.Name
diff --git a/server/internal/events/events.go b/server/internal/events/events.go
index 903602e..a664b78 100644
--- a/server/internal/events/events.go
+++ b/server/internal/events/events.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net/url"
"strings"
"time"
@@ -23,12 +24,58 @@ var ErrInvalid = errors.New("invalid event")
// Limits.
const (
- MaxTitle = 200
- MaxBody = 4000
- MaxDataSize = 256 * 1024
- MaxLimit = 200
+ MaxTitle = 200
+ MaxBody = 4000
+ MaxDataSize = 256 * 1024
+ MaxLimit = 200
+ MaxActions = 3
+ MaxActionLabel = 40
+ MaxActionURL = 2048
)
+// Action is a button attached to an event: on the phone it appears on the
+// notification and in the event detail; on the web in the event detail.
+type Action struct {
+ Label string `json:"label"`
+ URL string `json:"url"`
+}
+
+// blockedSchemes are never allowed in action URLs.
+var blockedSchemes = map[string]bool{"javascript": true, "data": true, "file": true, "vbscript": true}
+
+// validateActions normalises and checks a list of actions.
+func validateActions(in []Action) ([]Action, error) {
+ if len(in) > MaxActions {
+ return nil, fmt.Errorf("%w: at most %d actions are allowed", ErrInvalid, MaxActions)
+ }
+ out := make([]Action, 0, len(in))
+ for _, a := range in {
+ a.Label = strings.TrimSpace(a.Label)
+ a.URL = strings.TrimSpace(a.URL)
+ if a.Label == "" {
+ return nil, fmt.Errorf("%w: action label is required", ErrInvalid)
+ }
+ if len(a.Label) > MaxActionLabel {
+ return nil, fmt.Errorf("%w: action label must be %d characters or fewer", ErrInvalid, MaxActionLabel)
+ }
+ if a.URL == "" {
+ return nil, fmt.Errorf("%w: action url is required", ErrInvalid)
+ }
+ if len(a.URL) > MaxActionURL {
+ return nil, fmt.Errorf("%w: action url must be %d characters or fewer", ErrInvalid, MaxActionURL)
+ }
+ u, err := url.Parse(a.URL)
+ if err != nil || u.Scheme == "" {
+ return nil, fmt.Errorf("%w: action url must be absolute (https://... or an app scheme)", ErrInvalid)
+ }
+ if blockedSchemes[strings.ToLower(u.Scheme)] {
+ return nil, fmt.Errorf("%w: action url scheme %q is not allowed", ErrInvalid, u.Scheme)
+ }
+ out = append(out, a)
+ }
+ return out, nil
+}
+
// Input is the inbound event envelope.
type Input struct {
ExternalID string `json:"external_id"`
@@ -40,6 +87,7 @@ type Input struct {
Fingerprint string `json:"fingerprint"`
OccurredAt string `json:"occurred_at"`
Data json.RawMessage `json:"data"`
+ Actions []Action `json:"actions"`
}
// Event is a stored event.
@@ -57,21 +105,41 @@ type Event struct {
Body string `json:"body"`
Fingerprint string `json:"fingerprint"`
Data json.RawMessage `json:"data"`
+ Actions []Action `json:"actions,omitempty"`
OccurredAt string `json:"occurred_at"`
CreatedAt string `json:"created_at"`
// SilenceID is set when a silence rule stopped this event from being pushed.
SilenceID string `json:"silence_id,omitempty"`
Silenced bool `json:"silenced"`
+ // Group is set in grouped listings for events that carry a fingerprint: this
+ // event is the latest of Count occurrences sharing (project, fingerprint).
+ Group *GroupInfo `json:"group,omitempty"`
+}
+
+// GroupInfo summarises the occurrences behind a grouped row.
+type GroupInfo struct {
+ Count int `json:"count"`
+ FirstSeen string `json:"first_seen"`
+ LastSeen string `json:"last_seen"`
}
// Filter narrows List.
type Filter struct {
- ProjectID string
- Level string
- Source string
- Before string // cursor: id of the last event seen
- Limit int
- Silenced *bool // nil = any
+ ProjectID string
+ Level string
+ Source string
+ Fingerprint string
+ Before string // cursor: id of the last event seen
+ Limit int
+ Silenced *bool // nil = any
+ Since string // created_at >= (TimeLayout or RFC 3339)
+ Until string // created_at < (TimeLayout or RFC 3339)
+ // Query is a case-insensitive substring match over title, body, source,
+ // fingerprint and the data payload.
+ Query string
+ // Grouped collapses events sharing a non-empty fingerprint within a project
+ // into one row (the latest occurrence) annotated with Group.
+ Grouped bool
}
// Page is a page of events plus the cursor for the next page ("" when exhausted).
@@ -123,6 +191,12 @@ func Validate(in Input, r *redact.Redactor) (Input, []byte, error) {
in.OccurredAt = ids.Format(t)
}
+ actions, err := validateActions(in.Actions)
+ if err != nil {
+ return in, nil, err
+ }
+ in.Actions = actions
+
data := []byte("{}")
if len(in.Data) > 0 && string(in.Data) != "null" {
if len(in.Data) > MaxDataSize {
@@ -158,69 +232,159 @@ func (s *Store) Create(ctx context.Context, projectID string, in Input, r *redac
Body: in.Body,
Fingerprint: in.Fingerprint,
Data: data,
+ Actions: in.Actions,
OccurredAt: in.OccurredAt,
CreatedAt: ids.Now(),
}
+ actionsJSON := "[]"
+ if len(e.Actions) > 0 {
+ b, err := json.Marshal(e.Actions)
+ if err != nil {
+ return Event{}, err
+ }
+ actionsJSON = string(b)
+ }
_, err = s.db.ExecContext(ctx, `INSERT INTO events
- (id, external_id, project_id, source, type, level, title, body, fingerprint, payload_json, occurred_at, created_at)
- VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
- e.ID, nullable(e.ExternalID), e.ProjectID, e.Source, e.Type, e.Level, e.Title, e.Body, e.Fingerprint, string(e.Data), e.OccurredAt, e.CreatedAt)
+ (id, external_id, project_id, source, type, level, title, body, fingerprint, payload_json, actions_json, occurred_at, created_at)
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+ e.ID, nullable(e.ExternalID), e.ProjectID, e.Source, e.Type, e.Level, e.Title, e.Body, e.Fingerprint, string(e.Data), actionsJSON, e.OccurredAt, e.CreatedAt)
if err != nil {
return Event{}, err
}
return s.Get(ctx, e.ID)
}
-const selectCols = `e.id, COALESCE(e.external_id, ''), e.project_id, p.name, p.slug, p.icon, e.source, e.type, e.level, e.title, e.body, e.fingerprint, e.payload_json, e.occurred_at, e.created_at, COALESCE(e.silence_id, '')
- FROM events e JOIN projects p ON p.id = e.project_id`
+const selectCols = `e.id, COALESCE(e.external_id, ''), e.project_id, p.name, p.slug, p.icon, e.source, e.type, e.level, e.title, e.body, e.fingerprint, e.payload_json, e.actions_json, e.occurred_at, e.created_at, COALESCE(e.silence_id, '')`
+
+const fromClause = ` FROM events e JOIN projects p ON p.id = e.project_id`
-func scan(row interface{ Scan(...any) error }) (Event, error) {
+func scan(row interface{ Scan(...any) error }, extra ...any) (Event, error) {
var e Event
- var data string
- err := row.Scan(&e.ID, &e.ExternalID, &e.ProjectID, &e.ProjectName, &e.ProjectSlug, &e.ProjectIcon, &e.Source, &e.Type, &e.Level, &e.Title, &e.Body, &e.Fingerprint, &data, &e.OccurredAt, &e.CreatedAt, &e.SilenceID)
+ var data, actions string
+ dest := []any{&e.ID, &e.ExternalID, &e.ProjectID, &e.ProjectName, &e.ProjectSlug, &e.ProjectIcon, &e.Source, &e.Type, &e.Level, &e.Title, &e.Body, &e.Fingerprint, &data, &actions, &e.OccurredAt, &e.CreatedAt, &e.SilenceID}
+ dest = append(dest, extra...)
+ err := row.Scan(dest...)
e.Data = json.RawMessage(data)
e.Silenced = e.SilenceID != ""
+ if actions != "" && actions != "[]" {
+ _ = json.Unmarshal([]byte(actions), &e.Actions)
+ }
return e, err
}
// Get returns one event.
func (s *Store) Get(ctx context.Context, id string) (Event, error) {
- e, err := scan(s.db.QueryRowContext(ctx, `SELECT `+selectCols+` WHERE e.id = ?`, id))
+ e, err := scan(s.db.QueryRowContext(ctx, `SELECT `+selectCols+fromClause+` WHERE e.id = ?`, id))
if errors.Is(err, sql.ErrNoRows) {
return Event{}, ErrNotFound
}
return e, err
}
-// List returns events newest-first using keyset pagination on (created_at, id).
-func (s *Store) List(ctx context.Context, f Filter) (Page, error) {
- if f.Limit <= 0 {
- f.Limit = 50
- }
- if f.Limit > MaxLimit {
- f.Limit = MaxLimit
- }
- where := []string{"1=1"}
- args := []any{}
+// filterClause builds the WHERE fragments for f (cursor excluded) against
+// the events table aliased as alias.
+func filterClause(f Filter, alias string) (where []string, args []any) {
+ a := alias + "."
if f.ProjectID != "" {
- where = append(where, "(e.project_id = ? OR p.slug = ?)")
- args = append(args, f.ProjectID, f.ProjectID)
+ // p is the joined projects row; only the outer query has it.
+ if alias == "e" {
+ where = append(where, "("+a+"project_id = ? OR p.slug = ?)")
+ args = append(args, f.ProjectID, f.ProjectID)
+ } else {
+ where = append(where, "("+a+"project_id = ? OR "+a+"project_id IN (SELECT id FROM projects WHERE slug = ?))")
+ args = append(args, f.ProjectID, f.ProjectID)
+ }
}
if f.Level != "" {
- where = append(where, "e.level = ?")
+ where = append(where, a+"level = ?")
args = append(args, f.Level)
}
if f.Source != "" {
- where = append(where, "e.source = ?")
+ where = append(where, a+"source = ?")
args = append(args, f.Source)
}
+ if f.Fingerprint != "" {
+ where = append(where, a+"fingerprint = ?")
+ args = append(args, f.Fingerprint)
+ }
if f.Silenced != nil {
if *f.Silenced {
- where = append(where, "e.silence_id IS NOT NULL")
+ where = append(where, a+"silence_id IS NOT NULL")
} else {
- where = append(where, "e.silence_id IS NULL")
+ where = append(where, a+"silence_id IS NULL")
}
}
+ if f.Since != "" {
+ where = append(where, a+"created_at >= ?")
+ args = append(args, f.Since)
+ }
+ if f.Until != "" {
+ where = append(where, a+"created_at < ?")
+ args = append(args, f.Until)
+ }
+ if f.Query != "" {
+ q := strings.ToLower(strings.TrimSpace(f.Query))
+ where = append(where, "(instr(lower("+a+"title), ?) > 0 OR instr(lower("+a+"body), ?) > 0 OR instr(lower("+a+"source), ?) > 0 OR instr(lower("+a+"fingerprint), ?) > 0 OR instr(lower("+a+"payload_json), ?) > 0)")
+ args = append(args, q, q, q, q, q)
+ }
+ return where, args
+}
+
+// normaliseTime accepts TimeLayout or RFC 3339 and returns TimeLayout, so
+// string comparison against created_at is chronological.
+func normaliseTime(s string) (string, error) {
+ if s == "" {
+ return "", nil
+ }
+ t, err := ids.Parse(s)
+ if err != nil {
+ return "", fmt.Errorf("%w: timestamps must be RFC 3339", ErrInvalid)
+ }
+ return ids.Format(t), nil
+}
+
+// List returns events newest-first using keyset pagination on (created_at, id).
+//
+// With f.Grouped, events that share a non-empty fingerprint within a project
+// collapse into their latest occurrence (respecting the other filters), and
+// each such row carries Group with the occurrence count and first/last seen.
+func (s *Store) List(ctx context.Context, f Filter) (Page, error) {
+ if f.Limit <= 0 {
+ f.Limit = 50
+ }
+ if f.Limit > MaxLimit {
+ f.Limit = MaxLimit
+ }
+ var err error
+ if f.Since, err = normaliseTime(f.Since); err != nil {
+ return Page{}, err
+ }
+ if f.Until, err = normaliseTime(f.Until); err != nil {
+ return Page{}, err
+ }
+ where, args := filterClause(f, "e")
+ where = append([]string{"1=1"}, where...)
+
+ cols := selectCols
+ if f.Grouped {
+ // The same filters apply inside the group so that, say, level=error
+ // shows the latest *error* of a fingerprint and counts only errors.
+ gw, ga := filterClause(f, "x")
+ gw = append([]string{"x.project_id = e.project_id", "x.fingerprint = e.fingerprint"}, gw...)
+ g := strings.Join(gw, " AND ")
+ where = append(where, "(e.fingerprint = '' OR e.id = (SELECT x.id FROM events x WHERE "+g+" ORDER BY x.created_at DESC, x.id DESC LIMIT 1))")
+ // Pre-pend the group-subquery args: the correlated selects come first in the SQL text.
+ cols += `, CASE WHEN e.fingerprint = '' THEN 0 ELSE (SELECT COUNT(*) FROM events x WHERE ` + g + `) END,
+ CASE WHEN e.fingerprint = '' THEN '' ELSE (SELECT MIN(x.created_at) FROM events x WHERE ` + g + `) END,
+ CASE WHEN e.fingerprint = '' THEN '' ELSE (SELECT MAX(x.created_at) FROM events x WHERE ` + g + `) END`
+ var all []any
+ all = append(all, ga...)
+ all = append(all, ga...)
+ all = append(all, ga...)
+ all = append(all, args...)
+ all = append(all, ga...)
+ args = all
+ }
if f.Before != "" {
var createdAt string
err := s.db.QueryRowContext(ctx, `SELECT created_at FROM events WHERE id = ?`, f.Before).Scan(&createdAt)
@@ -234,14 +398,23 @@ func (s *Store) List(ctx context.Context, f Filter) (Page, error) {
args = append(args, createdAt, createdAt, f.Before)
}
args = append(args, f.Limit+1)
- rows, err := s.db.QueryContext(ctx, `SELECT `+selectCols+` WHERE `+strings.Join(where, " AND ")+` ORDER BY e.created_at DESC, e.id DESC LIMIT ?`, args...)
+ rows, err := s.db.QueryContext(ctx, `SELECT `+cols+fromClause+` WHERE `+strings.Join(where, " AND ")+` ORDER BY e.created_at DESC, e.id DESC LIMIT ?`, args...)
if err != nil {
return Page{}, err
}
defer rows.Close()
page := Page{Events: []Event{}}
for rows.Next() {
- e, err := scan(rows)
+ var e Event
+ if f.Grouped {
+ var g GroupInfo
+ e, err = scan(rows, &g.Count, &g.FirstSeen, &g.LastSeen)
+ if err == nil && e.Fingerprint != "" {
+ e.Group = &g
+ }
+ } else {
+ e, err = scan(rows)
+ }
if err != nil {
return Page{}, err
}
diff --git a/server/internal/mcp/mcp.go b/server/internal/mcp/mcp.go
new file mode 100644
index 0000000..2298b12
--- /dev/null
+++ b/server/internal/mcp/mcp.go
@@ -0,0 +1,291 @@
+// Package mcp exposes Boop's stored events to AI agents over the Model
+// Context Protocol. Every tool is read-only: agents can list, search and
+// inspect events and projects, never create or change anything.
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+
+ sdk "github.com/modelcontextprotocol/go-sdk/mcp"
+
+ "github.com/chrisgreg/boop/server/internal/events"
+ "github.com/chrisgreg/boop/server/internal/events/levels"
+ "github.com/chrisgreg/boop/server/internal/projects"
+)
+
+// Stores is what the tools read from.
+type Stores struct {
+ Projects *projects.Store
+ Events *events.Store
+}
+
+// DefaultLimit and MaxLimit bound list sizes so a tool result stays small
+// enough to fit comfortably in an agent's context.
+const (
+ DefaultLimit = 25
+ MaxLimit = 100
+)
+
+// NewServer builds the MCP server with every tool registered.
+func NewServer(st Stores, version string) *sdk.Server {
+ s := sdk.NewServer(&sdk.Implementation{Name: "boop", Title: "Boop", Version: version}, &sdk.ServerOptions{
+ Instructions: "Boop is a self-hosted notification inbox: applications post events (deploys, errors, payments, cron results) and the owner gets a push. " +
+ "These tools are read-only. Events belong to a project; events sharing a fingerprint within a project are the same thing recurring. " +
+ "Timestamps are RFC 3339 in UTC. Start with list_projects, then list_events or search_events, and use get_event for full detail.",
+ })
+ t := &tools{st: st}
+ ro := &sdk.ToolAnnotations{ReadOnlyHint: true, IdempotentHint: true, OpenWorldHint: boolPtr(false)}
+
+ sdk.AddTool(s, &sdk.Tool{Name: "list_projects", Title: "List projects", Annotations: ro,
+ Description: "List every project (an app or service that sends events), with its id and slug. Use the id or slug as the project argument of the other tools."}, t.listProjects)
+ sdk.AddTool(s, &sdk.Tool{Name: "list_events", Title: "List events", Annotations: ro,
+ Description: "List recent events newest first, optionally filtered by project, level, source, fingerprint and a since/until time window (RFC 3339). " +
+ "Set grouped=true to collapse repeated occurrences of the same fingerprint into one row with a count and first/last seen. " +
+ "Results are summaries; call get_event for the full payload. Page with the returned next_cursor as the before argument."}, t.listEvents)
+ sdk.AddTool(s, &sdk.Tool{Name: "get_event", Title: "Get event", Annotations: ro,
+ Description: "Fetch one event by id with its complete data payload (exception, stacktrace, tags, context, breadcrumbs and anything else the sender attached) and actions."}, t.getEvent)
+ sdk.AddTool(s, &sdk.Tool{Name: "search_events", Title: "Search events", Annotations: ro,
+ Description: "Case-insensitive substring search across event titles, bodies, sources, fingerprints and data payloads, newest first. Combine with project, level and since/until to narrow it down."}, t.searchEvents)
+ sdk.AddTool(s, &sdk.Tool{Name: "get_event_group", Title: "Get event group", Annotations: ro,
+ Description: "Everything about one recurring event: the occurrences that share a fingerprint within a project, newest first, with the count and first/last seen. " +
+ "Use the fingerprint from list_events (grouped) or an event."}, t.getEventGroup)
+ return s
+}
+
+// Handler returns an HTTP handler speaking Streamable HTTP. Authentication
+// is the caller's job (wrap it); the handler itself is stateless so any
+// request can be served by any instance without session bookkeeping.
+func Handler(s *sdk.Server, log *slog.Logger) http.Handler {
+ return sdk.NewStreamableHTTPHandler(func(*http.Request) *sdk.Server { return s }, &sdk.StreamableHTTPOptions{
+ Stateless: true, JSONResponse: true, Logger: log,
+ // The SDK's DNS-rebinding guard rejects requests that arrive on loopback
+ // with a non-localhost Host header, which is exactly a reverse proxy on
+ // the same box (nginx/Caddy -> 127.0.0.1:8080). The endpoint is bearer
+ // authenticated and the rest of the API does no origin checks either.
+ DisableLocalhostProtection: true,
+ })
+}
+
+type tools struct{ st Stores }
+
+// ---- list_projects ----
+
+type ListProjectsIn struct{}
+
+type ProjectOut struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Notify bool `json:"notify" jsonschema:"whether pushes are enabled for this project"`
+ MinLevel string `json:"min_level" jsonschema:"lowest level that is pushed to the phone"`
+ CreatedAt string `json:"created_at"`
+}
+
+type ListProjectsOut struct {
+ Projects []ProjectOut `json:"projects"`
+}
+
+func (t *tools) listProjects(ctx context.Context, _ *sdk.CallToolRequest, _ ListProjectsIn) (*sdk.CallToolResult, ListProjectsOut, error) {
+ ps, err := t.st.Projects.List(ctx)
+ if err != nil {
+ return nil, ListProjectsOut{}, err
+ }
+ out := ListProjectsOut{Projects: []ProjectOut{}}
+ for _, p := range ps {
+ out.Projects = append(out.Projects, ProjectOut{ID: p.ID, Name: p.Name, Slug: p.Slug, Notify: p.Notify, MinLevel: p.MinLevel, CreatedAt: p.CreatedAt})
+ }
+ return nil, out, nil
+}
+
+// ---- list_events / search_events ----
+
+type ListEventsIn struct {
+ Project string `json:"project,omitempty" jsonschema:"project id or slug; omit for all projects"`
+ Level string `json:"level,omitempty" jsonschema:"one of info, success, warning, error, critical"`
+ Source string `json:"source,omitempty" jsonschema:"exact source, e.g. error_tracker or github_actions"`
+ Fingerprint string `json:"fingerprint,omitempty" jsonschema:"only occurrences with this exact fingerprint"`
+ Since string `json:"since,omitempty" jsonschema:"RFC 3339 timestamp; only events received at or after this time"`
+ Until string `json:"until,omitempty" jsonschema:"RFC 3339 timestamp; only events received before this time"`
+ Silenced *bool `json:"silenced,omitempty" jsonschema:"true for only silenced events, false for only pushed ones; omit for both"`
+ Grouped bool `json:"grouped,omitempty" jsonschema:"collapse repeats of the same fingerprint into one row with a count"`
+ Before string `json:"before,omitempty" jsonschema:"cursor from a previous call's next_cursor"`
+ Limit int `json:"limit,omitempty" jsonschema:"1-100, default 25"`
+}
+
+type SearchEventsIn struct {
+ Query string `json:"query" jsonschema:"text to look for (case-insensitive substring)"`
+ Project string `json:"project,omitempty" jsonschema:"project id or slug; omit for all projects"`
+ Level string `json:"level,omitempty" jsonschema:"one of info, success, warning, error, critical"`
+ Since string `json:"since,omitempty" jsonschema:"RFC 3339 timestamp; only events received at or after this time"`
+ Until string `json:"until,omitempty" jsonschema:"RFC 3339 timestamp; only events received before this time"`
+ Before string `json:"before,omitempty" jsonschema:"cursor from a previous call's next_cursor"`
+ Limit int `json:"limit,omitempty" jsonschema:"1-100, default 25"`
+}
+
+// EventSummary is an event without its data payload.
+type EventSummary struct {
+ ID string `json:"id"`
+ Project string `json:"project" jsonschema:"project name"`
+ ProjectID string `json:"project_id"`
+ Level string `json:"level"`
+ Title string `json:"title"`
+ Body string `json:"body,omitempty"`
+ Source string `json:"source,omitempty"`
+ Type string `json:"type,omitempty"`
+ Fingerprint string `json:"fingerprint,omitempty"`
+ ExternalID string `json:"external_id,omitempty"`
+ OccurredAt string `json:"occurred_at"`
+ CreatedAt string `json:"created_at" jsonschema:"when the server received it"`
+ Silenced bool `json:"silenced,omitempty"`
+ DataKeys []string `json:"data_keys,omitempty" jsonschema:"top-level keys present in the data payload (fetch with get_event)"`
+ Actions []events.Action `json:"actions,omitempty"`
+ Group *events.GroupInfo `json:"group,omitempty" jsonschema:"present in grouped listings: how many times this fingerprint occurred and when"`
+}
+
+type EventsOut struct {
+ Events []EventSummary `json:"events"`
+ NextCursor string `json:"next_cursor,omitempty" jsonschema:"pass as before to get the next page"`
+}
+
+func (t *tools) listEvents(ctx context.Context, _ *sdk.CallToolRequest, in ListEventsIn) (*sdk.CallToolResult, EventsOut, error) {
+ f := events.Filter{ProjectID: in.Project, Level: in.Level, Source: in.Source, Fingerprint: in.Fingerprint, Since: in.Since, Until: in.Until,
+ Silenced: in.Silenced, Grouped: in.Grouped, Before: in.Before, Limit: in.Limit}
+ return t.list(ctx, f)
+}
+
+func (t *tools) searchEvents(ctx context.Context, _ *sdk.CallToolRequest, in SearchEventsIn) (*sdk.CallToolResult, EventsOut, error) {
+ if strings.TrimSpace(in.Query) == "" {
+ return nil, EventsOut{}, errors.New("query is required")
+ }
+ f := events.Filter{Query: in.Query, ProjectID: in.Project, Level: in.Level, Since: in.Since, Until: in.Until, Before: in.Before, Limit: in.Limit}
+ return t.list(ctx, f)
+}
+
+func (t *tools) list(ctx context.Context, f events.Filter) (*sdk.CallToolResult, EventsOut, error) {
+ if f.Level != "" && !levels.Valid(f.Level) {
+ return nil, EventsOut{}, fmt.Errorf("level must be one of %s", strings.Join(levels.All, ", "))
+ }
+ if f.Limit <= 0 {
+ f.Limit = DefaultLimit
+ }
+ if f.Limit > MaxLimit {
+ f.Limit = MaxLimit
+ }
+ page, err := t.st.Events.List(ctx, f)
+ if err != nil {
+ return nil, EventsOut{}, err
+ }
+ out := EventsOut{Events: []EventSummary{}, NextCursor: page.NextCursor}
+ for _, e := range page.Events {
+ out.Events = append(out.Events, summarise(e))
+ }
+ return nil, out, nil
+}
+
+func summarise(e events.Event) EventSummary {
+ s := EventSummary{ID: e.ID, Project: e.ProjectName, ProjectID: e.ProjectID, Level: e.Level, Title: e.Title, Body: e.Body, Source: e.Source, Type: e.Type,
+ Fingerprint: e.Fingerprint, ExternalID: e.ExternalID, OccurredAt: e.OccurredAt, CreatedAt: e.CreatedAt, Silenced: e.Silenced, Actions: e.Actions, Group: e.Group}
+ var data map[string]json.RawMessage
+ if json.Unmarshal(e.Data, &data) == nil {
+ for k := range data {
+ s.DataKeys = append(s.DataKeys, k)
+ }
+ }
+ return s
+}
+
+// ---- get_event ----
+
+type GetEventIn struct {
+ ID string `json:"id" jsonschema:"event id, e.g. evt_abc123"`
+}
+
+// EventOut is the full event.
+type EventOut struct {
+ EventSummary
+ ProjectSlug string `json:"project_slug"`
+ Data map[string]any `json:"data" jsonschema:"the sender's free-form payload; exception, stacktrace, tags, context and breadcrumbs are conventional keys"`
+}
+
+func (t *tools) getEvent(ctx context.Context, _ *sdk.CallToolRequest, in GetEventIn) (*sdk.CallToolResult, EventOut, error) {
+ e, err := t.st.Events.Get(ctx, strings.TrimSpace(in.ID))
+ if err != nil {
+ return nil, EventOut{}, err
+ }
+ return nil, full(e), nil
+}
+
+func full(e events.Event) EventOut {
+ out := EventOut{EventSummary: summarise(e), ProjectSlug: e.ProjectSlug, Data: map[string]any{}}
+ out.DataKeys = nil
+ _ = json.Unmarshal(e.Data, &out.Data)
+ return out
+}
+
+// ---- get_event_group ----
+
+type GetEventGroupIn struct {
+ Project string `json:"project" jsonschema:"project id or slug"`
+ Fingerprint string `json:"fingerprint" jsonschema:"the fingerprint shared by the occurrences"`
+ Since string `json:"since,omitempty" jsonschema:"RFC 3339 timestamp; only occurrences received at or after this time"`
+ Until string `json:"until,omitempty" jsonschema:"RFC 3339 timestamp; only occurrences received before this time"`
+ Before string `json:"before,omitempty" jsonschema:"cursor from a previous call's next_cursor"`
+ Limit int `json:"limit,omitempty" jsonschema:"occurrences to return, 1-100, default 25"`
+}
+
+type EventGroupOut struct {
+ Project string `json:"project"`
+ ProjectID string `json:"project_id"`
+ Fingerprint string `json:"fingerprint"`
+ Count int `json:"count" jsonschema:"total occurrences in the window"`
+ FirstSeen string `json:"first_seen,omitempty"`
+ LastSeen string `json:"last_seen,omitempty"`
+ Latest *EventOut `json:"latest,omitempty" jsonschema:"the most recent occurrence in full"`
+ Occurrences []EventSummary `json:"occurrences"`
+ NextCursor string `json:"next_cursor,omitempty"`
+}
+
+func (t *tools) getEventGroup(ctx context.Context, _ *sdk.CallToolRequest, in GetEventGroupIn) (*sdk.CallToolResult, EventGroupOut, error) {
+ in.Project, in.Fingerprint = strings.TrimSpace(in.Project), strings.TrimSpace(in.Fingerprint)
+ if in.Project == "" || in.Fingerprint == "" {
+ return nil, EventGroupOut{}, errors.New("project and fingerprint are required")
+ }
+ if in.Limit <= 0 {
+ in.Limit = DefaultLimit
+ }
+ if in.Limit > MaxLimit {
+ in.Limit = MaxLimit
+ }
+ // One grouped row gives the count and window; then the occurrences.
+ head, err := t.st.Events.List(ctx, events.Filter{ProjectID: in.Project, Fingerprint: in.Fingerprint, Since: in.Since, Until: in.Until, Grouped: true, Limit: 1})
+ if err != nil {
+ return nil, EventGroupOut{}, err
+ }
+ if len(head.Events) == 0 {
+ return nil, EventGroupOut{}, fmt.Errorf("no events with fingerprint %q in project %q", in.Fingerprint, in.Project)
+ }
+ latest := head.Events[0]
+ out := EventGroupOut{Project: latest.ProjectName, ProjectID: latest.ProjectID, Fingerprint: latest.Fingerprint, Occurrences: []EventSummary{}}
+ if latest.Group != nil {
+ out.Count, out.FirstSeen, out.LastSeen = latest.Group.Count, latest.Group.FirstSeen, latest.Group.LastSeen
+ }
+ l := full(latest)
+ out.Latest = &l
+ page, err := t.st.Events.List(ctx, events.Filter{ProjectID: in.Project, Fingerprint: in.Fingerprint, Since: in.Since, Until: in.Until, Before: in.Before, Limit: in.Limit})
+ if err != nil {
+ return nil, EventGroupOut{}, err
+ }
+ for _, e := range page.Events {
+ out.Occurrences = append(out.Occurrences, summarise(e))
+ }
+ out.NextCursor = page.NextCursor
+ return nil, out, nil
+}
+
+func boolPtr(b bool) *bool { return &b }
diff --git a/server/internal/mcp/mcp_test.go b/server/internal/mcp/mcp_test.go
new file mode 100644
index 0000000..d63a5e6
--- /dev/null
+++ b/server/internal/mcp/mcp_test.go
@@ -0,0 +1,238 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ sdk "github.com/modelcontextprotocol/go-sdk/mcp"
+
+ "github.com/chrisgreg/boop/server/internal/database"
+ "github.com/chrisgreg/boop/server/internal/events"
+ "github.com/chrisgreg/boop/server/internal/events/redact"
+ "github.com/chrisgreg/boop/server/internal/projects"
+)
+
+type fixture struct {
+ t *testing.T
+ session *sdk.ClientSession
+ uini projects.Project
+ infra projects.Project
+ ids []string
+}
+
+func setup(t *testing.T) *fixture {
+ t.Helper()
+ db, err := database.Open(filepath.Join(t.TempDir(), "boop.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ ctx := context.Background()
+ ps, es := projects.New(db), events.New(db)
+ name := func(s string) *string { return &s }
+ uini, _, err := ps.Create(ctx, projects.Input{Name: name("Uini")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ infra, _, _ := ps.Create(ctx, projects.Input{Name: name("Infra")})
+ r := redact.New()
+ f := &fixture{t: t, uini: uini, infra: infra}
+ post := func(p projects.Project, in events.Input) {
+ e, err := es.Create(ctx, p.ID, in, r)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.ids = append(f.ids, e.ID)
+ }
+ for i := 0; i < 3; i++ {
+ post(uini, events.Input{Title: "KeyError", Body: "key :can_palette? not found", Level: "error", Source: "error_tracker", Fingerprint: "keyerror",
+ Data: json.RawMessage(`{"exception":{"type":"KeyError"},"tags":{"environment":"production"},"context":{"password":"hunter2","user_id":"u1"}}`)})
+ }
+ post(uini, events.Input{Title: "Deploy complete", Level: "success", Source: "github_actions", Actions: []events.Action{{Label: "Open run", URL: "https://github.com/x/y/actions/runs/1"}}})
+ post(infra, events.Input{Title: "Disk 91% full", Level: "critical", Source: "cron", Body: "on db-1"})
+
+ srv := NewServer(Stores{Projects: ps, Events: es}, "test")
+ ct, st := sdk.NewInMemoryTransports()
+ go func() { _ = srv.Run(ctx, st) }()
+ client := sdk.NewClient(&sdk.Implementation{Name: "test", Version: "0"}, nil)
+ sess, err := client.Connect(ctx, ct, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { sess.Close() })
+ f.session = sess
+ return f
+}
+
+// call invokes a tool and decodes its structured content into out.
+func (f *fixture) call(name string, args map[string]any, out any) *sdk.CallToolResult {
+ f.t.Helper()
+ res, err := f.session.CallTool(context.Background(), &sdk.CallToolParams{Name: name, Arguments: args})
+ if err != nil {
+ f.t.Fatalf("%s: %v", name, err)
+ }
+ if res.IsError || out == nil {
+ return res
+ }
+ b, _ := json.Marshal(res.StructuredContent)
+ if err := json.Unmarshal(b, out); err != nil {
+ f.t.Fatalf("%s: decode %v: %s", name, err, b)
+ }
+ return res
+}
+
+func TestToolsAreReadOnlyAndListed(t *testing.T) {
+ f := setup(t)
+ res, err := f.session.ListTools(context.Background(), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, tl := range res.Tools {
+ names = append(names, tl.Name)
+ if tl.Annotations == nil || !tl.Annotations.ReadOnlyHint {
+ t.Errorf("%s must be annotated read-only", tl.Name)
+ }
+ if tl.Description == "" || tl.InputSchema == nil {
+ t.Errorf("%s needs a description and input schema", tl.Name)
+ }
+ }
+ want := "get_event,get_event_group,list_events,list_projects,search_events"
+ if got := strings.Join(sorted(names), ","); got != want {
+ t.Errorf("tools = %s, want %s", got, want)
+ }
+}
+
+func TestListProjects(t *testing.T) {
+ f := setup(t)
+ var out ListProjectsOut
+ f.call("list_projects", nil, &out)
+ if len(out.Projects) != 2 || out.Projects[0].Slug == "" || out.Projects[0].MinLevel != "info" {
+ t.Errorf("projects = %+v", out.Projects)
+ }
+}
+
+func TestListEventsFiltersAndGrouping(t *testing.T) {
+ f := setup(t)
+ var out EventsOut
+ f.call("list_events", nil, &out)
+ if len(out.Events) != 5 || out.Events[0].Title != "Disk 91% full" || out.Events[0].Project != "Infra" {
+ t.Fatalf("all: %+v", out.Events)
+ }
+ if out.Events[1].Actions == nil || out.Events[1].Actions[0].Label != "Open run" {
+ t.Errorf("actions should be in summaries: %+v", out.Events[1])
+ }
+ // Summaries carry the data keys but never the payload itself.
+ ke := out.Events[2]
+ if strings.Join(sorted(ke.DataKeys), ",") != "context,exception,tags" {
+ t.Errorf("data keys: %v", ke.DataKeys)
+ }
+ raw, _ := json.Marshal(out)
+ if strings.Contains(string(raw), "hunter2") || strings.Contains(string(raw), "can_palette") == false {
+ t.Errorf("summary leaked payload or lost body: %s", raw)
+ }
+
+ f.call("list_events", map[string]any{"project": "uini", "level": "error", "grouped": true}, &out)
+ if len(out.Events) != 1 || out.Events[0].Group == nil || out.Events[0].Group.Count != 3 {
+ t.Errorf("grouped: %+v", out.Events)
+ }
+ f.call("list_events", map[string]any{"project": f.infra.ID}, &out)
+ if len(out.Events) != 1 || out.Events[0].Level != "critical" {
+ t.Errorf("by id: %+v", out.Events)
+ }
+ f.call("list_events", map[string]any{"limit": 2}, &out)
+ if len(out.Events) != 2 || out.NextCursor == "" {
+ t.Fatalf("paged: %+v", out)
+ }
+ f.call("list_events", map[string]any{"limit": 2, "before": out.NextCursor}, &out)
+ if len(out.Events) != 2 || out.Events[0].Title != "KeyError" {
+ t.Errorf("page 2: %+v", out.Events)
+ }
+ if res := f.call("list_events", map[string]any{"level": "fatal"}, nil); !res.IsError {
+ t.Error("bad level should be a tool error")
+ }
+ if res := f.call("list_events", map[string]any{"since": "last night"}, nil); !res.IsError {
+ t.Error("bad since should be a tool error")
+ }
+}
+
+func TestSearchEvents(t *testing.T) {
+ f := setup(t)
+ var out EventsOut
+ f.call("search_events", map[string]any{"query": "PALETTE"}, &out)
+ if len(out.Events) != 3 {
+ t.Errorf("body search: %+v", out.Events)
+ }
+ f.call("search_events", map[string]any{"query": "db-1"}, &out)
+ if len(out.Events) != 1 || out.Events[0].Title != "Disk 91% full" {
+ t.Errorf("search: %+v", out.Events)
+ }
+ f.call("search_events", map[string]any{"query": "production", "project": "uini"}, &out) // inside data payload
+ if len(out.Events) != 3 {
+ t.Errorf("payload search: %+v", out.Events)
+ }
+ f.call("search_events", map[string]any{"query": "nothing-like-this"}, &out)
+ if len(out.Events) != 0 {
+ t.Errorf("no match: %+v", out.Events)
+ }
+ if res := f.call("search_events", map[string]any{"query": " "}, nil); !res.IsError {
+ t.Error("empty query should be a tool error")
+ }
+}
+
+func TestGetEvent(t *testing.T) {
+ f := setup(t)
+ var out EventOut
+ f.call("get_event", map[string]any{"id": f.ids[0]}, &out)
+ if out.ID != f.ids[0] || out.ProjectSlug != "uini" || out.Fingerprint != "keyerror" {
+ t.Errorf("event: %+v", out)
+ }
+ data := out.Data
+ if data["exception"].(map[string]any)["type"] != "KeyError" || data["context"].(map[string]any)["password"] != "[REDACTED]" {
+ t.Errorf("data should be the stored (redacted) payload: %s", out.Data)
+ }
+ if res := f.call("get_event", map[string]any{"id": "evt_nope"}, nil); !res.IsError {
+ t.Error("missing event should be a tool error, not a protocol error")
+ }
+}
+
+func TestGetEventGroup(t *testing.T) {
+ f := setup(t)
+ var out EventGroupOut
+ f.call("get_event_group", map[string]any{"project": "uini", "fingerprint": "keyerror"}, &out)
+ if out.Count != 3 || len(out.Occurrences) != 3 || out.Latest == nil || out.Latest.ID != f.ids[2] || out.FirstSeen == "" || out.FirstSeen > out.LastSeen {
+ t.Errorf("group: %+v", out)
+ }
+ if len(out.Latest.Data) == 0 {
+ t.Error("latest should carry the full payload")
+ }
+ f.call("get_event_group", map[string]any{"project": f.uini.ID, "fingerprint": "keyerror", "limit": 2}, &out)
+ if len(out.Occurrences) != 2 || out.NextCursor == "" || out.Count != 3 {
+ t.Errorf("paged group: %+v", out)
+ }
+ if res := f.call("get_event_group", map[string]any{"project": "infra", "fingerprint": "keyerror"}, nil); !res.IsError {
+ t.Error("fingerprint in another project should be an error")
+ }
+ if res := f.call("get_event_group", map[string]any{"project": "uini"}, nil); !res.IsError {
+ t.Error("missing fingerprint should be an error")
+ }
+}
+
+func sorted(s []string) []string {
+ out := append([]string(nil), s...)
+ for i := range out {
+ for j := i + 1; j < len(out); j++ {
+ if out[j] < out[i] {
+ out[i], out[j] = out[j], out[i]
+ }
+ }
+ }
+ return out
+}
+
+var _ = slog.New(slog.NewTextHandler(io.Discard, nil))
diff --git a/server/internal/settings/settings.go b/server/internal/settings/settings.go
index 073038f..5429ee3 100644
--- a/server/internal/settings/settings.go
+++ b/server/internal/settings/settings.go
@@ -16,6 +16,7 @@ const (
KeyRetentionDays = "retention_days"
KeySetupCompleted = "setup_completed"
KeyRedactKeys = "redact_keys" // comma-separated, added to the built-in list
+ KeyMCPEnabled = "mcp_enabled" // "false" turns the /mcp endpoint off; unset = on
)
// Store reads and writes settings.
diff --git a/server/migrations/0003_actions_groups.sql b/server/migrations/0003_actions_groups.sql
new file mode 100644
index 0000000..cf718f2
--- /dev/null
+++ b/server/migrations/0003_actions_groups.sql
@@ -0,0 +1,2 @@
+ALTER TABLE events ADD COLUMN actions_json TEXT NOT NULL DEFAULT '[]';
+CREATE INDEX events_group ON events(project_id, fingerprint, created_at DESC, id DESC);
diff --git a/server/web/src/App.svelte b/server/web/src/App.svelte
index b5a4f79..a07603e 100644
--- a/server/web/src/App.svelte
+++ b/server/web/src/App.svelte
@@ -5,6 +5,7 @@
import StatusDot from './lib/ui/StatusDot.svelte'
import Inbox from './pages/Inbox.svelte'
import EventDetail from './pages/EventDetail.svelte'
+ import Group from './pages/Group.svelte'
import Projects from './pages/Projects.svelte'
import Devices from './pages/Devices.svelte'
import Settings from './pages/Settings.svelte'
@@ -56,7 +57,7 @@
{ label: 'Devices', href: '/devices' },
{ label: 'Settings', href: '/settings' },
]
- const activeTab = $derived(route.name === 'event' ? '/' : router.path)
+ const activeTab = $derived(route.name === 'event' || route.name === 'group' ? '/' : router.path)
</script>
<div class="page">
@@ -93,6 +94,8 @@
<Inbox />
{:else if route.name === 'event'}
<EventDetail id={route.params.id} />
+ {:else if route.name === 'group'}
+ <Group project={route.params.project} fingerprint={route.params.fingerprint} />
{:else if route.name === 'projects'}
<Projects />
{:else if route.name === 'devices'}
diff --git a/server/web/src/lib/api.ts b/server/web/src/lib/api.ts
index 6fb130d..7b63374 100644
--- a/server/web/src/lib/api.ts
+++ b/server/web/src/lib/api.ts
@@ -18,6 +18,19 @@ export interface ProjectCreated extends Project {
api_key: string
}
+/** A button on the notification and in the event detail that opens a URL. */
+export interface EventAction {
+ label: string
+ url: string
+}
+
+/** Present on grouped listings: this row stands for `count` occurrences of its fingerprint. */
+export interface GroupInfo {
+ count: number
+ first_seen: string
+ last_seen: string
+}
+
export interface Event {
id: string
external_id?: string
@@ -36,6 +49,8 @@ export interface Event {
created_at: string
silenced: boolean
silence_id?: string
+ actions?: EventAction[]
+ group?: GroupInfo
}
export type SilenceField = 'fingerprint' | 'title' | 'source'
@@ -121,6 +136,8 @@ export interface Settings {
redact_keys: string[]
default_redact_keys: string[]
setup_completed: boolean
+ mcp_enabled: boolean
+ mcp_token_set: boolean
}
export class ApiError extends Error {
@@ -165,9 +182,9 @@ export const api = {
settings: () => request<Settings>('GET', '/api/v1/settings'),
updateSettings: (patch: Partial<Settings>) => request<Settings>('PATCH', '/api/v1/settings', patch),
- events: (params: { project?: string; level?: string; source?: string; before?: string; limit?: number; silenced?: string } = {}) => {
+ events: (params: { project?: string; level?: string; source?: string; fingerprint?: string; before?: string; limit?: number; silenced?: string; grouped?: boolean } = {}) => {
const q = new URLSearchParams()
- for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '') q.set(k, String(v))
+ for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== '' && v !== false) q.set(k, String(v))
const qs = q.toString()
return request<EventPage>('GET', '/api/v1/events' + (qs ? '?' + qs : ''))
},
diff --git a/server/web/src/lib/format.test.ts b/server/web/src/lib/format.test.ts
index 7370b76..1311998 100644
--- a/server/web/src/lib/format.test.ts
+++ b/server/web/src/lib/format.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { relative, duration, compact, dayGroup, retentionLabel } from './format'
+import { relative, duration, compact, dayGroup, retentionLabel, clock, seenRange } from './format'
const now = new Date('2026-08-28T12:00:00Z')
@@ -51,3 +51,18 @@ describe('retentionLabel', () => {
expect(retentionLabel(30)).toBe('30 days')
})
})
+
+describe('clock / seenRange', () => {
+ // These run in whatever TZ vitest has; compare against the same formatter.
+ const hm = (iso: string) => new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false })
+ it('shows only the time on the same day', () => {
+ expect(clock('2026-08-28T09:31:00Z', now)).toBe(hm('2026-08-28T09:31:00Z'))
+ })
+ it('adds the date on other days', () => {
+ expect(clock('2026-08-12T09:31:00Z', now)).toMatch(/^Aug 12 /)
+ })
+ it('builds the seen range', () => {
+ expect(seenRange('2026-08-28T09:31:00Z', '2026-08-28T10:42:00Z', now)).toBe(`First seen ${hm('2026-08-28T09:31:00Z')} · Last seen ${hm('2026-08-28T10:42:00Z')}`)
+ expect(clock(null)).toBe('—')
+ })
+})
diff --git a/server/web/src/lib/format.ts b/server/web/src/lib/format.ts
index 50484af..1f8d3dc 100644
--- a/server/web/src/lib/format.ts
+++ b/server/web/src/lib/format.ts
@@ -33,6 +33,20 @@ export function fullDate(s: string | null | undefined): string {
return `${shortDate(d)} · ${d.toLocaleTimeString('en-GB', { hour12: false })}`
}
+/** "09:31" when on the same day as `now`, otherwise "Aug 12 09:31". */
+export function clock(s: string | null | undefined, now: Date = new Date()): string {
+ const d = parseTime(s)
+ if (!d) return '—'
+ const hm = d.toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', hour12: false })
+ const sameDay = d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()
+ return sameDay ? hm : `${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} ${hm}`
+}
+
+/** "First seen 09:31 · Last seen 10:42" for a grouped row. */
+export function seenRange(first: string, last: string, now: Date = new Date()): string {
+ return `First seen ${clock(first, now)} · Last seen ${clock(last, now)}`
+}
+
/** "Today", "Yesterday", or a short date — for grouping the inbox. */
export function dayGroup(s: string, now: Date = new Date()): string {
const d = parseTime(s)
diff --git a/server/web/src/lib/motion.ts b/server/web/src/lib/motion.ts
index fa0ef3e..bea2054 100644
--- a/server/web/src/lib/motion.ts
+++ b/server/web/src/lib/motion.ts
@@ -1,4 +1,4 @@
-// Motion presets. The design system wants near-instant state changes, so everything is short
+// Motion presets. State changes should feel near-instant, so everything is short
// and ease-out, and it all collapses to zero under prefers-reduced-motion.
import { cubicOut } from 'svelte/easing'
import { fade, fly, slide, scale } from 'svelte/transition'
diff --git a/server/web/src/lib/router.svelte.ts b/server/web/src/lib/router.svelte.ts
index 112771d..7ac2aa7 100644
--- a/server/web/src/lib/router.svelte.ts
+++ b/server/web/src/lib/router.svelte.ts
@@ -2,7 +2,7 @@
// unknown path, so deep links work.
export interface Route {
- name: 'inbox' | 'event' | 'projects' | 'devices' | 'settings' | 'setup' | 'notfound'
+ name: 'inbox' | 'event' | 'group' | 'projects' | 'devices' | 'settings' | 'setup' | 'notfound'
params: Record<string, string>
}
@@ -11,6 +11,8 @@ function parse(path: string): Route {
if (p === '/') return { name: 'inbox', params: {} }
const ev = p.match(/^\/events\/([^/]+)$/)
if (ev) return { name: 'event', params: { id: decodeURIComponent(ev[1]) } }
+ const grp = p.match(/^\/groups\/([^/]+)\/([^/]+)$/)
+ if (grp) return { name: 'group', params: { project: decodeURIComponent(grp[1]), fingerprint: decodeURIComponent(grp[2]) } }
if (p === '/projects') return { name: 'projects', params: {} }
if (p === '/devices') return { name: 'devices', params: {} }
if (p === '/settings') return { name: 'settings', params: {} }
@@ -52,4 +54,9 @@ export function link(e: MouseEvent) {
router.navigate(href)
}
+/** Path of the occurrences page for a fingerprint within a project. */
+export function groupPath(project: string, fingerprint: string): string {
+ return `/groups/${encodeURIComponent(project)}/${encodeURIComponent(fingerprint)}`
+}
+
export { parse as parseRoute }
diff --git a/server/web/src/lib/router.test.ts b/server/web/src/lib/router.test.ts
index d00fd5f..e573f03 100644
--- a/server/web/src/lib/router.test.ts
+++ b/server/web/src/lib/router.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { parseRoute } from './router.svelte'
+import { parseRoute, groupPath } from './router.svelte'
describe('parseRoute', () => {
it('maps paths to routes', () => {
@@ -10,4 +10,10 @@ describe('parseRoute', () => {
expect(parseRoute('/setup')).toEqual({ name: 'setup', params: {} })
expect(parseRoute('/nope').name).toBe('notfound')
})
+ it('round-trips group paths with awkward fingerprints', () => {
+ const path = groupPath('prj_1', 'lib/a.ex:49 KeyError?')
+ expect(path).toBe('/groups/prj_1/lib%2Fa.ex%3A49%20KeyError%3F')
+ expect(parseRoute(path)).toEqual({ name: 'group', params: { project: 'prj_1', fingerprint: 'lib/a.ex:49 KeyError?' } })
+ expect(parseRoute('/groups/prj_1').name).toBe('notfound')
+ })
})
diff --git a/server/web/src/lib/ui/Card.svelte b/server/web/src/lib/ui/Card.svelte
index 44d9511..6626dc0 100644
--- a/server/web/src/lib/ui/Card.svelte
+++ b/server/web/src/lib/ui/Card.svelte
@@ -1,9 +1,9 @@
<script lang="ts">
import type { Snippet } from 'svelte'
- let { title, action, children, flush = false }: { title?: string; action?: Snippet; children: Snippet; flush?: boolean } = $props()
+ let { title, action, children, flush = false, compact = false }: { title?: string; action?: Snippet; children: Snippet; flush?: boolean; compact?: boolean } = $props()
</script>
-<section class="card" class:flush>
+<section class="card" class:flush class:compact>
{#if title || action}
<header class:only-action={!title}>
{#if title}<h2>{title}</h2>{/if}
@@ -21,6 +21,7 @@
padding: var(--up-space-5);
}
.flush { padding: var(--up-space-2); padding-top: var(--up-space-4); }
+ .compact { padding: 14px var(--up-space-4); }
header {
display: flex;
align-items: center;
diff --git a/server/web/src/lib/ui/LevelBadge.svelte b/server/web/src/lib/ui/LevelBadge.svelte
index 5ed7c18..ca1adaa 100644
--- a/server/web/src/lib/ui/LevelBadge.svelte
+++ b/server/web/src/lib/ui/LevelBadge.svelte
@@ -17,6 +17,7 @@
gap: 7px;
font: var(--up-type-small);
white-space: nowrap;
+ min-width: 76px; /* same width for every level so chips line up in lists */
}
.dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
.info { color: var(--boop-info-strong); }
diff --git a/server/web/src/pages/EventDetail.svelte b/server/web/src/pages/EventDetail.svelte
index 7d8e2f9..5ac3410 100644
--- a/server/web/src/pages/EventDetail.svelte
+++ b/server/web/src/pages/EventDetail.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { api, type Event, type Delivery, type Silence } from '../lib/api'
- import { link } from '../lib/router.svelte'
+ import { link, groupPath } from '../lib/router.svelte'
import { fullDate, relative } from '../lib/format'
import Card from '../lib/ui/Card.svelte'
import LevelBadge from '../lib/ui/LevelBadge.svelte'
@@ -177,12 +177,22 @@
<div class="facts">
<div><span class="k">Occurred</span><span title={event.occurred_at}>{fullDate(event.occurred_at)}</span></div>
<div><span class="k">Received</span><span title={event.created_at}>{fullDate(event.created_at)} · {relative(event.created_at)}</span></div>
- {#if event.fingerprint}<div><span class="k">Fingerprint</span><span class="mono">{event.fingerprint}</span></div>{/if}
+ {#if event.fingerprint}<div><span class="k">Fingerprint</span><span class="mono">{event.fingerprint} <a class="small" href={groupPath(event.project_id, event.fingerprint)} onclick={link}>all occurrences</a></span></div>{/if}
{#if event.external_id}<div><span class="k">External id</span><span class="mono">{event.external_id}</span></div>{/if}
<div><span class="k">Event id</span><span class="mono">{event.id}</span></div>
</div>
</Card>
+ {#if event.actions && event.actions.length}
+ <Card title="Actions">
+ <div class="actions">
+ {#each event.actions as a (a.label + a.url)}
+ <a class="action" href={a.url} target="_blank" rel="noopener noreferrer">{a.label}<span class="faint">↗</span></a>
+ {/each}
+ </div>
+ </Card>
+ {/if}
+
{#if exception}
<Card title="Exception">
<div class="exc">
@@ -341,6 +351,10 @@
.bc-m { word-break: break-word; }
.linkish { background: none; border: none; cursor: pointer; font: var(--up-type-ui); color: var(--up-accent); padding: 0; }
.linkish:hover { color: var(--up-accent-hover); }
+ .actions { display: flex; flex-wrap: wrap; gap: 8px; }
+ .action { display: inline-flex; align-items: center; gap: 6px; font: var(--up-type-ui); height: 34px; padding: 0 16px; border-radius: var(--up-radius-control); background: var(--up-accent); color: var(--up-text-on-dark); }
+ .action:hover { background: var(--up-accent-hover); color: var(--up-text-on-dark); }
+ .action .faint { color: inherit; opacity: 0.7; }
.dls { display: flex; flex-direction: column; gap: 8px; }
.dl { display: grid; grid-template-columns: 1fr auto 1fr auto; gap: 12px; align-items: center; font: var(--up-type-meta); }
.r { text-align: right; }
diff --git a/server/web/src/pages/Group.svelte b/server/web/src/pages/Group.svelte
new file mode 100644
index 0000000..afc9fbf
--- /dev/null
+++ b/server/web/src/pages/Group.svelte
@@ -0,0 +1,126 @@
+<script lang="ts">
+ import { api, type Event } from '../lib/api'
+ import { link } from '../lib/router.svelte'
+ import { relative, fullDate, seenRange } from '../lib/format'
+ import Card from '../lib/ui/Card.svelte'
+ import Button from '../lib/ui/Button.svelte'
+ import LevelBadge from '../lib/ui/LevelBadge.svelte'
+ import Notice from '../lib/ui/Notice.svelte'
+ import Empty from '../lib/ui/Empty.svelte'
+ import ProjectIcon from '../lib/ui/ProjectIcon.svelte'
+ import Skeleton from '../lib/ui/Skeleton.svelte'
+ import { rowIn } from '../lib/motion'
+
+ let { project, fingerprint }: { project: string; fingerprint: string } = $props()
+ let head = $state<Event | null>(null)
+ let events = $state<Event[]>([])
+ let cursor = $state<string | undefined>()
+ let loading = $state(true)
+ let loadingMore = $state(false)
+ let error = $state('')
+ let now = $state(new Date())
+
+ async function load(reset = true) {
+ try {
+ error = ''
+ if (reset) loading = true
+ else loadingMore = true
+ if (reset) {
+ const g = await api.events({ project, fingerprint, grouped: true, limit: 1 })
+ head = g.events[0] ?? null
+ }
+ const page = await api.events({ project, fingerprint, before: reset ? undefined : cursor, limit: 50 })
+ events = reset ? page.events : [...events, ...page.events]
+ cursor = page.next_cursor
+ now = new Date()
+ } catch (e: any) {
+ error = e.message
+ } finally {
+ loading = false
+ loadingMore = false
+ }
+ }
+
+ $effect(() => {
+ project
+ fingerprint
+ load(true)
+ })
+</script>
+
+<div class="stack">
+ <div class="crumb"><a href="/" onclick={link}>Inbox</a><span class="faint">/</span><span class="muted mono">{fingerprint}</span></div>
+
+ {#if error}
+ <Notice tone="bad">{error}</Notice>
+ {/if}
+
+ {#if head}
+ <Card>
+ <div class="head">
+ <div class="meta">
+ <span class="secondary proj"><ProjectIcon icon={head.project_icon} size={14} /><span>{head.project_name}</span></span>
+ <span class="faint">·</span>
+ <LevelBadge level={head.level} />
+ {#if head.source}<span class="faint">·</span><span class="muted">{head.source}</span>{/if}
+ </div>
+ <h1>{head.title} <span class="count">{head.group?.count ?? events.length} occurrence{(head.group?.count ?? events.length) === 1 ? '' : 's'}</span></h1>
+ {#if head.group}<p class="secondary">{seenRange(head.group.first_seen, head.group.last_seen, now)}</p>{/if}
+ <div class="facts">
+ <div><span class="k">Fingerprint</span><span class="mono">{fingerprint}</span></div>
+ {#if head.group}
+ <div><span class="k">First seen</span><span title={head.group.first_seen}>{fullDate(head.group.first_seen)}</span></div>
+ <div><span class="k">Last seen</span><span title={head.group.last_seen}>{fullDate(head.group.last_seen)}</span></div>
+ {/if}
+ </div>
+ </div>
+ </Card>
+ {/if}
+
+ <Card flush title="Occurrences">
+ {#if loading && events.length === 0}
+ <Skeleton rows={4} />
+ {:else if events.length === 0}
+ <Empty title="No occurrences">Nothing with this fingerprint in this project.</Empty>
+ {:else}
+ {#each events as e, i (e.id)}
+ <a class="ev" href="/events/{e.id}" onclick={link} in:rowIn={{ i }}>
+ <div class="main">
+ <div class="title">{e.title}</div>
+ {#if e.body}<div class="body">{e.body}</div>{/if}
+ </div>
+ <div class="lvl"><LevelBadge level={e.level} />{#if e.silenced}<span class="caption silenced">silenced</span>{/if}</div>
+ <div class="time" title={e.created_at}>{relative(e.created_at, now)}</div>
+ </a>
+ {/each}
+ {#if cursor}
+ <div class="more">
+ <Button variant="ghost" size="sm" onclick={() => load(false)} disabled={loadingMore}>{loadingMore ? 'Loading' : 'Load more'}</Button>
+ </div>
+ {/if}
+ {/if}
+ </Card>
+</div>
+
+<style>
+ .crumb { display: flex; gap: 8px; align-items: center; font: var(--up-type-meta); }
+ .head { display: flex; flex-direction: column; gap: 8px; }
+ .proj { display: inline-flex; gap: 6px; align-items: center; }
+ .meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; font: var(--up-type-meta); }
+ h1 { font: var(--up-type-metric); letter-spacing: -0.01em; word-break: break-word; display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
+ .count { font: var(--up-type-small); color: var(--up-accent-hover); background: var(--up-accent-tint); border-radius: var(--up-radius-pill); padding: 2px 10px; }
+ .facts { display: grid; grid-template-columns: 1fr 1fr; gap: 8px 24px; margin-top: var(--up-space-4); padding-top: var(--up-space-4); border-top: 1px solid var(--up-border-hairline); }
+ .facts > div { display: flex; flex-direction: column; gap: 2px; font: var(--up-type-meta); min-width: 0; }
+ .facts span:last-child { overflow: hidden; text-overflow: ellipsis; }
+ .k { font: var(--up-type-caption); color: var(--up-text-muted); }
+ .ev { display: grid; grid-template-columns: 1fr auto 64px; gap: var(--up-space-4); align-items: center; padding: 12px var(--up-space-4); border-radius: var(--up-radius-control); color: var(--up-ink); transition: background 120ms ease-out; }
+ .ev:hover { background: var(--up-bg-hover); color: var(--up-ink); }
+ .main { min-width: 0; }
+ .title { font: var(--up-type-row-title); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .body { font: var(--up-type-meta); color: var(--up-text-muted); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .time { font: var(--up-type-caption); color: var(--up-text-muted); text-align: right; }
+ .lvl { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }
+ .silenced { color: var(--up-text-inactive); }
+ .more { display: flex; justify-content: center; padding: 10px 0 4px; }
+ @media (max-width: 600px) { .facts { grid-template-columns: 1fr; } }
+</style>
diff --git a/server/web/src/pages/Inbox.svelte b/server/web/src/pages/Inbox.svelte
index 9ddc9b9..ed777b9 100644
--- a/server/web/src/pages/Inbox.svelte
+++ b/server/web/src/pages/Inbox.svelte
@@ -1,7 +1,7 @@
<script lang="ts">
import { api, LEVELS, type Event, type Project } from '../lib/api'
- import { link } from '../lib/router.svelte'
- import { relative, dayGroup } from '../lib/format'
+ import { link, groupPath } from '../lib/router.svelte'
+ import { relative, dayGroup, seenRange } from '../lib/format'
import { LEVEL_LABEL } from '../lib/levels'
import Card from '../lib/ui/Card.svelte'
import Select from '../lib/ui/Select.svelte'
@@ -23,13 +23,31 @@
let level = $state('')
let silenced = $state(typeof location !== 'undefined' ? new URLSearchParams(location.search).get('silenced') ?? '' : '')
let now = $state(new Date())
+ // Collapse repeats of the same fingerprint into one row. Remembered per browser.
+ let grouped = $state(readGrouped())
+
+ function readGrouped(): boolean {
+ try {
+ return localStorage.getItem('boop.inbox.grouped') !== 'false'
+ } catch {
+ return true
+ }
+ }
+ function setGrouped(v: boolean) {
+ grouped = v
+ try {
+ localStorage.setItem('boop.inbox.grouped', String(v))
+ } catch {
+ /* private mode etc. */
+ }
+ }
async function load(reset = true) {
try {
error = ''
if (reset) loading = true
else loadingMore = true
- const page = await api.events({ project, level, silenced, before: reset ? undefined : cursor, limit: 50 })
+ const page = await api.events({ project, level, silenced, grouped, before: reset ? undefined : cursor, limit: 50 })
events = reset ? page.events : [...events, ...page.events]
cursor = page.next_cursor
now = new Date()
@@ -45,6 +63,7 @@
project
level
silenced
+ grouped
load(true)
})
$effect(() => {
@@ -78,6 +97,10 @@
/>
<Select bind:value={level} options={[{ value: '', label: 'All levels' }, ...LEVELS.map((l) => ({ value: l, label: LEVEL_LABEL[l] }))]} aria-label="Level" />
<Select bind:value={silenced} options={[{ value: '', label: 'Pushed and silenced' }, { value: 'true', label: 'Silenced only' }, { value: 'false', label: 'Pushed only' }]} aria-label="Silenced" />
+ <label class="toggle caption">
+ <input type="checkbox" checked={grouped} onchange={(e) => setGrouped((e.currentTarget as HTMLInputElement).checked)} />
+ Group repeats
+ </label>
<span class="spacer"></span>
<Button variant="secondary" size="sm" onclick={() => load(true)} disabled={loading}>Refresh</Button>
</div>
@@ -102,14 +125,20 @@
{#each groups as g, gi (g.label)}
<div class="group" in:soft>{g.label}</div>
{#each g.items as e, i (e.id)}
- <a class="ev" href="/events/{e.id}" onclick={link} in:rowIn={{ i: gi * 4 + i }} animate:reorder>
+ {@const repeats = e.group && e.group.count > 1 ? e.group : null}
+ <a class="ev" href={repeats ? groupPath(e.project_id, e.fingerprint) : `/events/${e.id}`} onclick={link} in:rowIn={{ i: gi * 4 + i }} animate:reorder>
<div class="proj">
<ProjectIcon icon={e.project_icon} size={14} />
<span>{e.project_name}</span>
</div>
<div class="main">
- <div class="title">{e.title}</div>
- {#if e.body}<div class="body">{e.body}</div>{/if}
+ <div class="title">
+ <span class="t">{e.title}</span>
+ {#if repeats}<span class="count" title="{repeats.count} occurrences of this fingerprint">×{repeats.count}</span>{/if}
+ </div>
+ {#if repeats}
+ <div class="body seen">{seenRange(repeats.first_seen, repeats.last_seen, now)}</div>
+ {:else if e.body}<div class="body">{e.body}</div>{/if}
</div>
<div class="lvl">
<LevelBadge level={e.level} />
@@ -140,7 +169,7 @@
.group + .ev { border-top: none; }
.ev {
display: grid;
- grid-template-columns: 120px 1fr auto 64px;
+ grid-template-columns: 120px minmax(0, 1fr) 40px 64px;
gap: var(--up-space-4);
align-items: center;
padding: 12px var(--up-space-4);
@@ -152,10 +181,15 @@
.proj { font: var(--up-type-meta); color: var(--up-text-secondary); display: flex; gap: 6px; align-items: center; min-width: 0; }
.proj span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.main { min-width: 0; }
- .title { font: var(--up-type-row-title); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .title { font: var(--up-type-row-title); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: flex; align-items: baseline; gap: 8px; min-width: 0; }
+ .title .t { overflow: hidden; text-overflow: ellipsis; }
+ .count { font: var(--up-type-small); color: var(--up-accent-hover); background: var(--up-accent-tint); border-radius: var(--up-radius-pill); padding: 1px 8px; flex: none; }
+ .seen { color: var(--up-text-secondary); }
+ .toggle { display: inline-flex; align-items: center; gap: 6px; color: var(--up-text-secondary); cursor: pointer; user-select: none; }
+ .toggle input { accent-color: var(--up-accent); margin: 0; }
.body { font: var(--up-type-meta); color: var(--up-text-muted); margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.time { font: var(--up-type-caption); color: var(--up-text-muted); text-align: right; }
- .lvl { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }
+ .lvl { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-width: 0; }
.silenced { color: var(--up-text-inactive); }
.more { display: flex; justify-content: center; padding: 10px 0 4px; }
@media (max-width: 600px) {
diff --git a/server/web/src/pages/Projects.svelte b/server/web/src/pages/Projects.svelte
index e5cd787..40741bf 100644
--- a/server/web/src/pages/Projects.svelte
+++ b/server/web/src/pages/Projects.svelte
@@ -127,15 +127,14 @@
{#each projects as p (p.id)}
<div animate:reorder in:soft>
- <Card>
- {#snippet action()}
- <div class="row">
- <Button variant="ghost" size="sm" onclick={() => (editing = editing === p.id ? null : p.id)}>{editing === p.id ? 'Close' : 'Settings'}</Button>
+ <Card compact>
+ <div class="phead">
+ <ProjectIcon icon={p.icon} size={20} />
+ <div class="ptext">
+ <div class="pname"><span class="n">{p.name}</span><span class="mono muted caption">{p.slug}</span></div>
+ <div class="pmeta muted caption">{p.notify ? `notify ≥ ${LEVEL_LABEL[p.min_level].toLowerCase()}` : 'notifications off'} · created {relative(p.created_at)}</div>
</div>
- {/snippet}
- <div class="pname"><ProjectIcon icon={p.icon} size={18} /><span class="n">{p.name}</span></div>
- <div class="pmeta muted caption">
- <span class="mono">{p.slug}</span> · {p.notify ? `notify ≥ ${LEVEL_LABEL[p.min_level].toLowerCase()}` : 'notifications off'} · created {relative(p.created_at)}
+ <Button variant="ghost" size="sm" onclick={() => (editing = editing === p.id ? null : p.id)}>{editing === p.id ? 'Close' : 'Settings'}</Button>
</div>
{#if editing === p.id}
@@ -177,9 +176,11 @@
.actions { display: flex; justify-content: flex-end; margin-top: var(--up-space-4); }
.new { display: flex; gap: var(--up-space-3); align-items: center; }
.new :global(input:first-child) { flex: 1; }
- .pname { display: flex; align-items: center; gap: 8px; margin-top: -8px; }
- .n { font: var(--up-type-row-title); }
- .pmeta { margin-top: 2px; }
+ .phead { display: flex; align-items: center; gap: 12px; }
+ .ptext { flex: 1; min-width: 0; }
+ .pname { display: flex; align-items: baseline; gap: 8px; min-width: 0; }
+ .n { font: var(--up-type-row-title); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .pmeta { margin-top: 1px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.edit { margin-top: var(--up-space-4); }
@media (max-width: 520px) {
.new { flex-wrap: wrap; }
diff --git a/server/web/src/pages/Settings.svelte b/server/web/src/pages/Settings.svelte
index 2f62e1d..38d5505 100644
--- a/server/web/src/pages/Settings.svelte
+++ b/server/web/src/pages/Settings.svelte
@@ -5,6 +5,7 @@
import Button from '../lib/ui/Button.svelte'
import Select from '../lib/ui/Select.svelte'
import Input from '../lib/ui/Input.svelte'
+ import Switch from '../lib/ui/Switch.svelte'
import SettingRow from '../lib/ui/SettingRow.svelte'
import StatusDot from '../lib/ui/StatusDot.svelte'
import Notice from '../lib/ui/Notice.svelte'
@@ -73,6 +74,14 @@
load()
})
+ async function setMCP(v: boolean) {
+ try {
+ settings = await api.updateSettings({ mcp_enabled: v })
+ } catch (e: any) {
+ error = e.message
+ }
+ }
+
async function setRetention(v: string) {
try {
settings = await api.updateSettings({ retention_days: Number(v) })
@@ -123,6 +132,7 @@
{ value: '0', label: 'Unlimited' },
]
const lastPush = $derived(status?.last_push ?? null)
+ const origin = typeof location !== 'undefined' ? location.origin : ''
</script>
<div class="stack">
@@ -234,6 +244,13 @@
</SettingRow>
</Card>
+ <Card title="MCP">
+ <p class="secondary lead">Lets the AI assistant you already use read your events over the Model Context Protocol (read-only: list, search and inspect events and projects). Endpoint: <span class="mono">{status?.base_url ?? origin}/mcp</span>.</p>
+ <SettingRow label="MCP endpoint" hint={settings.mcp_token_set ? 'Connect with the BOOP_MCP_TOKEN bearer token, a device credential, or your admin login.' : 'No BOOP_MCP_TOKEN is set: device credentials and the admin login work; set the env var to give an agent its own token.'}>
+ <Switch checked={settings.mcp_enabled} onchange={setMCP} label="MCP endpoint" />
+ </SettingRow>
+ </Card>
+
<Card title="Silences">
<p class="secondary lead">Events matching a rule are still stored and shown, but never pushed to a phone. Add rules from an event's page or here. Fingerprint and source match exactly; title ignores case.</p>
<p class="lead" style="margin-top: 8px"><a href="/?silenced=true" onclick={link}>{silencedEvents} silenced event{silencedEvents === 1 ? '' : 's'}</a> · open one to unsilence it or push it now.</p>