:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobile): show pinned views in home screen widgets (#129763)
Chris Volzere1bd3adb085d
diff --git a/products/mobile/app.config.ts b/products/mobile/app.config.tsindex 5e4a1b2f4a7b..cc4cf9cc8e4d 100644--- a/products/mobile/app.config.ts+++ b/products/mobile/app.config.ts@@ -59,7 +59,7 @@ export default ({ config, projectRoot }: ConfigContext): ExpoConfig => {slug: 'posthog',owner: 'posthog',scheme,- version: '1.10.0',+ version: '1.11.0',orientation: 'default',userInterfaceStyle: 'automatic',icon: icons.png,diff --git a/products/mobile/app/_layout.tsx b/products/mobile/app/_layout.tsxindex d1ffb9a585d9..7200006d5129 100644--- a/products/mobile/app/_layout.tsx+++ b/products/mobile/app/_layout.tsx@@ -23,6 +23,7 @@ import { configureNotifications } from '@/features/notifications/pushRegistratioimport { useNotificationRouting } from '@/features/notifications/useNotificationRouting'import { usePushRegistration } from '@/features/notifications/usePushRegistration'import { useAutomaticUpdates } from '@/features/updates/useAutomaticUpdates'+import { useChartWidgetSync } from '@/features/widgets/useChartWidgetSync'import { track } from '@/lib/analytics'import { initAnalytics } from '@/lib/posthogClient'import { useScreenTracking } from '@/lib/useScreenTracking'@@ -107,6 +108,7 @@ export default function RootLayout(): ReactElement {useScreenTracking(ready)usePushRegistration()useHedgehogWidgetSync()+ useChartWidgetSync()useNotificationRouting()useAutomaticUpdates(ready && segments[0] === '(tabs)')diff --git a/products/mobile/app/views/dashboard/[id].tsx b/products/mobile/app/views/dashboard/[id].tsxindex d95a5e1ca7b9..87516e5548bf 100644--- a/products/mobile/app/views/dashboard/[id].tsx+++ b/products/mobile/app/views/dashboard/[id].tsx@@ -3,8 +3,16 @@ import type { ReactElement } from 'react'import { DashboardScreen } from '@/features/views/dashboard/DashboardScreen'import { displayModeParam, viewEntryParam } from '@/features/views/viewRoutes'+import { useWidgetOpenedEvent, widgetFamilyParam } from '@/features/widgets/useWidgetOpenedEvent'export default function DashboardRoute(): ReactElement {- const { id, from, mode } = useLocalSearchParams<{ id: string; from?: string; mode?: string }>()- return <DashboardScreen dashboardRef={id ?? ''} from={viewEntryParam(from)} displayMode={displayModeParam(mode)} />+ const { id, from, mode, family } = useLocalSearchParams<{+ id: string+ from?: string+ mode?: string+ family?: string+ }>()+ const entry = viewEntryParam(from)+ useWidgetOpenedEvent('dashboard', entry, widgetFamilyParam(family))+ return <DashboardScreen dashboardRef={id ?? ''} from={entry} displayMode={displayModeParam(mode)} />}diff --git a/products/mobile/app/views/insight/[shortId].tsx b/products/mobile/app/views/insight/[shortId].tsxindex bf2eabece573..bcfaf65c0b3c 100644--- a/products/mobile/app/views/insight/[shortId].tsx+++ b/products/mobile/app/views/insight/[shortId].tsx@@ -3,21 +3,25 @@ import type { ReactElement } from 'react'import { InsightScreen } from '@/features/views/insight/InsightScreen'import { displayModeParam, numberParam, viewEntryParam } from '@/features/views/viewRoutes'+import { useWidgetOpenedEvent, widgetFamilyParam } from '@/features/widgets/useWidgetOpenedEvent'export default function InsightRoute(): ReactElement {- const { shortId, fromDashboard, insightId, from, mode } = useLocalSearchParams<{+ const { shortId, fromDashboard, insightId, from, mode, family } = useLocalSearchParams<{shortId: stringfromDashboard?: stringinsightId?: stringfrom?: stringmode?: string+ family?: string}>()+ const entry = viewEntryParam(from)+ useWidgetOpenedEvent('insight', entry, widgetFamilyParam(family))return (<InsightScreenshortId={shortId ?? ''}fromDashboard={fromDashboard || null}insightId={numberParam(insightId)}- from={viewEntryParam(from)}+ from={entry}displayMode={displayModeParam(mode)}/>)diff --git a/products/mobile/docs/ARCHITECTURE.md b/products/mobile/docs/ARCHITECTURE.mdindex d33c9604de3e..73f660430ebe 100644--- a/products/mobile/docs/ARCHITECTURE.md+++ b/products/mobile/docs/ARCHITECTURE.md@@ -91,6 +91,9 @@ products/mobile/settings/ SettingsScreen, ProjectSwitcher, PushStatusGroup, SignOutSection, appInfo,EnvironmentGroup (internal builds), LegalGroup, SettingsLinkRow, SettingsRadioRow,DefaultPageGroup, defaultPageStore (the tab the app opens on)+ widgets/ chartWidgetSync (session copy and pin catalog for the Chart home screen widget),+ chartWidgetCatalog (buildCatalog), useChartWidgetSync, useWidgetOpenedEvent;+ see modules/chart-widget/README.mdlib/ analytics, posthogClient, dates, errors, haptics, markdownIt (the shared safe parser),deepLinkKind (link kind for analytics, webLinkTarget for issue and recording links),richText, useAsyncAction, useNow,diff --git a/products/mobile/docs/VIEWS.md b/products/mobile/docs/VIEWS.mdindex ba9462ed77f0..642bff1c32c7 100644--- a/products/mobile/docs/VIEWS.md+++ b/products/mobile/docs/VIEWS.md@@ -41,6 +41,16 @@ A complete pin list read forgets the prefs of that project's pins that are gone.Recent merges the last 20 views opened on this phone (`views-recent:v1`, per project) with the dashboards this user viewed on the web.Insights viewed on the web do not appear: no per-user source is open to OAuth without a new scope.+**Home screen widget.** The Chart widget on iOS and Android shows a pin from this list, and the OS picker offers the same pins as the Views page (up to 100), in Views order.+A new iOS widget shows the first supported pin automatically, including when its pins arrive after placement. Edit Widget lets you change it. Android preselects the first supported pin in its setup screen.+The iOS picker keeps unsupported pins visible with a reason, so an unsupported list does not appear empty.+After each complete pin list read, insight or dashboard update, and each change of a pin's mode or tile, `src/features/widgets/chartWidgetSync.ts` writes a pin catalog for the widget.+When the signed-in project has no catalog and no cached pin list, after a sign in, a project switch or a launch, the sync reads the pin list itself with the same query key and lane as `usePins`, once per project per session. A failure leaves the catalog for the next Views read.+All readable insight pins are available, including SQL numbers, text values, time series, tables, funnels, retention and breakdowns. Numbers retain their saved formatting and use a prominent centered layout. Charts show date and value labels, a formatted headline and the latest point; tables and other non-time-series displays use compact rows. A dashboard pin uses the tile chosen on this phone, or discovers a suitable tile using the same automatic preview rules as Views. This does not change the pin's display preference. The app shares its available Views snapshot with the widget, which refreshes independently using the same result semantics.+The catalog uses metadata the list already read. Only pins selected on placed widgets receive result snapshots. For selected widgets, it reads uncached pin results with `refresh=force_cache`, at most once per second, and leaves half of each insights request budget available for foreground Views reads. Pending reads stop when the session or project changes.+The widget reads its pin by itself on a timer with `refresh=force_cache`, so it never computes; see [the widget's README](../modules/chart-widget/README.md).+The widget holds a copy of the access token only while a Chart widget is placed, and never refreshes it. Widget data is encrypted in shared storage. Without a placed widget, the app keeps encrypted picker metadata but sends no widget credentials or result snapshots and reads only pin metadata for the picker. Losing Views access clears the widget data. On launch or when the app returns to the foreground with an OAuth token that expires within 24 hours, it refreshes the token once (`FOREGROUND_REFRESH_MARGIN_MS` in `src/auth/authStore.ts`), so the copy stays valid between app opens. A token with at least one minute left refreshes after session restoration, without holding the launch screen.+## Automatic pin previewsThe Pinned section shows each real pin once. For up to three pins without a display choice on this phone,@@ -156,7 +166,8 @@ Their Browse rows send `mobile_browse_list_opened` (`section`: `dashboards` or `| Full-screen chart | `/views/chart/{short_id}[?key={cache key}]` || Browse lists | `/views/browse/dashboards`, `/views/browse/insights` |-`from` is the `ViewEntry` (`pinned`, `recent`, `browse`, `search` or `dashboard`) for `mobile_view_opened`; `mode` is the pin's display mode.+`from` is the `ViewEntry` (`pinned`, `recent`, `browse`, `search`, `dashboard` or `widget`) for `mobile_view_opened`; `mode` is the pin's display mode.+A home screen widget opens a dashboard or insight with `from=widget&family=<small|medium|large>`, which also sends `mobile_widget_opened` (`kind`, `family`).Build links with `src/features/views/viewRoutes.ts` (`viewHref`, `dashboardHref`, `insightHref`, `webAnalyticsHref`, `chartHref`), never by hand.An insight opened from a tile also carries `fromDashboard` and `insightId`: it reads with `from_dashboard` and shares the dashboard's session range.Deep links work: `posthog://views/dashboard/demo-dash-kpis`, `posthog://views/insight/demo-ins-dau`, `posthog://views/web-analytics`.diff --git a/products/mobile/modules/chart-widget/README.md b/products/mobile/modules/chart-widget/README.mdindex a725c1bffbb3..f32616b7b0a6 100644--- a/products/mobile/modules/chart-widget/README.md+++ b/products/mobile/modules/chart-widget/README.md@@ -3,14 +3,15 @@A home-screen widget for iOS and Android that shows a pinned insight from the Views tab and reads PostHog by itself.See the sections below for the store contract, the fetch rules and the identifiers.-The widget shows one pin as a number and sparkline (small), one pin as a chart with its value and change (medium), or one chart plus up to two number tiles (large).-The person picks the pin in the OS: the Edit widget sheet on iOS, the configure screen on Android.+The widget shows one pin as a number, chart or compact rows (small and medium), or one pin plus up to two extra tiles (large). Number widgets center a large value and its change. Charts show a formatted headline, date endpoints and labeled value bounds; a single-series chart without an aggregate labels its headline “Latest”. Medium and large charts keep the full saved series (up to 60 points), rather than silently cropping to the last 14. Refresh age stays secondary to the data. A dashboard pin shows its selected insight. Numbers preserve saved currency, percentage, prefix, suffix and precision settings; text and boolean SQL values remain text.+An iOS widget with no saved selection shows the first supported pin in Views order, including when the catalog arrives after placement.+The person can change it in the Edit Widget sheet. Android preselects the first supported pin in its configure screen.The app itself shows nothing about widgets.## How it worksThe app and the widget share a small store.-The app writes the session copy and the pin catalog; the widget writes one snapshot per pin.+The app writes an encrypted pin catalog for the picker. When a Chart widget is placed, it also writes the session copy and snapshots for its selected pins; the widget refreshes one snapshot per pin.The widget never runs the app's JavaScript and never refreshes the OAuth token.```text@@ -39,17 +40,19 @@ That function subscribes to the stores below, so auth and Views do not import th| Sign out, expired session (`addSessionEndTask`), signed-out launch, demo mode starts | Clears the catalog, the credentials and every cached chart |Each write makes the OS reload every placed widget, so the app keeps the last JSON it wrote in memory and skips an identical write.-A clear resets that memory, so the next sign in writes again even with the same token.+A clear resets that memory, so the next sign in writes again even with the same token. Session-end cleanup retires the current token generation before clearing; queued and active work cannot republish it while an account replacement is pending. A committed sign-in starts a new generation and resumes sync.Writes happen only while the auth store and the stored session name the same host and user, so a sign in never pairs one account's token with another account's project.When the signed-in project has no catalog and no cached pin list, the sync reads the pin list itself, with the query key, fetcher (`readShortcuts` in `src/features/views/listReads.ts`) and lane that `usePins` uses.-It does that once per project per session, and only when the session has the Views scopes; a failure leaves the catalog for the next Views read.+It does that once per project per session, only when the session has the Views scopes; a failure leaves the catalog for the next Views read.Until the new project's catalog lands after a project switch, the widget shows "In another project".The widget never refreshes the OAuth token.On each return to the foreground, the app refreshes an OAuth access token with less than 24 hours left (`FOREGROUND_REFRESH_MARGIN_MS` in `src/auth/authStore.ts`), then writes the new copy, so the widget's token stays valid between app opens.-The catalog takes each pin's insight from what the Views list already read: the pin metadata cache (`viewsKeys.pinMetadata`), else the pin's Number or Chart snapshot.-For up to 30 pins without either, the sync reads `GET insights/?short_id=&basic=true&refresh=force_cache` through the list-read lane (`listRead('insights')`), one at a time, and stores the answer in the same metadata cache.+The catalog takes each pin's insight from the newest available pin metadata or Number/Chart snapshot.+Insight, dashboard and automatic preview updates also rebuild the catalog, so opening a pin in Views recovers an earlier metadata failure.+A dashboard without a manually chosen tile reuses the Views automatic preview cache or discovers a suitable tile before widget selection, without changing the pin's display preference. Ready pins publish immediately; background metadata reads fill in the remaining choices incrementally. Cache updates publish even while another read is pending, and an older response cannot replace newer app data.+For selected pins without either, the sync reads the full insight with `refresh=force_cache` through the list-read lane (`listRead('insights')`), one at a time, and stores the answer in the metadata and Views caches. Dashboard reads include `from_dashboard`, and snapshots are scoped to each pin so two dashboard contexts do not overwrite each other.A 429, a 503, an empty budget bucket or no connection stops the reads; those pins say "Open it in Views first" until the next sync.The sync never forces a compute.@@ -58,18 +61,22 @@ A widget tap opens `/views/insight/<short_id>?from=widget&family=<family>` or `/## Store contract-| Data | iOS | Android | Writer |-| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------ |-| Credentials | Keychain generic password: service `com.posthog.code.mobile.chart-widget`, account `credentials`, access group `group.<app bundle id>`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`; data is the UTF-8 JSON | `EncryptedSharedPreferences` file `chart_widget_secure` (MasterKey AES256_GCM), key `credentials`, written with `commit()` | App |-| Catalog | `UserDefaults(suiteName: "group.<app bundle id>")`, key `chart.catalog` | `SharedPreferences` file `chart_widget`, key `chart.catalog` | App |-| Snapshot of one pin | same suite, key `chart.snapshot.<pinId>` | `chart_widget`, key `chart.snapshot.<pinId>` | Widget |-| Last error of one pin | same suite, key `chart.snapshotError.<pinId>` | `chart_widget`, key `chart.snapshotError.<pinId>` | Widget |-| Project of one pin | same suite, key `chart.pinProject.<pinId>` = `{ "projectId": number, "projectName": string }` | kept per widget in `chart.widget.<appWidgetId>` as `projectId`, `projectName` and `pinName`, written at configure time | Widget |-| Widget configuration | the widget's configuration intent, kept by WidgetKit | `chart_widget`, key `chart.widget.<appWidgetId>` = `{ "pinId": string, "extraPinIds": string[] }` | Widget |+| Data | iOS | Android | Writer |+| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------- |+| Credentials | Keychain generic password: service `com.posthog.code.mobile.chart-widget`, account `credentials`, access group `group.<app bundle id>`, `kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`; data is the UTF-8 JSON | `EncryptedSharedPreferences` file `chart_widget_secure` (MasterKey AES256_GCM), key `credentials`, written with `commit()` | App |+| Catalog | AES-GCM encrypted `UserDefaults(suiteName: "group.<app bundle id>")`, key `chart.catalog` | `EncryptedSharedPreferences` file `chart_widget_secure`, key `chart.catalog` | App |+| Snapshot of one pin | same encrypted suite, key `chart.snapshot.<pinId>` | `chart_widget_secure`, key `chart.snapshot.<pinId>` | App or widget |+| Last error of one pin | same encrypted suite, key `chart.snapshotError.<pinId>` | `chart_widget_secure`, key `chart.snapshotError.<pinId>` | Widget |+| Project of one pin | same encrypted suite, key `chart.pinProject.<pinId>` = `{ "projectId": number, "projectName": string }` | kept per widget in `chart.widget.<appWidgetId>` as `projectId`, `projectName` and `pinName`, written at configure time | Widget |+| Widget configuration | the widget's configuration intent, kept by WidgetKit | `chart_widget_secure`, key `chart.widget.<appWidgetId>` = `{ "pinId": string, "extraPinIds": string[] }` | Widget |The suite is the hedgehog widget's App Group.An App Group id is also a keychain access group of every target in the group, so the extension reads the credentials without a keychain-sharing entitlement.-The credentials stay out of `UserDefaults` because the suite is a plain file in the group container.+Credentials stay in the keychain. Every `chart.*` value in the App Group suite is AES-GCM encrypted with a device-only 256-bit key stored alongside the credentials in the shared keychain. Both native targets compile the same storage implementation. Old plaintext entries are discarded, and unreadable encrypted values have no plaintext fallback.++Android stores the catalog, snapshots, errors and configuration in `chart_widget_secure`, alongside credentials. Valid saved widget selections migrate from `chart_widget` before its plaintext values are cleared. Existing encrypted selections take precedence; legacy snapshots and credentials are discarded.++`getWidgetState()` checks placed Chart widgets with WidgetKit on iOS and AppWidgetManager on Android. Only their selected pins receive result snapshots. The app checks placement on launch and foreground and before catalog writes; Android also clears credentials when the last widget is deleted. Picker metadata remains encrypted for first-time setup. Android can confirm a selection without widget credentials, then opens the app to synchronize the session after placement. Unselected pins use basic metadata reads, which exclude result rows. Loss of Views access clears the catalog and snapshots; missing or inaccessible pins lose their cached results. The iOS content boundary is privacy-sensitive so WidgetKit can redact account-derived text.### Credentials JSON@@ -92,7 +99,7 @@ The widget treats `now > expiresAt - 60000` as expired and sends no request.### Catalog JSONReplaced whole on each write.-Pins are in Views order, at most 30.+Pins are in Views order, up to the same 100-pin page as Views. A page with a next link does not replace the complete catalog.```json{@@ -113,6 +120,7 @@ Pins are in Views order, at most 30."eligible": true,"number": true,"chart": true,+ "displayMode": "chart","reason": null},{@@ -126,6 +134,7 @@ Pins are in Views order, at most 30."eligible": true,"number": true,"chart": true,+ "displayMode": "chart","reason": null},{@@ -136,38 +145,37 @@ Pins are in Views order, at most 30."insightId": 789,"shortId": "ghi789","dashboardId": null,- "eligible": false,+ "eligible": true,"number": false,"chart": false,- "reason": "Not a chart over time"+ "displayMode": "row",+ "reason": null}]}```-| Field | Meaning |-| ------------- | ---------------------------------------------------------------------------------------------------------------------------- |-| `id` | The pin's `shortcutId` (`PinView.shortcutId`). The widget configuration stores it. |-| `subtitle` | "Insight" for an insight pin. For a dashboard pin, "<dashboard name> · <tile name>", or "Dashboard" before a tile is chosen. |-| `insightId` | Null when the app has not read the insight. The widget then reads by `shortId`. |-| `shortId` | The insight's `short_id`: the pin's `ref`, or the chosen tile's insight. Null for a dashboard pin without a tile. |-| `dashboardId` | The dashboard's numeric id, sent as `from_dashboard`. Null for an insight pin. |-| `number` | `capabilitiesOf(query).number` (`src/model/adapters/insightSnapshot.ts`): one series or a big number, without a breakdown. |-| `chart` | `capabilitiesOf(query).chart`: a line or bar trends chart over time. |-| `eligible` | A `TrendsQuery` with `number` or `chart`. iOS leaves other pins out of the picker; Android shows them grayed with `reason`. |-| `reason` | Null when eligible, else one of the reasons below. |--| Reason | When |-| --------------------------------- | --------------------------------------------------------------------------------------------------------- |-| "Choose a tile in Views first" | A dashboard pin without a tile chosen on this phone (`PinDisplay.insightId`). |-| "Open it in Views first" | The app has not read the insight yet. |-| "Couldn't find this insight" | The server no longer returns the insight, or it is deleted. |-| "Not supported on the widget yet" | A SQL insight (`HogQLQuery`). |-| "Not a chart over time" | Any other kind, or a trends insight that is neither a number nor a line or bar chart (`tileLimitReason`). |+| Field | Meaning |+| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `id` | The pin's `shortcutId` (`PinView.shortcutId`). The widget configuration stores it. |+| `subtitle` | "Insight" for an insight pin. For a dashboard pin, "<dashboard name> · <tile name>", or "Dashboard" before a tile is chosen. |+| `insightId` | Null when the app has not read the insight. The widget then reads by `shortId`. |+| `shortId` | The insight's `short_id`: the pin's `ref`, or the chosen tile's insight. Null for a dashboard pin without a tile. |+| `dashboardId` | The dashboard's numeric id, sent as `from_dashboard`. Null for an insight pin. |+| `number` | The Views snapshot's number capability: one meaningful value, including SQL big numbers. |+| `chart` | The Views snapshot's chart capability, including SQL time series. |+| `eligible` | Any readable insight with a query, including a dashboard's selected tile. Missing or unread pins carry a reason. Only eligible pins are automatic defaults. |+| `reason` | Null when eligible, else one of the reasons below. |++| Reason | When |+| ------------------------------ | ----------------------------------------------------------------------------- |+| "Choose a tile in Views first" | A dashboard pin without a tile chosen on this phone (`PinDisplay.insightId`). |+| "Open it in Views first" | The app has not read the insight yet. |+| "Couldn't find this insight" | The server no longer returns the insight, or it is deleted. |### Snapshot JSON-Written by the widget after a good read, the same shape on both platforms.+Written by the app from the Views adapter when available, and by the widget after a good read, with the same shape on both platforms. Catalog pins can include this object as `snapshot` and the Views preference as `displayMode`. A changed insight, dashboard, project or mode clears the old cached rendering. Newer snapshots win, and in-flight reads for an old selection or account are discarded.The widget renders from it when a later read fails.The age it shows is from `lastRefreshAt` (when the server computed the numbers), else `fetchedAt`; with several pins on screen, the oldest.@@ -184,12 +192,18 @@ The age it shows is from `lastRefreshAt` (when the server computed the numbers),"deltaText": "12%","deltaBasis": "vs. previous 14 days","series": [{ "label": "Signups", "points": [{ "at": "2026-10-22", "value": 72 }], "previous": false }],- "chartKind": "line"+ "chartKind": "line",+ "display": "chart",+ "rows": []}```The error record is `{ "at": <epoch ms>, "kind": "network" | "auth" | "not_found" | "rate_limited" | "bad_data" | "no_result" }`.+The optional `chartValueText`, `axisLowText` and `axisHighText` preserve the insight’s number formatting for chart headlines and value bounds. An aggregate in `valueText` takes precedence over the latest point; multi-series charts do not invent a single headline.++The optional `display` is `number`, `chart` or `rows`; `rows` contains `{ "label": "...", "value": "..." }` entries. Older snapshots without these fields still render. Snapshots hold at most 12 rows and 60 points per series; a widget shows as many rows as fit. Funnels show step counts and conversion; retention shows available cohort percentages; category charts and tables show compact rows. Other insight result shapes use compact labeled values. `InsightParser.swift` and `InsightParser.kt` mirror the Views adapters for background refreshes. Shared invented fixtures in `fixtures/insights.json` are checked by the TypeScript, Swift and Kotlin checks.+### Reads`{host}/api/projects/{projectId}/insights/{insightId}/?refresh=force_cache`, plus `&from_dashboard={dashboardId}` for a dashboard pin.@@ -219,7 +233,7 @@ The widget only reads what the server already computed: never `blocking`, never| State | Text || -------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| Not configured | "Choose a pin", then "Touch and hold to pick a pin from your Views tab" |+| No supported pins | "No chart pins available", then "Open Views to pin an insight or choose a dashboard tile" || No credentials, demo mode | "Sign in to see your pins", then "Open PostHog to sign in" || Expired or rejected token | "Open PostHog to update" || Pin missing from catalog | "<name> is no longer pinned" |@@ -229,7 +243,7 @@ The widget only reads what the server already computed: never `blocking`, never| First read pending | The title, "Loading…" and a placeholder sparkline. Only for a pin never read || No cached result | The title, then "Open it in PostHog to load this insight"; links to the insight |-A state links to `<scheme>://views`; a chart links to the pin's view with `from=widget` (see "How it works").+A state links to `<scheme>://views`; a selected pin that is still loading and a chart link to the pin's view with `from=widget` (see "How it works").The scheme is `posthog`, `posthog-dev` or `posthog-preview` by build variant (`src/lib/appVariants.json`).### Identifiers@@ -263,17 +277,17 @@ App code calls `syncWidgetCredentials`, `syncWidgetCatalog` and `clearWidgetStatRemoteViews only (no Glance, no Compose), API 24 and up. Code in `android/src/main/java/com/posthog/code/mobile/chart/`:-| File | Role |-| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |-| `ChartModels.kt` | Credentials, catalog, widget config, snapshot and error JSON (`org.json`). |-| `ChartStore.kt` | The two preferences files below. Every write uses `commit()`. |-| `TrendsParser.kt` | Insight response to snapshot: mirrors `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts`, `rangePresets.ts`. |-| `ChartFetcher.kt` | One `HttpURLConnection` read per pin, `refresh=force_cache`, 20 s timeouts, status to error kind. |-| `ChartWidgetRefresh.kt` | `refreshAll(context)`: render from the cache on a background executor, then queue one network pass. |-| `ChartRefreshWorker.kt` | The `WorkManager` pass: each distinct pin once, then a render of every widget. |-| `ChartRenderer.kt`, `ChartCanvas.kt` | Layout choice, states, text, deep links; the chart drawn on a `Canvas` into a `Bitmap`. |-| `ChartWidgetProvider.kt` | The `AppWidgetProvider`. Every callback is wrapped, because a receiver exception kills the app process. |-| `ChartWidgetConfigureActivity.kt` | "Choose a pin", a plain `Activity` built from views. |+| File | Role |+| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| `ChartModels.kt` | Credentials, catalog, widget config, snapshot and error JSON (`org.json`). |+| `ChartStore.kt` | The two preferences files below. Every write uses `commit()`. |+| `TrendsParser.kt` and `InsightParser.kt` | Insight response to snapshot: mirrors `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts`, `rangePresets.ts`. |+| `ChartFetcher.kt` | One `HttpURLConnection` read per pin, `refresh=force_cache`, 20 s timeouts, status to error kind. |+| `ChartWidgetRefresh.kt` | `refreshAll(context)`: render from the cache on a background executor, then queue one network pass. |+| `ChartRefreshWorker.kt` | The `WorkManager` pass: each distinct pin once, then a render of every widget. |+| `ChartRenderer.kt`, `ChartCanvas.kt` | Layout choice, states, text, deep links; the chart drawn on a `Canvas` into a `Bitmap`. |+| `ChartWidgetProvider.kt` | The `AppWidgetProvider`. Every callback is wrapped, because a receiver exception kills the app process. |+| `ChartWidgetConfigureActivity.kt` | "Choose a pin", a plain `Activity` built from views. |### Identifiers@@ -281,8 +295,8 @@ RemoteViews only (no Glance, no Compose), API 24 and up. Code in `android/src/ma| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Provider | receiver `com.posthog.code.mobile.chart.ChartWidgetProvider`, info `res/xml/chart_widget_info.xml` || Configure activity | `com.posthog.code.mobile.chart.ChartWidgetConfigureActivity` (`APPWIDGET_CONFIGURE`, exported) |-| Plain preferences | `chart_widget`: `chart.catalog`, `chart.snapshot.<pinId>`, `chart.snapshotError.<pinId>`, `chart.widget.<appWidgetId>` |-| Secure preferences | `chart_widget_secure` (`EncryptedSharedPreferences`, `MasterKey` AES256_GCM): `credentials` |+| Legacy preferences | `chart_widget`: cleared on access |+| Secure preferences | `chart_widget_secure` (`EncryptedSharedPreferences`, `MasterKey` AES256_GCM): credentials, catalog, snapshots, errors and widget configuration || Work | unique `chart-widget-refresh` (REPLACE, network required), `chart-widget-keep-enabled` || Deep links | `<scheme>://views/insight/<shortId>?from=widget&family=<small\|medium\|large>`, `<scheme>://views/dashboard/<dashboardId>?from=widget&family=…`, states open `<scheme>://views` |@@ -303,7 +317,7 @@ Catalog changes discard snapshots and errors for removed pins or changed insightIt queues nothing when no widget is placed or the token is missing or expired; the widget then shows its state.- The pass reads each distinct pin of every placed widget once, writes the snapshot (which clears its error) or the error, then renders all widgets.A rejected token stops the pass and marks the remaining pins `auth`. A new token from the app clears every `auth` error.- Responses are discarded if the session or catalog changed, or if the worker was canceled.+ Responses are discarded if the session or catalog changed, or if the worker was canceled. A failure from a request older than the current snapshot cannot hide or delete that snapshot.A 429 or 503 stops the pass and pauses every pin for at least one minute, or longer when `Retry-After` says so.- WorkManager disables its reschedule receiver when no work is pending, and that component change makes the system send `APPWIDGET_UPDATE` again.A no-op job 10 years out (`chart-widget-keep-enabled`) stays queued while a widget is placed, so that loop cannot start. `onDisabled` cancels both.@@ -331,27 +345,27 @@ Catalog changes discard snapshots and errors for removed pins or changed insight## Chart widget (iOS)The iOS widget is a second kind in the `HedgehogWidget` extension (`targets/HedgehogWidget/`).-It reads the catalog and its snapshots from the App Group suite and the credentials from the keychain, and it reads PostHog itself.--| File | What it holds |-| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |-| `AppGroup.swift` | The App Group id from the extension's bundle id, shared with the hedgehog's `SharedStore` |-| `ChartModels.swift` | `Codable` shapes of the credentials, catalog, snapshot and snapshot error JSON |-| `ChartStore.swift` | Store keys, snapshot, error and pin project reads and writes, the keychain read (Foundation + Security) |-| `ChartFetcher.swift` | The cache-only insight read, status mapping, and `ChartRefresh` (one request per pin at a time) |-| `TrendsParser.swift` | `TrendsQuery` response to snapshot, mirroring `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts` and `rangePresets.ts` |-| `ChartState.swift` | Which state each slot shows, which pins a refresh reads, deep links, age text, gallery sample data |-| `ChartWidgetIntent.swift` | `ChartWidgetIntent`, `PinEntity` and `PinQuery` (the Edit widget picker) |-| `ChartTimelineProvider.swift` | `AppIntentTimelineProvider`: reads, writes snapshots, builds entries |-| `ChartViews.swift` | SwiftUI for small, medium and large, light and dark |-| `ChartWidget.swift` | The `AppIntentConfiguration`, registered in `HedgehogWidgetBundle.swift` |+It reads encrypted catalog and snapshot values from the App Group suite and their key and credentials from the keychain, and it reads PostHog itself.++| File | What it holds |+| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |+| `AppGroup.swift` | The App Group id from the extension's bundle id, shared with the hedgehog's `SharedStore` |+| `ChartModels.swift` | `Codable` shapes of the credentials, catalog, snapshot and snapshot error JSON |+| `ChartStore.swift` | Store keys, snapshot, error and pin project reads and writes, the keychain read (Foundation + Security) |+| `ChartFetcher.swift` | The cache-only insight read, status mapping, and `ChartRefresh` (one request per pin at a time) |+| `TrendsParser.swift` and `InsightParser.swift` | Insight response to snapshot, mirroring `insightSnapshot.ts`, `insightFormatting.ts`, `snapshotChart.ts` and `rangePresets.ts` |+| `ChartState.swift` | Which state each slot shows, which pins a refresh reads, deep links, age text, gallery sample data |+| `ChartWidgetIntent.swift` | `ChartWidgetIntent`, `PinEntity` and `PinQuery` (the Edit widget picker) |+| `ChartTimelineProvider.swift` | `AppIntentTimelineProvider`: reads, writes snapshots, builds entries |+| `ChartViews.swift` | SwiftUI for small, medium and large, light and dark |+| `ChartWidget.swift` | The `AppIntentConfiguration`, registered in `HedgehogWidgetBundle.swift` |### Native checkFrom `products/mobile` on macOS:```sh-swiftc targets/HedgehogWidget/{AppGroup,ChartModels,ChartStore,ChartFetcher,TrendsParser,ChartState}.swift scripts/check_chart_widget.swift -o /tmp/check-chart+swiftc targets/HedgehogWidget/{AppGroup,ChartModels,ChartStorage,ChartStore,ChartFetcher,TrendsParser,InsightParser,ChartState}.swift scripts/check_chart_widget.swift -o /tmp/check-chart/tmp/check-chart```@@ -366,7 +380,7 @@ The SwiftUI, WidgetKit and AppIntents files do not compile there; `xcodebuild` c| Widget | kind `ChartWidget`, target `HedgehogWidget`, families small, medium, large || Configuration | `ChartWidgetIntent` ("Chart"): `pin: PinEntity?`, `extraPins: [PinEntity]?` (large only) || Picker entity | `PinEntity`, id = the catalog pin id; `PinQuery` lists eligible pins in Views order |-| Store | `UserDefaults(suiteName: "group.<app bundle id>")`, keys `chart.catalog`, `chart.snapshot.<pinId>`, `chart.snapshotError.<pinId>`, `chart.pinProject.<pinId>` |+| Store | AES-GCM encrypted `UserDefaults(suiteName: "group.<app bundle id>")`, keys `chart.catalog`, `chart.snapshot.<pinId>`, `chart.snapshotError.<pinId>`, `chart.pinProject.<pinId>` || Credentials | keychain generic password, service `com.posthog.code.mobile.chart-widget`, account `credentials`, access group `group.<app bundle id>` || Deep links | `<scheme>://views/insight/<shortId>?from=widget&family=<small\|medium\|large>`, `<scheme>://views/dashboard/<dashboardId>?from=widget&family=...`; states open `<scheme>://views` |diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.ktindex cb737784e06f..220efdbd8a08 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartCanvas.kt@@ -9,6 +9,8 @@ import android.graphics.LinearGradientimport android.graphics.Paintimport android.graphics.Pathimport android.graphics.Shader+import android.text.TextPaint+import android.text.TextUtilsimport kotlin.math.absimport kotlin.math.maximport kotlin.math.min@@ -21,6 +23,7 @@ internal class ChartColors(val barNeutral: Int,val ink: Int,val hairline: Int,+ val surface: Int,) {companion object {private val SERIES = listOf(@@ -50,6 +53,7 @@ internal class ChartColors(barNeutral = themed.getColor(R.color.chart_widget_bar_neutral),ink = themed.getColor(R.color.chart_widget_ink),hairline = themed.getColor(R.color.chart_widget_hairline),+ surface = themed.getColor(R.color.chart_widget_surface),)}}@@ -62,11 +66,14 @@ internal class ChartSpec(val bars: Boolean,val inProgress: Boolean,val grid: Boolean,+ val lowLabel: String? = null,+ val highLabel: String? = null,+ val startLabel: String? = null,+ val endLabel: String? = null,)internal object ChartCanvas {private const val MAX_BITMAP_BYTES = 1.5 * 1024 * 1024- private const val LINE_PADDING_RATIO = 0.1/** Null when there is nothing to draw or no room. `density` is px per dp at the size the launcher shows. */fun draw(spec: ChartSpec, colors: ChartColors, widthPx: Int, heightPx: Int, density: Float): Bitmap? {@@ -78,7 +85,43 @@ internal object ChartCanvas {val dp = density * scaleval bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)val canvas = Canvas(bitmap)- if (spec.bars) drawBars(canvas, spec, colors, width, height, dp) else drawLines(canvas, spec, colors, width, height, dp)+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = 9f * dp; color = withAlpha(colors.ink, 0.48f) }+ val labels = spec.grid && spec.lowLabel != null && spec.highLabel != null+ val right = if (labels) min(width * 0.25f, max(paint.measureText(spec.lowLabel), paint.measureText(spec.highLabel)) + 10f * dp) else 0f+ val bottom = if (spec.grid && spec.startLabel != null) 15f * dp else 0f+ val plotWidth = max(1, (width - right).toInt())+ val plotHeight = max(1, (height - bottom).toInt())+ if (spec.bars) drawBars(canvas, spec, colors, plotWidth, plotHeight, dp) else drawLines(canvas, spec, colors, plotWidth, plotHeight, dp)+ if (labels) {+ paint.textAlign = Paint.Align.RIGHT+ canvas.drawText(TextUtils.ellipsize(spec.highLabel, paint, right - 4f * dp, TextUtils.TruncateAt.END).toString(), width.toFloat(), -paint.ascent(), paint)+ if (spec.lowLabel != spec.highLabel) canvas.drawText(TextUtils.ellipsize(spec.lowLabel, paint, right - 4f * dp, TextUtils.TruncateAt.END).toString(), width.toFloat(), plotHeight.toFloat(), paint)+ }+ if (spec.grid && spec.startLabel != null) {+ paint.textAlign = Paint.Align.LEFT+ canvas.drawText(spec.startLabel, 0f, height.toFloat(), paint)+ paint.textAlign = Paint.Align.RIGHT+ canvas.drawText(spec.endLabel ?: "", plotWidth.toFloat(), height.toFloat(), paint)+ }+ return bitmap+ }++ fun rows(rows: List<SnapshotRow>, colors: ChartColors, width: Int, height: Int, density: Float): Bitmap? {+ if (width <= 0 || height <= 0) return null+ val scale = min(1.0, sqrt(MAX_BITMAP_BYTES / (width.toDouble() * height * 4))).toFloat()+ val bitmap = Bitmap.createBitmap(max(1, (width * scale).toInt()), max(1, (height * scale).toInt()), Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bitmap)+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { textSize = 11 * density * scale; color = colors.ink }+ val rowHeight = 20 * density * scale+ val limit = min(rows.size, max(1, (bitmap.height / rowHeight).toInt()))+ rows.take(limit).forEachIndexed { index, row ->+ val y = rowHeight * index - paint.ascent()+ val valueWidth = min(bitmap.width * 0.55f, paint.measureText(row.value))+ val value = TextUtils.ellipsize(row.value, paint, valueWidth, TextUtils.TruncateAt.END).toString()+ val label = TextUtils.ellipsize(row.label, paint, bitmap.width - valueWidth - 8 * density * scale, TextUtils.TruncateAt.END).toString()+ canvas.drawText(label, 0f, y, paint)+ canvas.drawText(value, bitmap.width - paint.measureText(value), y, paint)+ }return bitmap}@@ -100,7 +143,7 @@ internal object ChartCanvas {hi = max(0.0, finite.max())} else {val span = finite.max() - finite.min()- val pad = if (span > 0) span * LINE_PADDING_RATIO else abs(finite.max()) * 0.1+ val pad = if (span > 0) 0.0 else abs(finite.max()) * 0.1lo = finite.min() - padhi = finite.max() + padif (finite.min() >= 0 && lo < 0) lo = 0.0@@ -112,16 +155,17 @@ internal object ChartCanvas {private fun drawGrid(canvas: Canvas, colors: ChartColors, scale: Scale, width: Int, dp: Float) {val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {color = colors.hairline- strokeWidth = max(1f, dp * 0.75f)+ strokeWidth = max(1f, dp * 0.65f)+ pathEffect = DashPathEffect(floatArrayOf(2f * dp, 3f * dp), 0f)}- for (fraction in listOf(0f, 0.5f, 1f)) {+ for (fraction in listOf(0f, 1f)) {val y = scale.top + (scale.bottom - scale.top) * fractioncanvas.drawLine(0f, y, width.toFloat(), y, paint)}}private fun drawLines(canvas: Canvas, spec: ChartSpec, colors: ChartColors, width: Int, height: Int, dp: Float) {- val stroke = if (spec.grid) 2f * dp else 1.75f * dp+ val stroke = if (spec.grid) 2.3f * dp else 1.75f * dpval dot = 2.75f * dpval padX = dot + 1f * dpval scale = scaleOf(spec.current.flatten() + spec.previous.orEmpty(), false, dot + 1f * dp, height - stroke / 2 - 1f * dp) ?: return@@ -155,9 +199,9 @@ internal object ChartCanvas {closeRun(first.lastIndex)val areaPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {style = Paint.Style.FILL- shader = LinearGradient(0f, scale.top, 0f, scale.bottom, withAlpha(accent, 0.22f), withAlpha(accent, 0.04f), Shader.TileMode.CLAMP)+ shader = LinearGradient(0f, scale.top, 0f, scale.bottom, withAlpha(accent, 0.16f), withAlpha(accent, 0.01f), Shader.TileMode.CLAMP)}- canvas.drawPath(area, areaPaint)+ if (spec.current.size == 1) canvas.drawPath(area, areaPaint)spec.previous?.let { previous ->val paint = linePaint(colors.previous, stroke * 0.7f).apply {@@ -184,6 +228,9 @@ internal object ChartCanvas {val lastIndex = first.indexOfLast { it.isFinite() }if (lastIndex >= 0) {val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = accent }+ paint.color = colors.surface+ canvas.drawCircle(x(lastIndex), scale.y(first[lastIndex]), dot + dp, paint)+ paint.color = accentcanvas.drawCircle(x(lastIndex), scale.y(first[lastIndex]), dot, paint)}}@@ -232,7 +279,7 @@ internal object ChartCanvas {val bottom = max(y, zero)if (bottom - top < 0.5f) return@forEachIndexed// One series reads like the app's pin: neutral bars and the newest in ink.- val base = if (groups == 1) (if (index == count - 1) colors.ink else colors.barNeutral) else colors.series[seriesIndex % colors.series.size]+ val base = if (groups == 1) (if (index == count - 1) colors.series.first() else withAlpha(colors.series.first(), 0.3f)) else colors.series[seriesIndex % colors.series.size]paint.color = if (spec.inProgress && index == count - 1) withAlpha(base, 0.55f) else baseval r = min(radius, bottom - top)val radii = if (value >= 0) floatArrayOf(r, r, r, r, 0f, 0f, 0f, 0f) else floatArrayOf(0f, 0f, 0f, 0f, r, r, r, r)diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.ktindex 8a715ddb3fa8..c1f373d3b8fc 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartFetcher.kt@@ -59,14 +59,14 @@ object ChartFetcher {if (queryStatus?.optString("error_code") == "rate_limited") return Outcome.Failure(ErrorKind.RATE_LIMITED)if (queryStatus != null && queryStatus.optBoolean("error", false)) return Outcome.Failure(ErrorKind.BAD_DATA)if (!insight.has("result") || insight.isNull("result")) return Outcome.Failure(ErrorKind.NO_RESULT)- return Outcome.Success(TrendsParser.parse(insight, pin.id, now))+ return Outcome.Success(InsightParser.parse(insight, pin, now))} catch (e: IOException) {return Outcome.Failure(ErrorKind.NETWORK)} catch (e: JSONException) {Log.w(TAG, "Pin ${pin.id} answered with JSON the widget cannot read")return Outcome.Failure(ErrorKind.BAD_DATA)} catch (e: BadDataException) {- Log.w(TAG, "Pin ${pin.id} is not a trends result: ${e.message}")+ Log.w(TAG, "Pin ${pin.id} has an unreadable result: ${e.message}")return Outcome.Failure(ErrorKind.BAD_DATA)} finally {connection.disconnect()diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.ktindex 2d4d8f359dce..b19d4c164c06 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartModels.kt@@ -57,6 +57,7 @@ data class CatalogPin(val number: Boolean,val chart: Boolean,val reason: String?,+ val displayMode: String? = null,) {val isDashboard: Boolean get() = kind == "dashboard"}@@ -89,6 +90,7 @@ data class Catalog(number = p.optBoolean("number", false),chart = p.optBoolean("chart", false),reason = p.stringOrNull("reason"),+ displayMode = p.stringOrNull("displayMode"),)}Catalog(@@ -163,6 +165,8 @@ data class SnapshotPoint(val at: String, val value: Double)data class SnapshotSeries(val label: String, val points: List<SnapshotPoint>, val previous: Boolean)+data class SnapshotRow(val label: String, val value: String)+data class ChartSnapshot(val pinId: String,val fetchedAt: Long,@@ -176,6 +180,11 @@ data class ChartSnapshot(val inProgress: Boolean,val series: List<SnapshotSeries>,val chartKind: String,+ val display: String? = null,+ val chartValueText: String? = null,+ val axisLowText: String? = null,+ val axisHighText: String? = null,+ val rows: List<SnapshotRow> = emptyList(),) {val deltaSign: Int get() = deltaPercent?.let { if (it > 0) 1 else if (it < 0) -1 else 0 } ?: 0@@ -202,6 +211,11 @@ data class ChartSnapshot(.put("inProgress", inProgress).put("series", seriesArray).put("chartKind", chartKind)+ .put("chartValueText", chartValueText ?: JSONObject.NULL)+ .put("axisLowText", axisLowText ?: JSONObject.NULL)+ .put("axisHighText", axisHighText ?: JSONObject.NULL)+ .put("display", display ?: JSONObject.NULL)+ .put("rows", JSONArray(rows.map { JSONObject().put("label", it.label).put("value", it.value) })).toString()}@@ -231,6 +245,13 @@ data class ChartSnapshot(inProgress = o.optBoolean("inProgress", false),series = series,chartKind = o.optString("chartKind", "line"),+ display = o.stringOrNull("display"),+ chartValueText = o.stringOrNull("chartValueText"),+ axisLowText = o.stringOrNull("axisLowText"),+ axisHighText = o.stringOrNull("axisHighText"),+ rows = o.optJSONArray("rows")?.let { rows -> (0 until rows.length()).mapNotNull { index ->+ rows.optJSONObject(index)?.let { SnapshotRow(it.optString("label"), it.optString("value")) }+ } } ?: emptyList(),)}.getOrNull()}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.ktindex 993f97d57479..c53a04fc6c12 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartRenderer.kt@@ -166,6 +166,9 @@ object ChartRenderer {// Opening the insight in the app computes it; the next refresh then finds the result.return Resolved.Message(name, message, detail, linkPin = pin.takeIf { error.kind == ErrorKind.NO_RESULT })}+ if (snapshot.valueText == null && snapshot.rows.isEmpty() && snapshot.series.none { series -> series.points.any { it.value.isFinite() } }) {+ return Resolved.Message(name, context.getString(R.string.chart_widget_empty), linkPin = pin)+ }val extras = config.extraPinIds.asSequence().filter { it != pin.id }.mapNotNull { catalog?.pin(it)?.takeIf { extra -> extra.eligible } }@@ -194,6 +197,8 @@ object ChartRenderer {}private fun dataViews(context: Context, id: Int, family: Family, widthDp: Int, heightDp: Int, data: Resolved.Data, now: Long): RemoteViews {+ val isNumber = data.snapshot.display == "number" || (data.snapshot.series.isEmpty() && data.snapshot.rows.isEmpty() && data.snapshot.valueText != null)+ if (isNumber && data.extras.isEmpty()) return numberViews(context, id, family, data, now)val layout = when (family) {Family.SMALL -> R.layout.chart_widget_smallFamily.MEDIUM -> R.layout.chart_widget_medium@@ -203,7 +208,8 @@ object ChartRenderer {val snapshot = data.snapshotval m = Metrics(context)views.setTextViewText(R.id.chart_title, data.pin.name)- bindValue(context, views, R.id.chart_value, R.id.chart_delta, snapshot)+ val headline = snapshot.valueText ?: snapshot.chartValueText+ bindValue(context, views, R.id.chart_value, R.id.chart_delta, snapshot.copy(valueText = headline))views.setTextViewText(R.id.chart_range, snapshot.rangeLabel ?: "")val displayed = listOf(snapshot) + if (family == Family.LARGE) {data.extras.mapNotNull { it.snapshot.visibleAfter(it.error) }@@ -212,6 +218,11 @@ object ChartRenderer {val updated = ageText(context, age)views.setTextViewText(R.id.chart_updated, updated)setTextColor(context, views, R.id.chart_updated, if (age > STALE_MS) R.color.chart_widget_orange else R.color.chart_widget_tertiary)+ val inlineAge = family != Family.SMALL && snapshot.rows.isEmpty() && snapshot.series.isNotEmpty()+ if (family != Family.SMALL) {+ views.setTextViewText(R.id.chart_age_inline, if (inlineAge) updated.removePrefix("Updated ") else "")+ views.setViewVisibility(R.id.chart_footer, if (inlineAge) View.GONE else View.VISIBLE)+ }val widthPx = widthDp * m.densityval heightPx = heightDp * m.density@@ -219,38 +230,57 @@ object ChartRenderer {var chartHeight: Floatif (family == Family.SMALL) {chartWidth = widthPx - m.dp(24f)- chartHeight = heightPx - m.dp(24f) - m.line(12f) - m.dp(2f) - m.line(26f) - m.dp(2f) - m.pill() - m.dp(6f) - m.dp(4f) - m.line(10.5f)- if (snapshot.valueText == null) chartHeight += m.line(26f) + m.dp(2f)+ chartHeight = heightPx - m.dp(24f) - m.line(12f) - m.dp(2f) - m.line(28f) - m.dp(2f) - m.pill() - m.dp(6f) - m.dp(4f) - m.line(10.5f)+ if (headline == null) chartHeight += m.line(28f) + m.dp(2f)} else {chartWidth = widthPx - m.dp(28f)- val headline = if (snapshot.valueText != null) max(m.line(26f), m.pill()) else m.line(10.5f)- chartHeight = heightPx - m.dp(28f) - max(m.dp(12f), m.line(12f)) - m.dp(2f) - headline - m.dp(8f) - m.dp(6f) - m.line(10.5f)+ val headlineHeight = if (headline != null) max(m.line(28f), m.pill()) else m.line(10.5f)+ chartHeight = heightPx - m.dp(28f) - max(m.dp(12f), m.line(12f)) - m.dp(2f) - headlineHeight - m.dp(8f) - m.dp(6f) - m.line(10.5f)bindHeadline(context, views, snapshot)}+ if (inlineAge) chartHeight += m.line(10.5f) + m.dp(6f)if (family == Family.LARGE) {- chartHeight -= m.dp(4f) + m.line(10.5f)if (data.extras.isNotEmpty()) {chartHeight -= m.dp(10f) + m.dp(20f) + m.line(12f) + m.dp(1f) + m.line(10.5f) + m.dp(4f) + max(m.line(20f), m.pill()) + m.dp(6f) + m.dp(28f)}}- val spec = specOf(snapshot, if (family == Family.LARGE) TrendsParser.MAX_POINTS else SHORT_POINTS, grid = family != Family.SMALL)- bindChart(context, views, R.id.chart_frame, R.id.chart_image_light, R.id.chart_image_dark, spec, chartWidth, chartHeight, m.density)- if (family == Family.LARGE) bindLarge(context, views, id, data, spec, chartWidth, m)+ val spec = specOf(snapshot, if (family == Family.SMALL) SHORT_POINTS else TrendsParser.MAX_POINTS, grid = family != Family.SMALL)+ if (snapshot.rows.isNotEmpty()) {+ bindRows(context, views, R.id.chart_frame, R.id.chart_image_light, R.id.chart_image_dark, snapshot.rows, chartWidth, chartHeight, m.density)+ } else {+ bindChart(context, views, R.id.chart_frame, R.id.chart_image_light, R.id.chart_image_dark, spec, chartWidth, chartHeight, m.density)+ }+ if (family == Family.LARGE) bindLarge(context, views, id, data, chartWidth, m)views.setOnClickPendingIntent(R.id.chart_root, linkIntent(context, pinLink(context, data.pin, family), id, 0))val pill = snapshot.deltaText?.let { arrow(snapshot.deltaSign) + it }views.setContentDescription(R.id.chart_root,- listOfNotNull(data.pin.name, snapshot.valueText, pill, snapshot.rangeLabel, updated).joinToString(", "),+ listOfNotNull(data.pin.name, headline, pill, snapshot.rangeLabel, snapshot.rows.joinToString(". ") { "${it.label}: ${it.value}" }.takeIf { it.isNotEmpty() }, updated).joinToString(", "),)return views}+ private fun numberViews(context: Context, id: Int, family: Family, data: Resolved.Data, now: Long): RemoteViews {+ val views = RemoteViews(context.packageName, R.layout.chart_widget_number)+ val snapshot = data.snapshot+ views.setTextViewText(R.id.chart_title, data.pin.name)+ bindValue(context, views, R.id.chart_value, R.id.chart_delta, snapshot)+ views.setTextViewText(R.id.chart_basis, snapshot.deltaBasis ?: snapshot.rangeLabel ?: "")+ val age = max(0L, now - (snapshot.lastRefreshAt?.let(DateText::parseInstant) ?: snapshot.fetchedAt))+ val updated = ageText(context, age)+ views.setTextViewText(R.id.chart_updated, updated)+ setTextColor(context, views, R.id.chart_updated, if (age > STALE_MS) R.color.chart_widget_orange else R.color.chart_widget_tertiary)+ views.setOnClickPendingIntent(R.id.chart_root, linkIntent(context, pinLink(context, data.pin, family), id, 0))+ views.setContentDescription(R.id.chart_root, listOfNotNull(data.pin.name, snapshot.valueText, snapshot.deltaText, snapshot.deltaBasis, updated).joinToString(", "))+ return views+ }+private fun bindHeadline(context: Context, views: RemoteViews, snapshot: ChartSnapshot) {val current = snapshot.series.filter { !it.previous }if (snapshot.valueText != null || current.size < 2) {views.setViewVisibility(R.id.chart_legend, View.GONE)- val basis = snapshot.deltaBasis?.takeIf { snapshot.valueText != null && snapshot.deltaText != null }+ val basis = if (snapshot.valueText == null && snapshot.chartValueText != null) context.getString(R.string.chart_widget_latest) else snapshot.deltaBasis?.takeIf { snapshot.valueText != null && snapshot.deltaText != null }views.setTextViewText(R.id.chart_basis, basis ?: "")views.setViewVisibility(R.id.chart_basis, if (basis != null) View.VISIBLE else View.GONE)return@@ -270,15 +300,8 @@ object ChartRenderer {views.setViewVisibility(R.id.chart_legend, View.VISIBLE)}- private fun bindLarge(context: Context, views: RemoteViews, id: Int, data: Resolved.Data, spec: ChartSpec?, chartWidth: Float, m: Metrics) {- val first = data.snapshot.series.firstOrNull { !it.previous }?.points?.takeLast(TrendsParser.MAX_POINTS)- if (spec != null && first != null && first.isNotEmpty()) {- views.setTextViewText(R.id.chart_axis_start, DateText.axisDate(first.first().at, data.snapshot.intervalLabel))- views.setTextViewText(R.id.chart_axis_end, DateText.axisDate(first.last().at, data.snapshot.intervalLabel))- views.setViewVisibility(R.id.chart_axis, View.VISIBLE)- } else {- views.setViewVisibility(R.id.chart_axis, View.GONE)- }+ private fun bindLarge(context: Context, views: RemoteViews, id: Int, data: Resolved.Data, chartWidth: Float, m: Metrics) {+ views.setViewVisibility(R.id.chart_axis, View.GONE)if (data.extras.isEmpty()) {views.setViewVisibility(R.id.chart_tiles, View.GONE)return@@ -307,7 +330,11 @@ object ChartRenderer {views.setTextViewText(ids.range, snapshot.rangeLabel ?: "")bindValue(context, views, ids.value, ids.delta, snapshot)val sparkline = specOf(snapshot, SHORT_POINTS, grid = false)- bindChart(context, views, ids.frame, ids.light, ids.dark, sparkline, tileWidth, m.dp(28f), m.density)+ if (snapshot.rows.isNotEmpty()) {+ bindRows(context, views, ids.frame, ids.light, ids.dark, snapshot.rows, tileWidth, m.dp(28f), m.density)+ } else {+ bindChart(context, views, ids.frame, ids.light, ids.dark, sparkline, tileWidth, m.dp(28f), m.density)+ }}}@@ -352,7 +379,11 @@ object ChartRenderer {val previous = snapshot.series.firstOrNull { it.previous }?.takeIf { current.size == 1 && !bars }?.points?.take(length)?.drop(start)?.map { it.value }- return ChartSpec(values, previous, bars, snapshot.inProgress, grid)+ val first = current.firstOrNull()?.points?.take(length)?.drop(start)+ return ChartSpec(values, previous, bars, snapshot.inProgress, grid,+ snapshot.axisLowText, snapshot.axisHighText,+ first?.firstOrNull()?.let { DateText.axisDate(it.at, snapshot.intervalLabel) },+ first?.lastOrNull()?.let { DateText.axisDate(it.at, snapshot.intervalLabel) })}/** Draws the chart for both themes; the layout shows the one that matches the launcher's night mode. */@@ -379,6 +410,16 @@ object ChartRenderer {views.setImageViewBitmap(darkId, dark)}+ private fun bindRows(context: Context, views: RemoteViews, frameId: Int, lightId: Int, darkId: Int,+ rows: List<SnapshotRow>, width: Float, height: Float, density: Float) {+ val light = ChartCanvas.rows(rows, ChartColors.of(context, false), width.toInt(), height.toInt(), density)+ val dark = ChartCanvas.rows(rows, ChartColors.of(context, true), width.toInt(), height.toInt(), density)+ if (light == null || dark == null) { views.setViewVisibility(frameId, View.GONE); return }+ views.setViewVisibility(frameId, View.VISIBLE)+ views.setImageViewBitmap(lightId, light)+ views.setImageViewBitmap(darkId, dark)+ }+/** From Android 12 the launcher picks the color for its own night mode; before that, the current mode decides. */private fun setTextColor(context: Context, views: RemoteViews, viewId: Int, colorRes: Int) {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.ktindex f2972071cf34..2c70727ed646 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartStore.kt@@ -3,6 +3,7 @@ package com.posthog.code.mobile.chartimport android.content.Contextimport android.content.SharedPreferencesimport android.util.Log+import org.json.JSONObjectimport androidx.security.crypto.EncryptedSharedPreferencesimport androidx.security.crypto.MasterKey@@ -26,8 +27,23 @@ object ChartStore {private var cachedCatalogJson: String? = nullprivate var cachedCatalog: Catalog? = null- private fun prefs(context: Context): SharedPreferences =- context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)+ @Synchronized+ private fun prefs(context: Context): SharedPreferences {+ val store = requireNotNull(securePrefs(context)) { "Widget storage unavailable" }+ val legacy = context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)+ if (legacy.all.isNotEmpty()) {+ val editor = store.edit()+ legacy.all.forEach { (key, value) ->+ if (key.startsWith(WIDGET_PREFIX) && key.removePrefix(WIDGET_PREFIX).toIntOrNull() != null &&+ !store.contains(key) && value is String) {+ WidgetConfig.parse(value)?.let { editor.putString(key, it.toJson()) }+ }+ }+ check(editor.commit()) { "Could not migrate widget selections" }+ check(legacy.edit().clear().commit()) { "Could not clear legacy widget storage" }+ }+ return store+ }/*** Null when the keystore cannot open the file. A restored backup or a corrupt key fails the same way, so the file@@ -123,20 +139,38 @@ object ChartStore {@Synchronizedfun setCatalogJson(context: Context, json: String?) {- val previous = catalog(context)- val next = json?.let(Catalog::parse)- val prefs = prefs(context)- val editor = prefs.edit()- previous?.pins?.forEach { pin ->- val replacement = next?.pin(pin.id)- if (previous.host != next?.host || previous.projectId != next?.projectId ||- replacement == null || pin.kind != replacement.kind || pin.insightId != replacement.insightId ||- pin.dashboardId != replacement.dashboardId- ) {- editor.remove("$SNAPSHOT_PREFIX${pin.id}").remove("$ERROR_PREFIX${pin.id}")+ val editor = prefs(context).edit()+ if (json == null) {+ editor.remove(KEY_CATALOG)+ clearSnapshots(context)+ } else {+ val old = catalog(context)+ val next = JSONObject(json)+ val pins = next.optJSONArray("pins")+ val selected = selectedPinIds(context).toSet()+ val allowed = (0 until (pins?.length() ?: 0)).mapNotNull { pins?.optJSONObject(it) }+ .filter { it.optBoolean("eligible") }.map { it.optString("id") }.toSet().intersect(selected)+ retainSnapshots(context, allowed)+ for (index in 0 until (pins?.length() ?: 0)) {+ val pin = pins?.optJSONObject(index) ?: continue+ val id = pin.optString("id")+ val previous = old?.pin(id)+ val changed = old?.host != next.optString("host").trimEnd('/') || old?.projectId != next.optLong("projectId") || previous == null || previous.kind != pin.optString("kind", "insight") || previous.insightId != pin.longOrNull("insightId") ||+ previous.shortId != pin.stringOrNull("shortId") || previous.dashboardId != pin.longOrNull("dashboardId") ||+ previous.displayMode != pin.stringOrNull("displayMode")+ if (changed) {+ editor.remove("$SNAPSHOT_PREFIX$id").remove("$ERROR_PREFIX$id")+ }+ pin.optJSONObject("snapshot")?.takeIf { id in allowed }?.let { snapshot ->+ val cached = if (changed) null else ChartStore.snapshot(context, id)+ if (snapshot.optLong("fetchedAt") >= (cached?.fetchedAt ?: 0L)) {+ editor.putString("$SNAPSHOT_PREFIX$id", snapshot.toString()).remove("$ERROR_PREFIX$id")+ }+ }+ pin.remove("snapshot")}+ editor.putString(KEY_CATALOG, next.toString())}- if (json == null) editor.remove(KEY_CATALOG) else editor.putString(KEY_CATALOG, json)editor.commit()}@@ -164,6 +198,7 @@ object ChartStore {) {val config = WidgetConfig(pinId, extraPinIds, projectId, projectName, pinName)prefs(context).edit().putString("$WIDGET_PREFIX$id", config.toJson()).commit()+ retainSnapshots(context, selectedPinIds(context).toSet())}fun removeWidget(context: Context, id: Int) {@@ -183,6 +218,21 @@ object ChartStore {if (pinId !in shown) editor.remove(key)}editor.commit()+ if (ChartRenderer.widgetIds(context).none { it != id }) clearCredentials(context)+ }++ fun selectedPinIds(context: Context): List<String> = ChartRenderer.widgetIds(context).flatMap { id ->+ widgetConfig(context, id)?.let { listOf(it.pinId) + it.extraPinIds } ?: emptyList()+ }.distinct()++ fun retainSnapshots(context: Context, selected: Set<String>) {+ val store = prefs(context)+ val editor = store.edit()+ store.all.keys.forEach { key ->+ val prefix = listOf(SNAPSHOT_PREFIX, ERROR_PREFIX).firstOrNull { key.startsWith(it) } ?: return@forEach+ if (key.removePrefix(prefix) !in selected) editor.remove(key)+ }+ editor.commit()}/** A restored home screen gives each widget a new id. */@@ -205,17 +255,26 @@ object ChartStore {pinIds: List<String>,outcome: ChartFetcher.Outcome,isStopped: () -> Boolean,+ startedAt: Long,): Boolean {- if (isStopped() || expectedSession != session(context) || expectedCatalog != catalog(context)) return false+ if (isStopped() || expectedSession != session(context) || expectedCatalog != catalog(context) ||+ !selectedPinIds(context).containsAll(pinIds)) return falseval editor = prefs(context).edit()when (outcome) {- is ChartFetcher.Outcome.Success -> editor- .putString("$SNAPSHOT_PREFIX${outcome.snapshot.pinId}", outcome.snapshot.toJson())- .remove("$ERROR_PREFIX${outcome.snapshot.pinId}")+ is ChartFetcher.Outcome.Success -> {+ setSnapshot(context, outcome.snapshot)+ return true+ }is ChartFetcher.Outcome.Failure -> {val now = System.currentTimeMillis()- val error = SnapshotError(now, outcome.kind)- pinIds.forEach { editor.putString("$ERROR_PREFIX$it", error.toJson()) }+ val error = SnapshotError(startedAt, outcome.kind)+ pinIds.forEach {+ if ((snapshot(context, it)?.fetchedAt ?: 0L) > startedAt) return@forEach+ editor.putString("$ERROR_PREFIX$it", error.toJson())+ if (outcome.kind == ErrorKind.AUTH || outcome.kind == ErrorKind.NOT_FOUND) {+ editor.remove("$SNAPSHOT_PREFIX$it")+ }+ }if (outcome.kind == ErrorKind.RATE_LIMITED) editor.putLong(KEY_RETRY_AT, now + outcome.retryAfterMs)}}@@ -225,7 +284,9 @@ object ChartStore {fun snapshot(context: Context, pinId: String): ChartSnapshot? =prefs(context).getString("$SNAPSHOT_PREFIX$pinId", null)?.let(ChartSnapshot::parse)+ @Synchronizedfun setSnapshot(context: Context, snapshot: ChartSnapshot) {+ if ((ChartStore.snapshot(context, snapshot.pinId)?.fetchedAt ?: 0L) > snapshot.fetchedAt) returnprefs(context).edit().putString("$SNAPSHOT_PREFIX${snapshot.pinId}", snapshot.toJson()).remove("$ERROR_PREFIX${snapshot.pinId}")diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.ktindex 6b921c520a8c..a8809e774ea8 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetConfigureActivity.kt@@ -63,7 +63,6 @@ class ChartWidgetConfigureActivity : Activity() {})val catalog = ChartStore.catalog(this)when {- ChartStore.credentials(this) == null -> showMessage(getString(R.string.chart_widget_configure_signed_out))catalog == null || catalog.pins.isEmpty() -> showMessage(getString(R.string.chart_widget_configure_empty))else -> showPicker(catalog)}@@ -90,7 +89,7 @@ class ChartWidgetConfigureActivity : Activity() {val current = ChartStore.widgetConfig(this, widgetId)val eligible = catalog.pins.filter { it.eligible }val ineligible = catalog.pins.filter { !it.eligible }- selected = current?.pinId?.takeIf { id -> eligible.any { it.id == id } }+ selected = current?.pinId?.takeIf { id -> eligible.any { it.id == id } } ?: eligible.firstOrNull()?.idcurrent?.extraPinIds?.filter { id -> eligible.any { it.id == id } }?.let(extras::addAll)lateinit var done: Button@@ -179,6 +178,9 @@ class ChartWidgetConfigureActivity : Activity() {ChartWidgetRefresh.refreshAll(this)setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId))finish()+ if (ChartStore.credentials(this) == null) {+ packageManager.getLaunchIntentForPackage(packageName)?.let(::startActivity)+ }}private fun twoLines(title: String, subtitle: String): CharSequence {diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.ktindex 557faaaea66f..7a1d1f1873b4 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetModule.kt@@ -8,6 +8,14 @@ class ChartWidgetModule : Module() {override fun definition() = ModuleDefinition {Name("ChartWidget")+ AsyncFunction("getWidgetState") {+ val ids = ChartRenderer.widgetIds(context())+ val selected = ChartStore.selectedPinIds(context())+ ChartStore.retainSnapshots(context(), selected.toSet())+ if (ids.isEmpty()) ChartStore.clearCredentials(context())+ mapOf("installed" to ids.isNotEmpty(), "pinIds" to selected, "usesDefault" to (ids.isNotEmpty() && selected.isEmpty()))+ }+Function("setCredentials") { json: String ->ChartStore.setCredentials(context(), json)ChartWidgetRefresh.refreshAll(context())diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.ktindex f8ad2a7edf53..240e1862d90e 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/ChartWidgetRefresh.kt@@ -75,11 +75,12 @@ object ChartWidgetRefresh {.mapNotNull { catalog.pin(it)?.takeIf { pin -> pin.eligible } }for ((index, pin) in pins.withIndex()) {if (isStopped() || session != ChartStore.session(context)) return+ val startedAt = System.currentTimeMillis()val outcome = fetch(context, credentials, pin)val stopsPass = outcome is ChartFetcher.Outcome.Failure &&(outcome.kind == ErrorKind.AUTH || outcome.kind == ErrorKind.RATE_LIMITED)val affected = if (stopsPass) pins.drop(index).map { it.id } else listOf(pin.id)- if (!ChartStore.commitFetch(context, session, catalog, affected, outcome, isStopped) || stopsPass) return+ if (!ChartStore.commitFetch(context, session, catalog, affected, outcome, isStopped, startedAt) || stopsPass) return}}}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/InsightParser.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/InsightParser.ktnew file mode 100644index 000000000000..d8d0cd9fb54e--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/InsightParser.kt@@ -0,0 +1,230 @@+package com.posthog.code.mobile.chart++import org.json.JSONArray+import org.json.JSONObject++/** Matches the result shapes consumed by the Views adapters, without running app JavaScript in a widget. */+object InsightParser {+ fun parse(response: JSONObject, pin: CatalogPin, now: Long): ChartSnapshot {+ val query = response.optJSONObject("query") ?: JSONObject()+ val source = query.optJSONObject("source") ?: query+ val kind = source.optString("kind")+ if (kind == "TrendsQuery") {+ val snapshot = chartLabels(TrendsParser.parse(response, pin.id, now)) { value ->+ val filter = source.optJSONObject("trendsFilter")+ TrendsParser.formatValue(value, TrendsParser.formatOf(filter), false)+ }+ if (pin.displayMode == "number" && pin.number) return snapshot.copy(display = "number")+ val filter = source.optJSONObject("trendsFilter")+ val display = filter?.stringOrNull("display") ?: query.stringOrNull("display")+ if (display in setOf("ActionsPie", "ActionsTable", "WorldMap", "ActionsBarValue", "ActionsDonut", "ActionsProportionBar")) {+ val format = TrendsParser.ValueFormat(filter?.stringOrNull("aggregationAxisFormat"),+ filter?.optString("aggregationAxisPrefix") ?: "", filter?.optString("aggregationAxisPostfix") ?: "", null, null)+ val rows = objects(response.optJSONArray("result")).filter { it.optString("compare_label") != "previous" && number(it.opt("aggregated_value")) != null }+ .sortedWith(compareBy<JSONObject> { it.optString("breakdown_value") == "\$\$_posthog_breakdown_other_\$\$" }.thenByDescending { number(it.opt("aggregated_value")) })+ .take(12).map { entry ->+ val value = number(entry.opt("aggregated_value"))+ SnapshotRow(entry.optString("label", "Value"), value?.let { TrendsParser.formatValue(it, format, false) } ?: "–")+ }+ return snapshot.copy(display = "rows", rows = rows)+ }+ return snapshot.copy(display = if (pin.displayMode == "number" || display == "BoldNumber") "number" else "chart")+ }+ val base = ChartSnapshot(pin.id, now, response.stringOrNull("last_refresh"), null, "day", null,+ null, null, null, false, emptyList(), "line", "rows")+ if (kind == "HogQLQuery") return sql(response, query, base)+ val result = response.optJSONArray("result")+ if (kind == "FunnelsQuery" && result != null) {+ val groups = if (result.opt(0) is JSONArray) values(result).mapNotNull { it as? JSONArray }.map(::objects) else listOf(objects(result))+ val first = groups.firstOrNull() ?: emptyList()+ val layout = source.optJSONObject("funnelsFilter")?.stringOrNull("funnelVizType")+ if ((layout != null && layout != "steps") || first.any { number(it.opt("count")) == null }) return base.copy(rows = genericRows(result))+ val counts = first.indices.map { i -> groups.sumOf { number(it.getOrNull(i)?.opt("count")) ?: 0.0 } }+ if (source.optJSONObject("breakdownFilter")?.optString("breakdown_type") == "cohort" && groups.size > 1) {+ return base.copy(rows = genericRows(result))+ }+ val rows = first.mapIndexed { i, step -> SnapshotRow(step.stringOrNull("custom_name") ?: step.optString("name", "Step ${i + 1}"), text(counts[i])) }.take(12)+ val entered = counts.firstOrNull() ?: 0.0+ return base.copy(rows = rows, valueText = if (counts.size > 1 && entered > 0) "${TrendsParser.number(counts.last() / entered * 100, 1)}%" else null,+ rangeLabel = "Overall conversion")+ }+ if (kind == "RetentionQuery" && result != null) {+ val filter = source.optJSONObject("retentionFilter")+ val records = objects(result)+ val aggregation = filter?.stringOrNull("aggregationType")+ val breakdown = source.optJSONObject("breakdownFilter")+ if ((aggregation != null && aggregation != "count") || breakdown?.stringOrNull("breakdown") != null ||+ (breakdown?.optJSONArray("breakdowns")?.length() ?: 0) > 0 || records.any { !it.isNull("breakdown_value") }) {+ return base.copy(rows = genericRows(result))+ }+ val period = filter?.optString("period", "Day") ?: "Day"+ val previous = filter?.optString("retentionReference") == "previous"+ val rows = records.take(12).mapNotNull { row ->+ val start = row.stringOrNull("date")?.let { DateText.parseInstant(it) } ?: return@mapNotNull null+ val counts = objects(row.optJSONArray("values")).map { number(it.opt("count")) ?: 0.0 }+ val calendar = java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"))+ calendar.timeInMillis = start+ val available = counts.indices.takeWhile { i ->+ calendar.timeInMillis = start+ when (period) {+ "Month" -> calendar.add(java.util.Calendar.MONTH, i)+ "Week" -> calendar.add(java.util.Calendar.DAY_OF_YEAR, 7 * i)+ "Hour" -> calendar.add(java.util.Calendar.HOUR_OF_DAY, i)+ else -> calendar.add(java.util.Calendar.DAY_OF_YEAR, i)+ }+ calendar.timeInMillis <= now+ }+ val percentages = available.map { i ->+ val count = counts[i]+ val denominator = if (previous && i > 0) counts[i - 1] else counts.firstOrNull() ?: 0.0+ "${TrendsParser.number(if (denominator > 0) count / denominator * 100 else 0.0, 0)}%"+ }+ SnapshotRow(row.optString("date", "Cohort").take(10), percentages.joinToString(" · "))+ }+ return base.copy(rows = rows, rangeLabel = "${filter?.optString("period", "Day") ?: "Day"} retention")+ }+ return base.copy(rows = genericRows(response.opt("result")))+ }++ private fun chartLabels(snapshot: ChartSnapshot, format: (Double) -> String): ChartSnapshot {+ val current = snapshot.series.filter { !it.previous }+ val values = snapshot.series.filter { snapshot.chartKind != "bar" || !it.previous }.flatMap { it.points.map { p -> p.value } }.filter { it.isFinite() }+ return snapshot.copy(+ chartValueText = current.singleOrNull()?.points?.lastOrNull { it.value.isFinite() }?.let { format(it.value) },+ axisLowText = values.minOrNull()?.let { format(if (snapshot.chartKind == "bar") minOf(0.0, it) else it) },+ axisHighText = values.maxOrNull()?.let { format(if (snapshot.chartKind == "bar") maxOf(0.0, it) else it) },+ )+ }++ internal fun number(value: Any?): Double? = when (value) {+ is Number -> value.toDouble().takeIf { it.isFinite() }+ is String -> value.takeIf { it.length <= 128 && it.matches(Regex("\\s*[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?\\s*")) }?.toDoubleOrNull()?.takeIf { it.isFinite() }+ else -> null+ }++ private fun values(array: JSONArray?): List<Any?> = if (array == null) emptyList() else (0 until array.length()).map { array.opt(it) }+ private fun objects(array: JSONArray?): List<JSONObject> = values(array).mapNotNull { it as? JSONObject }+ private fun text(value: Any?): String = when {+ value == null || value == JSONObject.NULL -> "–"+ value is String -> value+ value is JSONArray -> values(value).take(6).joinToString(" · ") { text(it) }+ number(value) != null -> TrendsParser.number(number(value)!!, 3)+ else -> value.toString()+ }++ private fun genericRows(value: Any?): List<SnapshotRow> {+ if (value is JSONArray) return values(value).take(12).flatMapIndexed { index, row ->+ if (row is JSONObject) {+ val label = row.stringOrNull("label") ?: row.stringOrNull("name") ?: row.stringOrNull("date") ?: "Row ${index + 1}"+ val key = listOf("count", "aggregated_value", "value", "data").firstOrNull { row.has(it) }+ if (key != null) listOf(SnapshotRow(label, text(row.opt(key))))+ else row.keys().asSequence().sorted().take(6).map { SnapshotRow(it, text(row.opt(it))) }.toList()+ } else listOf(SnapshotRow("Value ${index + 1}", text(row)))+ }+ if (value is JSONObject) return value.keys().asSequence().sorted().take(12).map { SnapshotRow(it, text(value.opt(it))) }.toList()+ return if (value == null || value == JSONObject.NULL) emptyList() else listOf(SnapshotRow("Value", text(value)))+ }++ private fun formatting(query: JSONObject, column: String, display: String = "chart"): JSONObject {+ val table = objects(query.optJSONObject("tableSettings")?.optJSONArray("columns"))+ val axes = objects(query.optJSONObject("chartSettings")?.optJSONArray("yAxis"))+ fun format(entries: List<JSONObject>): JSONObject? = entries.firstOrNull { it.optString("column") == column }?.optJSONObject("settings")?.optJSONObject("formatting")+ return (when (display) { "number" -> format(table); "table" -> format(table) ?: format(axes); else -> format(axes) ?: format(table) }) ?: JSONObject()+ }++ private fun sqlText(cell: Any?, format: JSONObject): String {+ val value = number(cell) ?: return text(cell)+ val style = format.stringOrNull("style")+ val digits = (format.opt("decimalPlaces") as? Number)?.toInt()?.coerceIn(0, 100)+ val scaled = if (style == "percent") value * 100 else value+ val formatted = when (style) {+ "short" -> TrendsParser.formatValue(value, TrendsParser.ValueFormat("short", "", "", null, null), false)+ "number", "percent" -> TrendsParser.number(scaled, digits ?: 3, digits ?: 0) + if (style == "percent") "%" else ""+ else -> if (digits != null) String.format(java.util.Locale.US, "%.${digits}f", scaled) else java.math.BigDecimal.valueOf(scaled).stripTrailingZeros().toPlainString()+ }+ return format.optString("prefix", "") + formatted + format.optString("suffix", "")+ }++ private fun sqlDate(value: Any?): String? {+ val match = (value as? String)?.trim()?.let { Regex("""^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2})(:\d{2})?(?:\.\d+)?)?(?:Z|[+-]\d{2}(?::?\d{2})?)?$""").matchEntire(it) } ?: return null+ val (date, time, seconds) = match.destructured+ val at = if (time.isEmpty()) date else "$date $time${seconds.ifEmpty { ":00" }}"+ return at.takeIf { DateText.parseInstant(it) != null }+ }++ private fun sqlInterval(dates: List<String>): String {+ val times = dates.mapNotNull { DateText.parseInstant(it) }.distinct().sorted()+ val gaps = times.zipWithNext { a, b -> b - a }.sorted()+ val median = gaps.getOrNull(gaps.size / 2) ?: return "day"+ return when {+ median < 21 * 3_600_000L -> "hour"+ median < 6 * 86_400_000L -> "day"+ median < 28 * 86_400_000L -> "week"+ else -> "month"+ }+ }++ private fun sql(response: JSONObject, query: JSONObject, base: ChartSnapshot): ChartSnapshot {+ val rows = values(response.optJSONArray("result")).mapNotNull { it as? JSONArray }+ val columns = values(response.optJSONArray("columns")).map { it.toString() }+ val types = values(response.optJSONArray("types")).map { (it as? JSONArray)?.optString(1) ?: "" }+ fun scalar(index: Int): String {+ var type = types.getOrNull(index)?.trim() ?: ""+ while ((type.startsWith("Nullable(") || type.startsWith("LowCardinality(")) && type.endsWith(")")) {+ type = type.substringAfter('(').dropLast(1).trim()+ }+ return type+ }+ fun date(index: Int): Boolean = scalar(index).startsWith("Date")+ fun numeric(index: Int): Boolean = listOf("Int", "UInt", "Float", "Decimal").any { scalar(index).startsWith(it) }+ val settings = query.optJSONObject("chartSettings") ?: JSONObject()+ val savedX = settings.optJSONObject("xAxis")?.stringOrNull("column")+ val x = columns.indexOf(savedX).takeIf { it >= 0 } ?: columns.indices.firstOrNull(::date) ?: columns.indices.firstOrNull { !numeric(it) }+ val namedY = objects(settings.optJSONArray("yAxis")).mapNotNull { columns.indexOf(it.optString("column")).takeIf { i -> i >= 0 } }+ val breakdown = columns.indexOf(settings.stringOrNull("seriesBreakdownColumn")).takeIf { it >= 0 }+ val y = (namedY.ifEmpty { columns.indices.filter(::numeric) }).filter { it != x && it != breakdown }+ var display = query.optString("display", "ActionsTable")+ if (display == "Auto") display = when {+ columns.size == 1 && numeric(0) -> "BoldNumber"+ x != null && date(x) && y.isNotEmpty() && rows.size > 1 -> "ActionsLineGraph"+ else -> "ActionsTable"+ }+ if (display == "BoldNumber") return base.copy(display = "number", valueText = rows.firstOrNull()?.takeIf { !it.isNull(0) }?.let { sqlText(it.opt(0), formatting(query, columns.firstOrNull() ?: "", "number")) })+ val overTime = display in setOf("ActionsLineGraph", "ActionsLineGraphCumulative", "ActionsAreaGraph", "ActionsBar", "ActionsStackedBar", "ActionsUnstackedBar")+ if (overTime && x != null && date(x) && y.isNotEmpty()) {+ val dates = sortedSetOf<String>()+ val sums = linkedMapOf<String, MutableMap<Int, MutableMap<String, Double>>>()+ for (row in rows) {+ val at = sqlDate(row.opt(x)) ?: continue+ dates.add(at)+ val group = breakdown?.let { text(row.opt(it)) } ?: ""+ if (!sums.containsKey(group) && sums.size >= 5) continue+ val byColumn = sums.getOrPut(group) { mutableMapOf() }+ for (column in y.take(5)) {+ val value = number(row.opt(column)) ?: continue+ val byDate = byColumn.getOrPut(column) { mutableMapOf() }+ byDate[at] = (byDate[at] ?: 0.0) + value+ }+ }+ val axis = dates.toList()+ val visibleDates = axis.takeLast(60)+ val series = y.asSequence().flatMap { column -> sums.keys.asSequence().map { group ->+ val byDate = sums[group]?.get(column).orEmpty()+ var total = if (display == "ActionsLineGraphCumulative") axis.dropLast(visibleDates.size).sumOf { byDate[it] ?: 0.0 } else 0.0+ val points = visibleDates.map { at ->+ var value = byDate[at]+ if (display == "ActionsLineGraphCumulative" && value != null) { total += value; value = total }+ SnapshotPoint(at, value ?: Double.NaN)+ }+ SnapshotSeries(if (group.isEmpty()) columns[column] else "${columns[column]} · $group", points, false)+ } }.take(5).toList()+ val snapshot = base.copy(display = "chart", intervalLabel = sqlInterval(dates.toList()), series = series, chartKind = if (display.contains("Bar") || objects(settings.optJSONArray("yAxis")).firstOrNull()?.optJSONObject("settings")?.optJSONObject("display")?.optString("displayType") == "bar") "bar" else "line")+ return chartLabels(snapshot) { sqlText(it, formatting(query, columns[y[0]])) }+ }+ return base.copy(rows = rows.take(12).map { row ->+ val label = x?.let { text(row.opt(it)) } ?: "Value"+ val indices = columns.indices.filter { it != x }+ SnapshotRow(label, indices.joinToString(" · ") { if (numeric(it)) sqlText(row.opt(it), formatting(query, columns[it], "table")) else text(row.opt(it)) })+ })+ }+}diff --git a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.kt b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.ktindex 7e2ef465d9ad..620f7669e0d4 100644--- a/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.kt+++ b/products/mobile/modules/chart-widget/android/src/main/java/com/posthog/code/mobile/chart/TrendsParser.kt@@ -236,7 +236,7 @@ object TrendsParser {return "vs ${DateText.axisDate(at, interval)}"}- private fun formatOf(filter: JSONObject?): ValueFormat {+ internal fun formatOf(filter: JSONObject?): ValueFormat {fun precision(key: String): Int? =(filter?.opt(key) as? Number)?.takeIf { it.toDouble() == floor(it.toDouble()) }?.toInt()?.takeIf { it in 0..100 }return ValueFormat(diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xmlindex 78af2560e65d..0bd8f2f1bb2a 100644--- a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xml+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_background.xml@@ -1,5 +1,5 @@<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"><solid android:color="@color/chart_widget_surface" />- <stroke android:width="1dp" android:color="@color/chart_widget_hairline" />+ <stroke android:width="0.5dp" android:color="@color/chart_widget_hairline" /><corners android:radius="24dp" /></shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_dot.xml b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_dot.xmlnew file mode 100644index 000000000000..72669639f7aa--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/drawable/chart_widget_dot.xml@@ -0,0 +1,3 @@+<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">+ <solid android:color="@color/chart_widget_series_1" />+</shape>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xmlindex 8e3ba66408ac..0c8db5b5f264 100644--- a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xml+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_large.xml@@ -14,10 +14,10 @@android:orientation="horizontal"><ImageView- android:layout_width="12dp"- android:layout_height="12dp"+ android:layout_width="5dp"+ android:layout_height="5dp"android:importantForAccessibility="no"- android:src="@drawable/chart_widget_glyph" />+ android:src="@drawable/chart_widget_dot" /><TextViewandroid:id="@+id/chart_title"@@ -26,6 +26,8 @@android:layout_height="wrap_content"android:layout_marginStart="6dp"android:layout_weight="1" />+ <TextView android:id="@+id/chart_age_inline" style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="6dp" /></LinearLayout><LinearLayout@@ -70,7 +72,7 @@android:id="@+id/chart_frame"android:layout_width="match_parent"android:layout_height="0dp"- android:layout_marginTop="8dp"+ android:layout_marginTop="6dp"android:layout_weight="1"><ImageViewandroid:id="@+id/chart_image_light"@@ -231,7 +233,7 @@</LinearLayout></LinearLayout>- <LinearLayout+ <LinearLayout android:id="@+id/chart_footer"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="6dp"diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xmlindex e176f8852327..66354df1d896 100644--- a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xml+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_medium.xml@@ -14,10 +14,10 @@android:orientation="horizontal"><ImageView- android:layout_width="12dp"- android:layout_height="12dp"+ android:layout_width="5dp"+ android:layout_height="5dp"android:importantForAccessibility="no"- android:src="@drawable/chart_widget_glyph" />+ android:src="@drawable/chart_widget_dot" /><TextViewandroid:id="@+id/chart_title"@@ -26,6 +26,8 @@android:layout_height="wrap_content"android:layout_marginStart="6dp"android:layout_weight="1" />+ <TextView android:id="@+id/chart_age_inline" style="@style/ChartWidgetText.Footer"+ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="6dp" /></LinearLayout><LinearLayout@@ -70,7 +72,7 @@android:id="@+id/chart_frame"android:layout_width="match_parent"android:layout_height="0dp"- android:layout_marginTop="8dp"+ android:layout_marginTop="6dp"android:layout_weight="1"><ImageViewandroid:id="@+id/chart_image_light"@@ -82,7 +84,7 @@android:visibility="@integer/chart_widget_dark_visibility" /></FrameLayout>- <LinearLayout+ <LinearLayout android:id="@+id/chart_footer"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="6dp"diff --git a/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_number.xml b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_number.xmlnew file mode 100644index 000000000000..b0a97ba8236a--- /dev/null+++ b/products/mobile/modules/chart-widget/android/src/main/res/layout/chart_widget_number.xml@@ -0,0 +1,25 @@+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"+ android:id="@+id/chart_root"+ android:layout_width="match_parent"+ android:layout_height="match_parent"+ android:background="@drawable/chart_widget_background"+ android:clipToOutline="true"+ android:orientation="vertical"+ android:padding="16dp">+ <TextView android:id="@+id/chart_title" style="@style/ChartWidgetText.Title"+ android:layout_width="match_parent" android:layout_height="wrap_content" />+ <LinearLayout android:layout_width="match_parent" android:layout_height="0dp"+ android:layout_weight="1" android:gravity="center" android:orientation="vertical">+ <TextView android:id="@+id/chart_value" style="@style/ChartWidgetText.Value.Hero"+ android:layout_width="match_parent" android:layout_height="60dp" />+ <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"+ android:gravity="center" android:orientation="horizontal" android:layout_marginTop="4dp">+ <TextView android:id="@+id/chart_delta" style="@style/ChartWidgetText.Pill"+ android:layout_width="wrap_content" android:layout_height="wrap_content" />+ <TextView android:id="@+id/chart_basis" style="@style/ChartWidgetText.Meta"+ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="6dp" />+ </LinearLayout>+ </LinearLayout>+ <TextView android:id="@+id/chart_updated" style="@style/ChartWidgetText.Footer"+ android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="end" />+</LinearLayout>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xmlindex 193ce68b2277..cd0a3a220b18 100644--- a/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xml+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/strings.xml@@ -1,6 +1,7 @@<resources>+ <string name="chart_widget_latest">Latest</string><string name="chart_widget_label">Chart</string>- <string name="chart_widget_description">A pinned insight from your Views tab, with its latest value.</string>+ <string name="chart_widget_description">A pinned view, with its latest value or chart.</string><!-- Widget states. --><string name="chart_widget_choose_pin">Choose a pin</string>@@ -19,7 +20,9 @@<string name="chart_widget_no_result">Open it in PostHog to load this insight</string><string name="chart_widget_not_found_short">Not found</string><string name="chart_widget_this_pin">This pin</string>- <string name="chart_widget_ineligible">Not a chart over time</string>+ <string name="chart_widget_ineligible">Open this view in PostHog</string>++ <string name="chart_widget_empty">No data for this range</string><!-- Freshness, from when the server computed the numbers. --><string name="chart_widget_updated_just_now">Updated just now</string>diff --git a/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xml b/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xmlindex 605d5d6dbf49..e82358e5b763 100644--- a/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xml+++ b/products/mobile/modules/chart-widget/android/src/main/res/values/styles.xml@@ -7,14 +7,25 @@<style name="ChartWidgetText.Title"><item name="android:textSize">12sp</item><item name="android:fontFamily">sans-serif-medium</item>- <item name="android:textColor">@color/chart_widget_ink</item>+ <item name="android:textColor">@color/chart_widget_secondary</item></style><style name="ChartWidgetText.Value">- <item name="android:textSize">26sp</item>+ <item name="android:textSize">28sp</item>+ <item name="android:autoSizeTextType">uniform</item>+ <item name="android:autoSizeMinTextSize">12sp</item>+ <item name="android:autoSizeMaxTextSize">28sp</item>+ <item name="android:autoSizeStepGranularity">1sp</item><item name="android:textStyle">bold</item><item name="android:fontFeatureSettings">tnum</item><item name="android:textColor">@color/chart_widget_ink</item></style>+ <style name="ChartWidgetText.Value.Hero">+ <item name="android:textSize">50sp</item>+ <item name="android:autoSizeMaxTextSize">50sp</item>+ <item name="android:autoSizeMinTextSize">22sp</item>+ <item name="android:letterSpacing">-0.03</item>+ <item name="android:gravity">center</item>+ </style><style name="ChartWidgetText.Value.Tile"><item name="android:textSize">20sp</item></style>@@ -23,7 +34,7 @@<item name="android:textColor">@color/chart_widget_secondary</item></style><style name="ChartWidgetText.Footer">- <item name="android:textSize">10.5sp</item>+ <item name="android:textSize">9sp</item><item name="android:textColor">@color/chart_widget_tertiary</item></style><style name="ChartWidgetText.Pill">diff --git a/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.kt b/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.ktindex 72830fc81d69..472e5fe9d875 100644--- a/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.kt+++ b/products/mobile/modules/chart-widget/android/src/test/java/com/posthog/code/mobile/chart/ChartWidgetRefreshTest.kt@@ -92,19 +92,23 @@ class ChartWidgetRefreshTest {@Testfun configurationReturnsOnlyTheConfirmedWidgetId() {- val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE)- .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 1)- val controller = Robolectric.buildActivity(ChartWidgetConfigureActivity::class.java, intent).create()- val activity = controller.get()- assertFalse(activity.isFinishing)- assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)- doneButton(activity).performClick()- assertTrue(activity.isFinishing)- assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode)- val result = shadowOf(activity).resultIntent- assertEquals(setOf(AppWidgetManager.EXTRA_APPWIDGET_ID), result.extras!!.keySet())- assertEquals(1, result.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1))- controller.destroy()+ for (signedIn in listOf(true, false)) {+ if (!signedIn) ChartStore.clearCredentials(context)+ val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE)+ .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, 1)+ val controller = Robolectric.buildActivity(ChartWidgetConfigureActivity::class.java, intent).create()+ val activity = controller.get()+ assertFalse(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ doneButton(activity).performClick()+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_OK, shadowOf(activity).resultCode)+ val result = shadowOf(activity).resultIntent+ assertEquals(setOf(AppWidgetManager.EXTRA_APPWIDGET_ID), result.extras!!.keySet())+ assertEquals(1, result.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1))+ assertEquals("first", ChartStore.widgetConfig(context, 1)?.pinId)+ controller.destroy()+ }}@Test@@ -167,18 +171,59 @@ class ChartWidgetRefreshTest {assertEquals(0, calls)ChartStore.setCatalogJson(context, """{"host":"https://example.com","projectId":1,"pins":[]}""")assertFalse(ChartStore.commitFetch(context, ChartStore.session(context)!!, catalog, listOf("first"),- ChartFetcher.Outcome.Success(snapshot()), { false }))+ ChartFetcher.Outcome.Success(snapshot()), { false }, 1000L))+ assertNull(ChartStore.snapshot(context, "first"))+ }++ @Test+ fun backgroundReadsPreserveNewerAppSnapshots() {+ val newer = snapshot().copy(fetchedAt = 2000L, valueText = "84")+ ChartStore.setSnapshot(context, newer)+ ChartWidgetRefresh.fetchShownPins(context, { false }) { _, _, pin ->+ ChartFetcher.Outcome.Success(snapshot(pin.id))+ }+ assertEquals(newer, ChartStore.snapshot(context, "first"))+ assertEquals(snapshot("second"), ChartStore.snapshot(context, "second"))+ }++ @Test+ fun delayedFailuresPreserveSnapshotsWrittenAfterTheRequestStarted() {+ val session = ChartStore.session(context)!!+ val catalog = ChartStore.catalog(context)!!+ val newer = snapshot().copy(fetchedAt = 2000L, valueText = "84")+ for (kind in listOf(ErrorKind.AUTH, ErrorKind.NOT_FOUND, ErrorKind.NETWORK)) {+ ChartStore.setSnapshot(context, newer)+ ChartStore.commitFetch(context, session, catalog, listOf("first"),+ ChartFetcher.Outcome.Failure(kind), { false }, 1000L)+ assertEquals(newer, ChartStore.snapshot(context, "first"))+ assertNull(ChartStore.snapshotError(context, "first"))+ }+ ChartStore.commitFetch(context, session, catalog, listOf("first"),+ ChartFetcher.Outcome.Failure(ErrorKind.NOT_FOUND), { false }, 3000L)assertNull(ChartStore.snapshot(context, "first"))}+ @Test+ fun migratesLegacySelectionsWithoutOverwritingNewSelectionsOrCopyingResults() {+ val legacy = context.getSharedPreferences("chart_widget", Context.MODE_PRIVATE)+ val original = WidgetConfig("legacy", listOf("extra"), 1, "Old project", "Old pin").toJson()+ legacy.edit().putString("chart.widget.1", original).putString("chart.widget.2", original)+ .putString("chart.snapshot.legacy", "old values").putString("chart.widget.invalid", original).commit()+ assertEquals("first", ChartStore.widgetConfig(context, 1)?.pinId)+ assertEquals(WidgetConfig.parse(original), ChartStore.widgetConfig(context, 2))+ assertNull(ChartStore.snapshot(context, "legacy"))+ assertTrue(legacy.all.isEmpty())+ }+@Testfun catalogChangesDiscardOnlySnapshotsForChangedTargets() {val original = JSONObject().put("host", "https://example.com").put("projectId", 1).put("pins", org.json.JSONArray().put(JSONObject()- .put("id", "first").put("kind", "dashboard").put("dashboardId", 10).put("insightId", 1)))+ .put("id", "first").put("kind", "dashboard").put("dashboardId", 10).put("insightId", 1).put("eligible", true)))val replacements = listOf(original.toString(),JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("name", "Renamed") }.toString(),+ JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("kind", "insight") }.toString(),JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("insightId", 2) }.toString(),JSONObject(original.toString()).apply { getJSONArray("pins").getJSONObject(0).put("dashboardId", 11) }.toString(),JSONObject(original.toString()).put("projectId", 2).toString(),@@ -269,7 +314,7 @@ class ChartWidgetRefreshTest {assertEquals(1, calls)assertTrue(ChartStore.retryAt(context) >= before + 120_000L)assertEquals(ErrorKind.RATE_LIMITED, ChartStore.snapshotError(context, "second")?.kind)- context.getSharedPreferences("chart_widget", Context.MODE_PRIVATE).edit().putLong("chart.retryAt", 0L).commit()+ context.getSharedPreferences("test-credentials", Context.MODE_PRIVATE).edit().putLong("chart.retryAt", 0L).commit()ChartWidgetRefresh.fetchShownPins(context, { false }, fetch)assertEquals(2, calls)}@@ -342,4 +387,27 @@ class ChartWidgetRefreshTest {assertEquals(1000L, cached.updatedAt())assertEquals(0L, cached.copy(lastRefreshAt = "1970-01-01T00:00:00Z").updatedAt())}+ @Test+ fun storesOnlySelectedSnapshotsInTheProtectedStoreAndClearsRemovedSelections() {+ val raw = context.getSharedPreferences("chart_widget", Context.MODE_PRIVATE)+ raw.edit().putString("chart.snapshot.legacy", "private result").commit()+ ChartStore.setCatalogJson(context, """{"host":"https://example.com","projectId":1,"pins":[+ {"id":"first","insightId":1,"eligible":true,"snapshot":${snapshot().toJson()}},+ {"id":"unselected","insightId":3,"eligible":true,"snapshot":${snapshot("unselected").toJson()}}+ ]}""")+ assertEquals(snapshot(), ChartStore.snapshot(context, "first"))+ assertNull(ChartStore.snapshot(context, "unselected"))+ assertTrue(raw.all.isEmpty())+ assertFalse(context.getSharedPreferences("test-credentials", Context.MODE_PRIVATE).getString("chart.catalog", "")!!.contains("snapshot"))+ for (kind in listOf(ErrorKind.AUTH, ErrorKind.NOT_FOUND)) {+ ChartStore.setSnapshot(context, snapshot())+ ChartWidgetRefresh.fetchShownPins(context, { false }) { _, _, _ -> ChartFetcher.Outcome.Failure(kind) }+ assertNull(ChartStore.snapshot(context, "first"))+ }+ ChartStore.retainSnapshots(context, emptySet())+ assertNull(ChartStore.snapshot(context, "first"))+ ChartStore.removeWidget(context, 1)+ assertNull(ChartStore.credentials(context))+ }+}diff --git a/products/mobile/modules/chart-widget/fixtures/insights.json b/products/mobile/modules/chart-widget/fixtures/insights.jsonnew file mode 100644index 000000000000..1949f29507a3--- /dev/null+++ b/products/mobile/modules/chart-widget/fixtures/insights.json@@ -0,0 +1,833 @@+[+ {+ "name": "SQL currency number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL currency number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "BoldNumber",+ "tableSettings": {+ "columns": [+ {+ "column": "value",+ "settings": {+ "formatting": {+ "style": "number",+ "prefix": "$",+ "decimalPlaces": 2+ }+ }+ }+ ]+ }+ },+ "result": [["1234.5"]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "Decimal(18, 2)"]]+ },+ "expected": {+ "valueText": "$1,234.50",+ "display": "number"+ }+ },+ {+ "name": "SQL percentage number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL percentage number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "BoldNumber",+ "tableSettings": {+ "columns": [+ {+ "column": "value",+ "settings": {+ "formatting": {+ "style": "percent",+ "decimalPlaces": 1+ }+ }+ }+ ]+ }+ },+ "result": [[0.125]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "Float64"]]+ },+ "expected": {+ "valueText": "12.5%",+ "display": "number"+ }+ },+ {+ "name": "SQL automatic number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL automatic number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "Auto"+ },+ "result": [[42]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "UInt64"]]+ },+ "expected": {+ "valueText": "42",+ "display": "number"+ }+ },+ {+ "name": "SQL date chart",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL date chart",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsLineGraph",+ "chartSettings": {+ "xAxis": {+ "column": "date"+ },+ "yAxis": [+ {+ "column": "count"+ }+ ]+ }+ },+ "result": [["2026-10-30", 3], ["2026-10-31", "5"]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["date", "count"],+ "types": [["date", "Date"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "chart",+ "seriesCount": 1,+ "lastValue": 5,+ "chartValueText": "5",+ "axisLowText": "3",+ "axisHighText": "5"+ }+ },+ {+ "name": "SQL automatic date chart",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL automatic date chart",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "Auto"+ },+ "result": [["2026-10-30", 3], ["2026-10-31", 5]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["date", "count"],+ "types": [["date", "Date"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "chart",+ "seriesCount": 1,+ "lastValue": 5+ }+ },+ {+ "name": "SQL table",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL table",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsTable"+ },+ "result": [["Basic", 12], ["Plus", 30]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["plan", "count"],+ "types": [["plan", "String"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "rows",+ "rowCount": 2+ }+ },+ {+ "name": "SQL category chart",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL category chart",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsBar",+ "chartSettings": {+ "xAxis": {+ "column": "plan"+ },+ "yAxis": [+ {+ "column": "count"+ }+ ]+ }+ },+ "result": [["Basic", 12], ["Plus", 30]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["plan", "count"],+ "types": [["plan", "String"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "rows",+ "rowCount": 2+ }+ },+ {+ "name": "Funnel steps",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Funnel steps",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "FunnelsQuery"+ }+ },+ "result": [+ {+ "name": "Visit",+ "count": 100+ },+ {+ "name": "Signup",+ "count": 25+ }+ ],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 2,+ "valueText": "25%"+ }+ },+ {+ "name": "Retention cohorts",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Retention cohorts",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "RetentionQuery",+ "retentionFilter": {+ "period": "Day"+ }+ }+ },+ "result": [+ {+ "date": "2026-10-30",+ "values": [+ {+ "count": 100+ },+ {+ "count": 25+ }+ ]+ }+ ],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1+ }+ },+ {+ "name": "Trends breakdown",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Trends breakdown",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "TrendsQuery",+ "series": [+ {+ "kind": "EventsNode",+ "event": "example"+ }+ ],+ "trendsFilter": {+ "display": "ActionsPie"+ },+ "breakdownFilter": {+ "breakdown": "plan",+ "breakdown_type": "event"+ }+ }+ },+ "result": [+ {+ "label": "Basic",+ "aggregated_value": 12,+ "data": [12],+ "days": ["2026-10-30"],+ "breakdown_value": "Basic"+ },+ {+ "label": "Plus",+ "aggregated_value": 30,+ "data": [30],+ "days": ["2026-10-30"],+ "breakdown_value": "Plus"+ }+ ],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 2+ }+ },+ {+ "name": "SQL duplicate coordinates and gaps",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL duplicate coordinates and gaps",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT date, plan, count FROM example"+ },+ "display": "ActionsLineGraph",+ "chartSettings": {+ "xAxis": {+ "column": "date"+ },+ "yAxis": [+ {+ "column": "count"+ }+ ],+ "seriesBreakdownColumn": "plan"+ }+ },+ "result": [["2026-10-30", "Basic", 2], ["2026-10-30", "Basic", 3], ["2026-10-31", "Plus", 7]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["date", "plan", "count"],+ "types": [["date", "Date"], ["plan", "String"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "chart",+ "seriesCount": 2,+ "firstValue": 5,+ "lastIsGap": true,+ "chartValueText": null+ }+ },+ {+ "name": "SQL empty number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL empty number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "BoldNumber",+ "tableSettings": {+ "columns": [+ {+ "column": "value",+ "settings": {+ "formatting": {+ "style": "number",+ "prefix": "$",+ "decimalPlaces": 2+ }+ }+ }+ ]+ }+ },+ "result": [[null]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "Decimal(18, 2)"]]+ },+ "expected": {+ "display": "number",+ "valueText": null+ }+ },+ {+ "name": "SQL text number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL text number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "BoldNumber"+ },+ "result": [["Ready"]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "String"]]+ },+ "expected": {+ "display": "number",+ "valueText": "Ready"+ }+ },+ {+ "name": "SQL boolean number",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL boolean number",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "BoldNumber"+ },+ "result": [[true]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["value"],+ "types": [["value", "Bool"]]+ },+ "expected": {+ "display": "number",+ "valueText": "true"+ }+ },+ {+ "name": "Retention future periods",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Retention future periods",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "RetentionQuery",+ "retentionFilter": {+ "period": "Month"+ }+ }+ },+ "result": [+ {+ "date": "2026-11-01",+ "values": [+ {+ "count": 100+ },+ {+ "count": 25+ }+ ]+ }+ ],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1,+ "firstRowValue": "100%"+ }+ },+ {+ "name": "PathsQuery compact rows",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "PathsQuery",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "PathsQuery"+ }+ },+ "result": {+ "paths": [["Started", "Finished", 12]]+ },+ "last_refresh": null,+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1,+ "appSnapshot": false+ }+ },+ {+ "name": "LifecycleQuery compact rows",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "LifecycleQuery",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "LifecycleQuery"+ }+ },+ "result": [+ {+ "label": "New",+ "data": [8, 12]+ }+ ],+ "last_refresh": null,+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1,+ "appSnapshot": false+ }+ },+ {+ "name": "StickinessQuery compact rows",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "StickinessQuery",+ "derived_name": null,+ "query": {+ "kind": "InsightVizNode",+ "source": {+ "kind": "StickinessQuery"+ }+ },+ "result": [+ {+ "label": "Active for 3 days",+ "count": 15+ }+ ],+ "last_refresh": null,+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1,+ "appSnapshot": false+ }+ },+ {+ "name": "SQL datetime wall clock",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL datetime wall clock",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsLineGraph",+ "chartSettings": {+ "xAxis": {+ "column": "date"+ },+ "yAxis": [+ {+ "column": "count"+ }+ ]+ }+ },+ "result": [["2026-10-30T08:00:00.000+02:00", 3], ["2026-10-31T08:00:00Z", 5]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["date", "count"],+ "types": [["date", "DateTime"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "chart",+ "seriesCount": 1,+ "lastValue": 5,+ "firstAt": "2026-10-30 08:00:00"+ }+ },+ {+ "name": "SQL text identifiers",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL text identifiers",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsTable"+ },+ "result": [["Basic", "001"], ["Plus", "002"]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["plan", "count"],+ "types": [["plan", "String"], ["count", "String"]]+ },+ "expected": {+ "display": "rows",+ "rowCount": 2,+ "firstRowValue": "001"+ }+ },+ {+ "name": "SQL chart labels preserve units",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "SQL chart labels preserve units",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "SELECT value FROM example"+ },+ "display": "ActionsLineGraph",+ "chartSettings": {+ "xAxis": {+ "column": "date"+ },+ "yAxis": [+ {+ "column": "count",+ "settings": {+ "formatting": {+ "style": "number",+ "prefix": "$",+ "decimalPlaces": 2+ }+ }+ }+ ]+ }+ },+ "result": [["2026-10-30", 3], ["2026-10-31", "5"]],+ "last_refresh": "2026-11-01T12:00:00Z",+ "cache_target_age": null,+ "next_allowed_client_refresh": null,+ "columns": ["date", "count"],+ "types": [["date", "Date"], ["count", "UInt64"]]+ },+ "expected": {+ "display": "chart",+ "seriesCount": 1,+ "lastValue": 5,+ "chartValueText": "$5.00",+ "axisLowText": "$3.00",+ "axisHighText": "$5.00"+ }+ },+ {+ "name": "SQL table keeps text columns and table formatting",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Example",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "select example"+ },+ "display": "ActionsTable",+ "tableSettings": {+ "columns": [+ {+ "column": "count",+ "settings": {+ "formatting": {+ "style": "number",+ "prefix": "$"+ }+ }+ }+ ]+ },+ "chartSettings": {+ "yAxis": [+ {+ "column": "count",+ "settings": {+ "formatting": {+ "style": "percent"+ }+ }+ }+ ]+ }+ },+ "columns": ["plan", "count", "status"],+ "types": [["plan", "String"], ["count", "UInt64"], ["status", "String"]],+ "result": [["Starter", 12, "active"]],+ "last_refresh": null,+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "rows",+ "rowCount": 1,+ "firstRowValue": "$12 \u00b7 active"+ }+ },+ {+ "name": "SQL hourly bars ignore collection axes",+ "response": {+ "id": 101,+ "short_id": "example1",+ "name": "Example",+ "derived_name": null,+ "query": {+ "kind": "DataVisualizationNode",+ "source": {+ "kind": "HogQLQuery",+ "query": "select example"+ },+ "display": "ActionsBar"+ },+ "columns": ["dates", "at", "counts", "count"],+ "types": [+ ["dates", "Array(Date)"],+ ["at", "Nullable(DateTime)"],+ ["counts", "Array(UInt64)"],+ ["count", "LowCardinality(Nullable(UInt64))"]+ ],+ "result": [+ [["2026-11-02"], "2026-11-02 10:00:00", [9], 3],+ [["2026-11-02"], "2026-11-02 11:00:00", [8], 5]+ ],+ "last_refresh": null,+ "cache_target_age": null,+ "next_allowed_client_refresh": null+ },+ "expected": {+ "display": "chart",+ "seriesCount": 1,+ "firstAt": "2026-11-02 10:00:00",+ "firstValue": 3,+ "lastValue": 5,+ "intervalLabel": "hour",+ "axisLowText": "0",+ "axisHighText": "5"+ }+ }+]diff --git a/products/mobile/modules/chart-widget/index.ts b/products/mobile/modules/chart-widget/index.tsindex f79d6e13a98d..d7030c5262b3 100644--- a/products/mobile/modules/chart-widget/index.ts+++ b/products/mobile/modules/chart-widget/index.ts@@ -10,7 +10,14 @@ export interface WidgetCredentials {userUuid: string}+export interface WidgetState {+ installed: boolean+ pinIds: string[]+ usesDefault: boolean+}+interface ChartWidgetNativeModule {+ getWidgetState(): Promise<WidgetState>setCredentials(json: string): voidclearCredentials(): voidsetCatalog(json: string): void@@ -47,3 +54,7 @@ export function clearCatalog(): void {export function reloadWidgets(): void {native?.reloadWidgets()}++export async function getWidgetState(): Promise<WidgetState> {+ return (await native?.getWidgetState()) ?? { installed: false, pinIds: [], usesDefault: false }+}diff --git a/products/mobile/modules/chart-widget/ios/AppGroup.swift b/products/mobile/modules/chart-widget/ios/AppGroup.swiftnew file mode 120000index 000000000000..65dc384ebd4a--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/AppGroup.swift@@ -0,0 +1 @@+../../../targets/HedgehogWidget/AppGroup.swift\ No newline at end of filediff --git a/products/mobile/modules/chart-widget/ios/ChartModels.swift b/products/mobile/modules/chart-widget/ios/ChartModels.swiftnew file mode 120000index 000000000000..2145fc3735f4--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/ChartModels.swift@@ -0,0 +1 @@+../../../targets/HedgehogWidget/ChartModels.swift\ No newline at end of filediff --git a/products/mobile/modules/chart-widget/ios/ChartStorage.swift b/products/mobile/modules/chart-widget/ios/ChartStorage.swiftnew file mode 120000index 000000000000..70b6e595e99b--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/ChartStorage.swift@@ -0,0 +1 @@+../../../targets/HedgehogWidget/ChartStorage.swift\ No newline at end of filediff --git a/products/mobile/modules/chart-widget/ios/ChartStore.swift b/products/mobile/modules/chart-widget/ios/ChartStore.swiftnew file mode 120000index 000000000000..88bd72c4e83f--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/ChartStore.swift@@ -0,0 +1 @@+../../../targets/HedgehogWidget/ChartStore.swift\ No newline at end of filediff --git a/products/mobile/modules/chart-widget/ios/ChartWidgetIntent.swift b/products/mobile/modules/chart-widget/ios/ChartWidgetIntent.swiftnew file mode 120000index 000000000000..b3e23f6f7008--- /dev/null+++ b/products/mobile/modules/chart-widget/ios/ChartWidgetIntent.swift@@ -0,0 +1 @@+../../../targets/HedgehogWidget/ChartWidgetIntent.swift\ No newline at end of filediff --git a/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swift b/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swiftindex 5d1141bf0527..159b8cfb6d27 100644--- a/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swift+++ b/products/mobile/modules/chart-widget/ios/ChartWidgetModule.swift@@ -13,88 +13,144 @@ private let keychainService = "com.posthog.code.mobile.chart-widget"private let keychainAccount = "credentials"enum ChartWidgetKeychainError: Error, CustomStringConvertible {- case status(OSStatus)+ case status(OSStatus)- var description: String {- switch self {- case let .status(status):- return "The widget session could not be saved to the keychain (OSStatus \(status))"- }+ var description: String {+ switch self {+ case .status(let status):+ return "The widget session could not be saved to the keychain (OSStatus \(status))"}+ }}// An App Group id is also a keychain access group of every target in that group, so the widget extension reads this// item without a keychain-sharing entitlement.private func credentialsItem() -> [String: Any] {- [- kSecClass as String: kSecClassGenericPassword,- kSecAttrService as String: keychainService,- kSecAttrAccount as String: keychainAccount,- kSecAttrAccessGroup as String: suiteName,- ]+ [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: keychainService,+ kSecAttrAccount as String: keychainAccount,+ kSecAttrAccessGroup as String: suiteName,+ ]}private func writeCredentials(_ json: String) throws {- // The widget refreshes on a timer while the phone is locked, so the item must stay readable after the first unlock.- let attributes: [String: Any] = [- kSecValueData as String: Data(json.utf8),- kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,- ]- var status = SecItemUpdate(credentialsItem() as CFDictionary, attributes as CFDictionary)- if status == errSecItemNotFound {- let item = credentialsItem().merging(attributes) { _, new in new }- status = SecItemAdd(item as CFDictionary, nil)- }- if status != errSecSuccess {- throw ChartWidgetKeychainError.status(status)- }+ // The widget refreshes on a timer while the phone is locked, so the item must stay readable after the first unlock.+ let attributes: [String: Any] = [+ kSecValueData as String: Data(json.utf8),+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,+ ]+ var status = SecItemUpdate(credentialsItem() as CFDictionary, attributes as CFDictionary)+ if status == errSecItemNotFound {+ let item = credentialsItem().merging(attributes) { _, new in new }+ status = SecItemAdd(item as CFDictionary, nil)+ }+ if status != errSecSuccess {+ throw ChartWidgetKeychainError.status(status)+ }}private func deleteCredentials() -> OSStatus {- SecItemDelete(credentialsItem() as CFDictionary)+ SecItemDelete(credentialsItem() as CFDictionary)}private func removeSnapshots() {- guard let defaults = UserDefaults(suiteName: suiteName) else {- return- }- for key in defaults.dictionaryRepresentation().keys- where snapshotKeyPrefixes.contains(where: { key.hasPrefix($0) }) {- defaults.removeObject(forKey: key)- }+ guard let defaults = ChartStore.storage else {+ return+ }+ for key in defaults.keys+ where snapshotKeyPrefixes.contains(where: { key.hasPrefix($0) }) {+ defaults.removeObject(forKey: key)+ }}public class ChartWidgetModule: Module {- public func definition() -> ModuleDefinition {- Name("ChartWidget")+ public func definition() -> ModuleDefinition {+ Name("ChartWidget")- Function("setCredentials") { (json: String) throws in- try writeCredentials(json)- WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)- }+ AsyncFunction("getWidgetState") {+ if #available(iOS 17.0, *) { return try await chartWidgetState() }+ return ["installed": false, "pinIds": [], "usesDefault": false] as [String: Any]+ }++ Function("setCredentials") { (json: String) throws in+ try writeCredentials(json)+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }++ Function("clearCredentials") { () throws in+ let status = deleteCredentials()+ // Charts of the previous account must not show to whoever signs in next, even when the delete failed.+ removeSnapshots()+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ if status != errSecSuccess && status != errSecItemNotFound {+ throw ChartWidgetKeychainError.status(status)+ }+ }- Function("clearCredentials") { () throws in- let status = deleteCredentials()- // Charts of the previous account must not show to whoever signs in next, even when the delete failed.- removeSnapshots()- WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)- if status != errSecSuccess && status != errSecItemNotFound {- throw ChartWidgetKeychainError.status(status)+ Function("setCatalog") { (json: String) in+ if let defaults = ChartStore.storage {+ let catalog = (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any]+ let old = defaults.string(forKey: catalogKey).flatMap {+ (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any]+ }+ let oldPins = old?["pins"] as? [[String: Any]] ?? []+ let pins = catalog?["pins"] as? [[String: Any]] ?? []+ for key in defaults.keys where key.hasPrefix("chart.snapshot.") {+ let id = String(key.dropFirst("chart.snapshot.".count))+ if !pins.contains(where: { $0["id"] as? String == id && $0["eligible"] as? Bool == true })+ {+ defaults.removeObject(forKey: key)+ }+ }+ for pin in pins {+ guard let id = pin["id"] as? String else { continue }+ let previous = oldPins.first { $0["id"] as? String == id }+ let changed =+ String(describing: old?["host"]) != String(describing: catalog?["host"])+ || String(describing: old?["projectId"]) != String(describing: catalog?["projectId"])+ || ["insightId", "shortId", "dashboardId", "displayMode"].contains {+ String(describing: pin[$0]) != String(describing: previous?[$0])+ }+ let key = "chart.snapshot.\(id)"+ if changed {+ defaults.removeObject(forKey: key)+ defaults.removeObject(forKey: "chart.snapshotError.\(id)")+ }+ if pin["eligible"] as? Bool == true, let snapshot = pin["snapshot"] as? [String: Any],+ let at = snapshot["fetchedAt"] as? Double+ {+ let cached = defaults.string(forKey: key).flatMap {+ (try? JSONSerialization.jsonObject(with: Data($0.utf8))) as? [String: Any]+ }+ if at >= (cached?["fetchedAt"] as? Double ?? 0),+ let data = try? JSONSerialization.data(withJSONObject: snapshot),+ let value = String(data: data, encoding: .utf8)+ {+ defaults.set(value, forKey: key)+ defaults.removeObject(forKey: "chart.snapshotError.\(id)")}+ }}-- Function("setCatalog") { (json: String) in- UserDefaults(suiteName: suiteName)?.set(json, forKey: catalogKey)- WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ var metadata = catalog ?? [:]+ metadata["pins"] = pins.map { pin in pin.filter { $0.key != "snapshot" } }+ if let data = try? JSONSerialization.data(withJSONObject: metadata),+ let value = String(data: data, encoding: .utf8)+ {+ defaults.set(value, forKey: catalogKey)}+ }+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }- Function("clearCatalog") {- UserDefaults(suiteName: suiteName)?.removeObject(forKey: catalogKey)- WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)- }+ Function("clearCatalog") {+ ChartStore.storage?.removeObject(forKey: catalogKey)+ removeSnapshots()+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)+ }- Function("reloadWidgets") {- WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)- }+ Function("reloadWidgets") {+ WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)}+ }}diff --git a/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspec b/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspecindex 4e45a824729d..ac8f569bd405 100644--- a/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspec+++ b/products/mobile/modules/chart-widget/ios/PostHogChartWidget.podspec@@ -17,7 +17,7 @@ Pod::Spec.new do |s|s.static_framework = trues.dependency 'ExpoModulesCore'- s.frameworks = 'WidgetKit', 'Security'+ s.frameworks = 'WidgetKit', 'Security', 'CryptoKit', 'AppIntents's.source_files = '**/*.{h,m,swift}'s.pod_target_xcconfig = {diff --git a/products/mobile/releases/requests/native-1110.json b/products/mobile/releases/requests/native-1110.jsonnew file mode 100644index 000000000000..bc7ee746dce9--- /dev/null+++ b/products/mobile/releases/requests/native-1110.json@@ -0,0 +1,8 @@+{+ "schemaVersion": 1,+ "id": "native-1110",+ "kind": "native",+ "runtimeVersion": "1.11.0",+ "previousRelease": "native-1100",+ "notes": "This release adds the Chart home screen widget on iOS and Android. It shows a pinned insight from the Views tab as a number, chart or compact rows, including SQL values and a dashboard's selected tile, in small, medium and large sizes, and refreshes by itself every 30 minutes with a read-only copy of the session. Verify: add the widget from the home screen, pick a pin in the iOS Edit widget sheet or the Android setup screen, check formatted currency, percentages, text, tables, funnels and retention against the app, change a dashboard's selected tile and confirm the widget updates, check the large centered number, chart labels and headline in light and dark appearances, check the value and age against the app, sign out and confirm the widget asks to sign in, switch project and confirm the widget says the pin is in another project, and confirm the Hedgehog widget still plays."+}diff --git a/products/mobile/scripts/check_chart_widget.kt b/products/mobile/scripts/check_chart_widget.ktnew file mode 100644index 000000000000..1d5a6ad38160--- /dev/null+++ b/products/mobile/scripts/check_chart_widget.kt@@ -0,0 +1,52 @@+package com.posthog.code.mobile.chart++import org.json.JSONArray+import org.json.JSONObject+import java.io.File++fun main(args: Array<String>) {+ val fixtures = JSONArray(File(args.single()).readText())+ for (index in 0 until fixtures.length()) {+ val fixture = fixtures.getJSONObject(index)+ val expected = fixture.getJSONObject("expected")+ val pin = CatalogPin("pin-example", "insight", "Example", "", 101, "example1", null, true, true, true, null)+ val snapshot = InsightParser.parse(fixture.getJSONObject("response"), pin, 1793617200000L)+ val name = fixture.getString("name")+ for ((field, actual) in listOf("chartValueText" to snapshot.chartValueText, "axisLowText" to snapshot.axisLowText, "axisHighText" to snapshot.axisHighText)) {+ if (expected.has(field)) check(actual == expected.stringOrNull(field)) { "$name: $field" }+ }+ if (expected.has("intervalLabel")) check(snapshot.intervalLabel == expected.getString("intervalLabel")) { "$name: interval" }+ check(snapshot.display == expected.getString("display")) { "$name: display ${snapshot.display}" }+ if (expected.has("valueText")) check(snapshot.valueText == expected.stringOrNull("valueText")) { "$name: value ${snapshot.valueText}" }+ if (expected.has("firstAt")) check(snapshot.series.first().points.first().at == expected.getString("firstAt")) { "$name: date" }+ if (expected.has("firstValue")) check(snapshot.series.first().points.first().value == expected.getDouble("firstValue")) { "$name: duplicate sum" }+ if (expected.optBoolean("lastIsGap")) check(snapshot.series.first().points.last().value.isNaN()) { "$name: gap" }+ if (expected.has("firstRowValue")) check(snapshot.rows.first().value == expected.getString("firstRowValue")) { "$name: first row" }+ if (expected.has("rowCount")) check(snapshot.rows.size == expected.getInt("rowCount")) { "$name: rows" }+ if (expected.has("seriesCount")) check(snapshot.series.size == expected.getInt("seriesCount")) { "$name: series" }+ if (expected.has("lastValue")) check(snapshot.series.first().points.last().value == expected.getDouble("lastValue")) { "$name: last value" }+ check(ChartSnapshot.parse(snapshot.toJson()) == snapshot) { "$name: round trip" }+ println("ok $name")+ }+ check(InsightParser.number("1".repeat(16000) + "!") == null)+ check(InsightParser.number(" -1.25e2 ") == -125.0)+ val rows = JSONArray()+ val start = java.time.LocalDateTime.of(2026, 1, 1, 0, 0)+ for (index in 0 until 10_000) {+ val at = start.plusHours(index.toLong()).toString()+ rows.put(JSONArray(listOf(at, 1)))+ rows.put(JSONArray(listOf(at, 2)))+ }+ val response = JSONObject().put("query", JSONObject().put("kind", "DataVisualizationNode")+ .put("source", JSONObject().put("kind", "HogQLQuery")).put("display", "ActionsLineGraphCumulative"))+ .put("columns", JSONArray(listOf("at", "value")))+ .put("types", JSONArray().put(JSONArray(listOf("at", "DateTime"))).put(JSONArray(listOf("value", "UInt64"))))+ .put("result", rows)+ val pin = CatalogPin("scale", "insight", "Example", "", 101, "example1", null, true, true, true, null)+ val snapshot = InsightParser.parse(response, pin, 1793617200000L)+ check(snapshot.series.single().points.size == 60)+ check(snapshot.series.single().points.first().value == 29_823.0)+ check(snapshot.series.single().points.last().value == 30_000.0)+ println("ok large cumulative SQL result")++}diff --git a/products/mobile/scripts/check_chart_widget.swift b/products/mobile/scripts/check_chart_widget.swiftindex 7db49832243c..b16c2a419096 100644--- a/products/mobile/scripts/check_chart_widget.swift+++ b/products/mobile/scripts/check_chart_widget.swift@@ -1,3 +1,4 @@+import CryptoKitimport Foundation// Usage: check-chart@@ -33,6 +34,7 @@ struct CheckChartWidget {try checkStore(now: now)try await checkRefresh(now: now)try checkState(now: now)+ try checkInsightFormats(now: now)if failures > 0 {print("\(failures) check(s) failed")@@ -303,19 +305,29 @@ struct CheckChartWidget {let noMatch = Data(json(["results": [["short_id": "other", "query": trends(), "result": []]]] as JSONObject).utf8)check("short id read without a match is not_found", ChartFetcher.outcome(status: 200, body: noMatch, pin: byShortId, now: now) == .failed(.notFound))let funnel = Data(json(["query": ["kind": "InsightVizNode", "source": ["kind": "FunnelsQuery"]], "result": []] as JSONObject).utf8)- check("a non-trends result is bad_data", ChartFetcher.outcome(status: 200, body: funnel, pin: insight, now: now) == .failed(.badData))+ if case .snapshot(let snapshot) = ChartFetcher.outcome(status: 200, body: funnel, pin: insight, now: now) {+ check("an empty funnel remains a valid snapshot", snapshot.display == "rows" && snapshot.rows?.isEmpty == true)+ } else { check("an empty funnel remains a valid snapshot", false) }}static func checkStore(now: Date) throws {let suite = "check-chart-widget-\(ProcessInfo.processInfo.processIdentifier)"- let store = try require(UserDefaults(suiteName: suite), "test suite")- defer { store.removePersistentDomain(forName: suite) }+ let raw = try require(UserDefaults(suiteName: suite), "test suite")+ let key = SymmetricKey(size: .bits256)+ let store = ChartStorage(defaults: raw, key: key)+ defer { raw.removePersistentDomain(forName: suite) }check("app group from the extension id", AppGroup.appId(fromExtensionBundleId: "com.posthog.code.mobile.dev.HedgehogWidget") == "com.posthog.code.mobile.dev"&& AppGroup.appId(fromExtensionBundleId: "com.posthog.code.mobile") == "com.posthog.code.mobile")store.set(catalogJSON, forKey: ChartStore.catalogKey)let catalog = try require(ChartStore.catalog(store: store), "stored catalog")let pin = try require(catalog.pin(id: "pin-a"), "stored pin")let dashboard = try require(catalog.pin(id: "pin-b"), "stored dashboard pin")+ check("store: catalog has no plaintext copy", raw.string(forKey: ChartStore.catalogKey) == nil && raw.data(forKey: ChartStore.catalogKey) != nil)+ let wrongKey = ChartStorage(defaults: raw, key: SymmetricKey(size: .bits256))+ check("store: a wrong key cannot read values", wrongKey.string(forKey: ChartStore.catalogKey) == nil)+ raw.set("legacy result", forKey: "chart.snapshot.legacy")+ _ = ChartStorage(defaults: raw, key: key)+ check("store: old plaintext is removed", raw.object(forKey: "chart.snapshot.legacy") == nil)check("store: catalog reads back", ChartStore.catalog(store: store)?.pins.count == 4)let snapshot = ChartSample.snapshot(pinId: "pin-a", value: "1,284", delta: 12, deltaText: "12%", values: [1, 2, 3], now: now)ChartRefresh.record(.failed(.network), pin: pin, credentials: credentials, at: now, store: store)@@ -325,6 +337,9 @@ struct CheckChartWidget {ChartRefresh.record(.snapshot(snapshot), pin: pin, credentials: credentials, at: now, store: store)check("store: a good read writes the snapshot", ChartStore.snapshot(pinId: "pin-a", store: store) == snapshot)check("store: a good read clears the error", ChartStore.error(pinId: "pin-a", store: store) == nil)+ let older = ChartSample.snapshot(pinId: "pin-a", value: "Old", delta: 0, deltaText: "", values: [0], now: now.addingTimeInterval(-60))+ ChartRefresh.record(.snapshot(older), pin: pin, credentials: credentials, at: now, store: store)+ check("store: older background read preserves the app snapshot", ChartStore.snapshot(pinId: "pin-a", store: store) == snapshot)ChartRefresh.record(.failed(.rateLimited), pin: pin, credentials: credentials, at: now, store: store)check("store: a failure keeps the snapshot", ChartStore.snapshot(pinId: "pin-a", store: store) == snapshot)check("store: snapshotError kind", store.string(forKey: "chart.snapshotError.pin-a")?.contains("rate_limited") == true)@@ -334,12 +349,24 @@ struct CheckChartWidget {let marker = store.string(forKey: "chart.pinProject.pin-a").flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) as? JSONObject }check("store: pin project marker JSON", (marker?["projectId"] as? Int) == 2 && (marker?["projectName"] as? String) == "PostHog App")check("store: pin project marker reads back", ChartStore.pinProject(pinId: "pin-a", store: store) == ChartPinProject(projectId: 2, projectName: "PostHog App"))+ for kind in [ChartErrorKind.auth, .notFound] {+ ChartStore.save(snapshot, store: store)+ ChartRefresh.record(.failed(kind), pin: pin, credentials: credentials, at: now, store: store)+ check("store: access failures discard cached values", ChartStore.snapshot(pinId: pin.id, store: store) == nil)+ }+ for kind in [ChartErrorKind.auth, .notFound, .network] {+ ChartStore.save(snapshot, store: store)+ ChartRefresh.record(.failed(kind), pin: pin, credentials: credentials, at: now.addingTimeInterval(-60), store: store)+ check("store: a delayed failure preserves newer app data", ChartStore.snapshot(pinId: pin.id, store: store) == snapshot+ && ChartStore.error(pinId: pin.id, store: store) == nil)+ }let credentialsJSON = #"{"version":1,"host":"https://eu.posthog.com","projectId":7,"projectName":"Shop","accessToken":"pha_example","expiresAt":null,"userUuid":"u"}"#check("credentials decode with a null expiry", ChartStore.decodeCredentials(Data(credentialsJSON.utf8))?.isExpired(at: now) == false)for (target, changedCatalog) in [(pin, catalogJSON.replacingOccurrences(of: "\"insightId\": 123", with: "\"insightId\": 321")),(dashboard, catalogJSON.replacingOccurrences(of: "\"dashboardId\": 12", with: "\"dashboardId\": 13")),+ (pin, catalogJSON.replacingOccurrences(of: "\"insightId\": 123", with: "\"displayMode\": \"rows\", \"insightId\": 123")),] {let currentSnapshot = ChartSample.snapshot(pinId: target.id, value: "654", delta: 0, deltaText: "No change", values: [654], now: now)let oldSnapshot = ChartSample.snapshot(pinId: target.id, value: "123", delta: 0, deltaText: "No change", values: [123], now: now)@@ -402,12 +429,13 @@ struct CheckChartWidget {static func checkRefresh(now: Date) async throws {let suite = "check-chart-refresh-\(ProcessInfo.processInfo.processIdentifier)"- let store = try require(UserDefaults(suiteName: suite), "refresh test suite")- defer { store.removePersistentDomain(forName: suite) }+ let raw = try require(UserDefaults(suiteName: suite), "refresh test suite")+ let store = ChartStorage(defaults: raw, key: SymmetricKey(size: .bits256))+ defer { raw.removePersistentDomain(forName: suite) }store.set(catalogJSON, forKey: ChartStore.catalogKey)let pin = try require(ChartStore.catalog(store: store)?.pin(id: "pin-b"), "original dashboard tile")let requests = PendingFetches()- let refresh = ChartRefresh(store: store, fetch: { pin, _, _ in await requests.fetch(pin) })+ let refresh = ChartRefresh(store: store, currentCredentials: { credentials }, fetch: { pin, _, _ in await requests.fetch(pin) })let original = Task { await refresh.refresh(pin, credentials: credentials, now: now) }await requests.waitForRequest(456)@@ -424,6 +452,11 @@ struct CheckChartWidget {await requests.complete(456, with: .snapshot(oldSnapshot))await original.valuecheck("refresh: the old tile cannot overwrite the new result", ChartStore.snapshot(pinId: pin.id, store: store) == snapshot)+ store.removeObject(forKey: "chart.snapshot.\(pin.id)")+ let signedOut = ChartRefresh(store: store, currentCredentials: { nil }, fetch: { _, _, _ in .snapshot(snapshot) })+ await signedOut.refresh(replacement, credentials: credentials, now: now)+ check("refresh: an ended session cannot repopulate the cache", ChartStore.snapshot(pinId: pin.id, store: store) == nil)+}static func checkState(now: Date) throws {@@ -460,7 +493,16 @@ struct CheckChartWidget {message(ChartResolver.content(primary: signups, extras: [], store: state(credentials: expired), links: links, now: now)) == "Open PostHog to update")let unconfigured = ChartResolver.content(primary: nil, extras: [], store: state(), links: links, now: now)- check("state: not configured", message(unconfigured) == "Choose a pin")+ check("state: automatically uses the first eligible pin", unconfigured.primary.title == "Signups" && unconfigured.primary.state == .loading)+ let noCatalog = ChartResolver.content(primary: nil, extras: [], store: state(catalog: nil), links: links, now: now)+ check("state: missing catalog points to the app", message(noCatalog) == "Open PostHog to load your pins")+ let emptyCatalog = ChartCatalog(version: 1, host: catalog.host, projectId: 2, projectName: nil, writtenAt: 0, pins: [])+ let noPins = ChartResolver.content(primary: nil, extras: [], store: state(catalog: emptyCatalog), links: links, now: now)+ check("state: empty catalog explains the next step", message(noPins) == "No pinned views available")+ let defaults = ChartResolver.selections(primary: nil, extras: [signups], family: .large, catalog: catalog)+ check("selection: default participates in fetch and deduplication", defaults.0 == signups && defaults.1.isEmpty)+ let chosen = ChartResolver.selections(primary: ChartSelection(id: "pin-b", name: "Product KPIs"), extras: [], family: .medium, catalog: catalog)+ check("selection: explicit choice wins over the default", chosen.0?.id == "pin-b")let revenue = ChartSelection(id: "pin-x", name: "Revenue")let gone = ChartResolver.content(primary: revenue, extras: [], store: state(), links: links, now: now)@@ -497,7 +539,7 @@ struct CheckChartWidget {check("state: another project sends nothing", ChartResolver.pinsToFetch([signups], store: state(credentials: elsewhere), now: now).isEmpty)let loading = ChartResolver.content(primary: signups, extras: [], store: state(), links: links, now: now)- check("state: first read pending", loading.primary.state == .loading && loading.primary.title == "Signups")+ check("state: first read pending", loading.primary.state == .loading && loading.primary.title == "Signups" && loading.primary.link == links.pin(catalog.pin(id: "pin-a")!))let cached = ChartSample.snapshot(pinId: "pin-a", value: "1,284", delta: 12, deltaText: "12%", values: [1, 2], now: now.addingTimeInterval(-3600))let stale = ChartResolver.content(primary: signups, extras: [],@@ -552,6 +594,53 @@ struct CheckChartWidget {check("medium: no extra pins", ChartResolver.selections(primary: signups, extras: extras, family: .medium).1.isEmpty)}+ static func checkInsightFormats(now: Date) throws {+ let path = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()+ .appendingPathComponent("modules/chart-widget/fixtures/insights.json")+ let fixtures = try JSONSerialization.jsonObject(with: Data(contentsOf: path)) as! [JSONObject]+ let pin = ChartPin(id: "pin-example", kind: "insight", name: "Example", subtitle: nil,+ insightId: 101, shortId: "example1", dashboardId: nil, eligible: true,+ number: true, chart: true, reason: nil)+ for fixture in fixtures {+ let name = fixture["name"] as! String+ let response = fixture["response"] as! JSONObject+ let expected = fixture["expected"] as! JSONObject+ let snapshot = try InsightParser.snapshot(response: response, pin: pin, now: now)+ check("format: \(name) round trip", try JSONDecoder().decode(ChartSnapshot.self, from: JSONEncoder().encode(snapshot)) == snapshot)+ if let interval = expected["intervalLabel"] as? String { check("format: \(name) interval", snapshot.intervalLabel == interval) }+ check("format: \(name) display", snapshot.display == expected["display"] as? String)+ for (field, actual) in [("chartValueText", snapshot.chartValueText), ("axisLowText", snapshot.axisLowText), ("axisHighText", snapshot.axisHighText)] where expected[field] != nil {+ check("format: \(name) \(field)", actual == expected[field] as? String)+ }+ if let value = expected["valueText"] as? String { check("format: \(name) value", snapshot.valueText == value, snapshot.valueText ?? "nil") }+ if expected["valueText"] is NSNull { check("format: \(name) null value", snapshot.valueText == nil) }+ if let value = expected["firstAt"] as? String { check("format: \(name) date", snapshot.series.first?.points.first?.at == value) }+ if let value = expected["firstValue"] as? Double { check("format: \(name) first point", snapshot.series.first?.points.first?.value == value) }+ if expected["lastIsGap"] as? Bool == true { check("format: \(name) gap", snapshot.series.first?.points.last?.value == nil) }+ if let value = expected["firstRowValue"] as? String { check("format: \(name) first row", snapshot.rows?.first?.value == value) }+ if let count = expected["rowCount"] as? Int { check("format: \(name) rows", snapshot.rows?.count == count) }+ if let count = expected["seriesCount"] as? Int { check("format: \(name) series", snapshot.series.count == count) }+ if let value = expected["lastValue"] as? Double { check("format: \(name) last point", snapshot.series.first?.points.last?.value == value) }+ }+ check("SQL: long numeric text stays text", InsightParser.number(String(repeating: "1", count: 16000) + "!") == nil)+ check("SQL: decimals still parse", InsightParser.number(" -1.25e2 ") == -125)+ let start = ChartDates.parse("2026-01-01T00:00:00Z")!+ let formatter = ISO8601DateFormatter()+ let rows: [[Any]] = (0..<10_000).flatMap { index in+ let at = formatter.string(from: start.addingTimeInterval(Double(index) * 3600))+ return [[at, 1], [at, 2]]+ }+ let response: JSONObject = [+ "query": ["kind": "DataVisualizationNode", "source": ["kind": "HogQLQuery"], "display": "ActionsLineGraphCumulative"],+ "columns": ["at", "value"], "types": [["at", "DateTime"], ["value", "UInt64"]], "result": rows,+ ]+ let large = try InsightParser.snapshot(response: response, pin: pin, now: now)+ check("large SQL: only the latest 60 points", large.series.first?.points.count == 60)+ check("large SQL: cumulative includes earlier duplicate rows", large.series.first?.points.first?.value == 29_823+ && large.series.first?.points.last?.value == 30_000)++ }+static func require<T>(_ value: T?, _ name: String) throws -> T {guard let value else {check(name, false, "missing")diff --git a/products/mobile/src/api/budget.ts b/products/mobile/src/api/budget.tsindex 2bb1516c7124..1771811de6bc 100644--- a/products/mobile/src/api/budget.ts+++ b/products/mobile/src/api/budget.ts@@ -62,6 +62,17 @@ export function canSpend(family: BudgetFamily, now: number = Date.now()): booleareturn bucketsFor(family, now).every((bucket) => bucket.tokens >= 1)}+/** Delay until a background read can leave half of every bucket for foreground requests. */+export function backgroundReadDelay(family: BudgetFamily, now: number = Date.now()): number {+ const state = bucketsFor(family, now)+ return Math.max(+ 0,+ ...BUDGETS[family].map((spec, index) =>+ Math.ceil(((spec.capacity / 2 + 1 - (state[index]?.tokens ?? 0)) * spec.windowMs) / spec.capacity)+ )+ )+}+/** Takes one token from every bucket of the family, or none when any bucket is empty. */export function trySpend(family: BudgetFamily, now: number = Date.now()): boolean {const state = bucketsFor(family, now)diff --git a/products/mobile/src/api/shortcuts.ts b/products/mobile/src/api/shortcuts.tsindex 665820efae17..f3ea56db11ad 100644--- a/products/mobile/src/api/shortcuts.ts+++ b/products/mobile/src/api/shortcuts.ts@@ -26,6 +26,11 @@ export interface ShortcutInput {/** One page holds every pin the app shows. A longer list shows a note instead of a second page. */export const SHORTCUT_PAGE_SIZE = 100+/** True when the page holds every starred row, so a pin missing from it is really gone. */+export function isCompleteShortcutPage(page: PaginatedApi<FileSystemShortcutApi>): boolean {+ return !page.next+}+export function fetchShortcuts(signal?: AbortSignal): Promise<PaginatedApi<FileSystemShortcutApi>> {return apiJson<PaginatedApi<FileSystemShortcutApi>>(projectPath('file_system_shortcut/'), {query: { limit: SHORTCUT_PAGE_SIZE },diff --git a/products/mobile/src/auth/BootSplash.test.tsx b/products/mobile/src/auth/BootSplash.test.tsxindex fe05c1ffb5ea..42e89228f6fb 100644--- a/products/mobile/src/auth/BootSplash.test.tsx+++ b/products/mobile/src/auth/BootSplash.test.tsx@@ -48,6 +48,7 @@ jest.mock('@/features/updates/useAutomaticUpdates', () => ({ useAutomaticUpdatesjest.mock('@/features/chat/draftPersistence', () => ({}))jest.mock('@/features/offlineCache', () => ({ installOfflineCache: jest.fn() }))jest.mock('@/features/hedgehog/useHedgehogWidgetSync', () => ({ useHedgehogWidgetSync: jest.fn() }))+jest.mock('@/features/widgets/useChartWidgetSync', () => ({ useChartWidgetSync: jest.fn() }))jest.mock('@/features/notifications/pushRegistration', () => ({ configureNotifications: jest.fn() }))jest.mock('@/features/notifications/useNotificationRouting', () => ({ useNotificationRouting: jest.fn() }))jest.mock('@/features/notifications/usePushRegistration', () => ({ usePushRegistration: jest.fn() }))diff --git a/products/mobile/src/auth/authStore.ts b/products/mobile/src/auth/authStore.tsindex 8919cbcc6cd3..0d1b5c6f24f2 100644--- a/products/mobile/src/auth/authStore.ts+++ b/products/mobile/src/auth/authStore.ts@@ -1,4 +1,5 @@import AsyncStorage from '@react-native-async-storage/async-storage'+import { AppState, type NativeEventSubscription } from 'react-native'import { create } from 'zustand'import { createJSONStorage, persist } from 'zustand/middleware'@@ -64,9 +65,11 @@ export interface AuthState {signOut: () => Promise<void>}-/** Refresh at launch when the access token has less than this left, so the first requests do not all 401. */const RESTORE_REFRESH_MARGIN_MS = 60_000+/** Refresh at launch or on foreground when the access token has less than this left, so the home screen widget's copy stays valid. */+const FOREGROUND_REFRESH_MARGIN_MS = 24 * 60 * 60_000+type SignOutTask = () => Promise<undefined | (() => void)>type SessionEndTask = () => void | Promise<void>@@ -310,11 +313,13 @@ export const useAuthStore = create<AuthState>()(method: owner.method,region: regionForHost(owner.host),})+ let refreshedDuringRestore = falseif (tokens.kind === 'oauth' &&tokens.expiresAt !== null &&tokens.expiresAt - Date.now() < RESTORE_REFRESH_MARGIN_MS) {+ refreshedDuringRestore = truetry {if ((await refreshAccessToken()) === null) {return@@ -328,6 +333,9 @@ export const useAuthStore = create<AuthState>()(await get().reloadAccount()}set({ status: 'signed_in', signedIn: true })+ if (!refreshedDuringRestore && AppState.currentState === 'active') {+ refreshBeforeForegroundMargin()+ }const restored = get().userif (restored) {identify(restored.distinctId)@@ -571,7 +579,29 @@ export function refreshAccessToken(): Promise<string | null> {return promise}+function refreshBeforeForegroundMargin(): void {+ const tokens = getSessionTokens()+ if (+ useAuthStore.getState().status !== 'signed_in' ||+ tokens?.kind !== 'oauth' ||+ tokens.expiresAt === null ||+ tokens.expiresAt - Date.now() >= FOREGROUND_REFRESH_MARGIN_MS+ ) {+ return+ }+ // Offline or a server error keeps the session; the next foreground or 401 tries again.+ refreshAccessToken().catch(() => undefined)+}++let foregroundSubscription: NativeEventSubscription | null = null+export function installAuthProvider(): void {+ foregroundSubscription?.remove()+ foregroundSubscription = AppState.addEventListener('change', (state) => {+ if (state === 'active') {+ refreshBeforeForegroundMargin()+ }+ })setAuthProvider({getAuth: () => {const state = useAuthStore.getState()diff --git a/products/mobile/src/auth/sessionRestore.test.ts b/products/mobile/src/auth/sessionRestore.test.tsindex 90fbe36f9612..69bd4eaa4c13 100644--- a/products/mobile/src/auth/sessionRestore.test.ts+++ b/products/mobile/src/auth/sessionRestore.test.ts@@ -1,4 +1,5 @@import * as SecureStore from 'expo-secure-store'+import { AppState } from 'react-native'import { installAuthProvider, refreshAccessToken, useAuthStore } from './authStore'import { loadTokens, saveTokens, setSessionTokens } from './tokens'@@ -38,8 +39,10 @@ describe('stored session identity', () => {expect(await loadTokens()).toBeNull()})- test('restores the secure identity after a stalled refresh and allows a later refresh to recover', async () => {+ test('restores a valid session before a stalled refresh and allows a later refresh to recover', async () => {jest.useFakeTimers()+ const previousState = AppState.currentState+ AppState.currentState = 'active'try {let stalledSignal: AbortSignal | null | undefinedlet stall = true@@ -70,7 +73,10 @@ describe('stored session identity', () => {organizations: [],})}) as unknown as typeof fetch- await saveTokens(tokens, { host, clientId: 'example-client', method: 'oauth', userUuid: 'current-user' })+ await saveTokens(+ { ...tokens, expiresAt: Date.now() + 10 * 60_000 },+ { host, clientId: 'example-client', method: 'oauth', userUuid: 'current-user' }+ )useAuthStore.setState({status: 'loading',signedIn: false,@@ -96,12 +102,15 @@ describe('stored session identity', () => {setSessionTokens(null)installAuthProvider()const restoring = useAuthStore.getState().restore()- await jest.advanceTimersByTimeAsync(20_000)+ await jest.advanceTimersByTimeAsync(0)await restoring+ expect(useAuthStore.getState().status).toBe('signed_in')+ expect(stalledSignal?.aborted).toBe(false)+ await jest.advanceTimersByTimeAsync(20_000)expect(stalledSignal?.aborted).toBe(true)expect(useAuthStore.getState()).toMatchObject({ status: 'signed_in', signedIn: true })expect(await loadTokens()).toMatchObject({ accessToken: 'example-access', refreshToken: 'example-refresh' })- expect(requests).toEqual([`${host}/oauth/token`, `${host}/api/users/@me/`])+ expect(requests).toEqual([`${host}/api/users/@me/`, `${host}/oauth/token`])expect(useAuthStore.getState()).toMatchObject({host,clientId: 'example-client',@@ -116,6 +125,7 @@ describe('stored session identity', () => {tokens: { accessToken: 'example-rotated-access' },})} finally {+ AppState.currentState = previousStatejest.useRealTimers()}})diff --git a/products/mobile/src/auth/tokenRefresh.test.ts b/products/mobile/src/auth/tokenRefresh.test.tsindex c0155b283a0a..f66458f7ff9c 100644--- a/products/mobile/src/auth/tokenRefresh.test.ts+++ b/products/mobile/src/auth/tokenRefresh.test.ts@@ -1,10 +1,19 @@+import { waitFor } from '@testing-library/react-native'import * as SecureStore from 'expo-secure-store'+import { AppState, type AppStateStatus } from 'react-native'import { apiJson, NotSignedInError, projectPath } from '@/api/client'import { TransportError } from '@/api/transport'import { addSessionEndTask, addSignOutTask, installAuthProvider, useAuthStore } from './authStore'import { authorize, OAuthError, refreshTokens } from './oauth'-import { getSessionIdentity, getSessionTokens, loadTokens, saveTokens, setSessionTokens } from './tokens'+import {+ getSessionIdentity,+ getSessionTokens,+ loadTokens,+ type SessionTokens,+ saveTokens,+ setSessionTokens,+} from './tokens'jest.mock('@react-native-async-storage/async-storage', () =>require('@react-native-async-storage/async-storage/jest/async-storage-mock')@@ -157,6 +166,40 @@ describe('token refresh through the API client', () => {expect(getSessionTokens()?.accessToken).toBe(accessToken)})+ test.each([+ { name: 'a foreground refreshes a token that ends within a day, once', expiresIn: 60_000, refreshes: 1 },+ { name: 'a foreground leaves a token with more than a day left', expiresIn: 2 * 86_400_000, refreshes: 0 },+ ])('$name', async ({ expiresIn, refreshes }) => {+ const tokenRequests: string[] = []+ fetchMock.mockImplementation(async (url) => {+ if (url !== `${HOST}/oauth/token`) {+ return json(404, {})+ }+ tokenRequests.push(url)+ return json(200, { access_token: 'new-access', refresh_token: 'new-refresh', expires_in: 604800 })+ })+ await saveTokens({ ...(getSessionTokens() as SessionTokens), expiresAt: Date.now() + expiresIn })+ let onAppState: ((state: AppStateStatus) => void) | undefined+ const subscribe = jest.spyOn(AppState, 'addEventListener').mockImplementation((_type, listener) => {+ onAppState = listener+ return { remove: () => undefined }+ })+ try {+ installAuthProvider()++ onAppState?.('background')+ onAppState?.('active')+ onAppState?.('active')++ expect(tokenRequests).toHaveLength(refreshes)+ await waitFor(() =>+ expect(getSessionTokens()?.accessToken).toBe(refreshes > 0 ? 'new-access' : 'old-access')+ )+ } finally {+ subscribe.mockRestore()+ }+ })+test.each([{ operation: 'sign-in', status: 200 },{ operation: 'sign-in', status: 400 },diff --git a/products/mobile/src/auth/tokens.ts b/products/mobile/src/auth/tokens.tsindex b141e17d7317..1ae53f4e4dfa 100644--- a/products/mobile/src/auth/tokens.ts+++ b/products/mobile/src/auth/tokens.ts@@ -52,6 +52,32 @@ let current: SessionTokens | null = nulllet generation = 0let storageQueue: Promise<void> = Promise.resolve()+/** `session`: a sign in, sign out or restore. `refresh`: the same session with rotated tokens. */+export type SessionTokensChange = 'session' | 'refresh'++const tokenListeners = new Set<(change: SessionTokensChange) => void>()++/**+ * Calls `listener` after the in-memory tokens change. Features that keep a copy of the session, such as the home screen+ * widget, subscribe here so auth does not import them.+ */+export function onSessionTokensChanged(listener: (change: SessionTokensChange) => void): () => void {+ tokenListeners.add(listener)+ return () => {+ tokenListeners.delete(listener)+ }+}++function publishTokens(change: SessionTokensChange): void {+ for (const listener of tokenListeners) {+ try {+ listener(change)+ } catch {+ // A listener failure must not fail the sign in, refresh or sign out that changed the tokens.+ }+ }+}+function serializeStorage<T>(work: () => Promise<T>): Promise<T> {const result = storageQueue.then(work, work)storageQueue = result.then(@@ -82,6 +108,7 @@ export function setSessionTokens(tokens: SessionTokens | null, owner: SessionIdeidentity = owner ? Object.freeze({ ...owner }) : nullcurrent = tokensgeneration += 1+ publishTokens('session')}// expo-secure-store has no web implementation. The web build is a dev and preview target, so it keeps tokens in@@ -177,6 +204,7 @@ export async function loadTokens(): Promise<SessionTokens | null> {current = validOwner ? tokens : nullidentity = validOwner ? Object.freeze({ ...owner }) : nullgeneration += 1+ publishTokens('session')return current}@@ -189,6 +217,7 @@ export async function saveTokens(tokens: SessionTokens, owner: SessionIdentity |await writeItem(STORAGE_KEY, storedSession(tokens, owner))current = tokensidentity = owner ? Object.freeze({ ...owner }) : null+ publishTokens('refresh')})}@@ -231,6 +260,7 @@ export async function saveRefreshedTokens(tokens: SessionTokens, expectedGeneratreturn false}current = tokens+ publishTokens('refresh')return true})}@@ -239,6 +269,7 @@ export async function clearTokens(): Promise<void> {current = nullidentity = nullgeneration += 1+ publishTokens('session')try {await serializeStorage(() => deleteItem(STORAGE_KEY))} catch {diff --git a/products/mobile/src/features/chat/chatNavigation.test.tsx b/products/mobile/src/features/chat/chatNavigation.test.tsxindex 408045f19d99..0d9b9fe09495 100644--- a/products/mobile/src/features/chat/chatNavigation.test.tsx+++ b/products/mobile/src/features/chat/chatNavigation.test.tsx@@ -29,6 +29,7 @@ jest.mock('@/demo/demoMode', () => ({}))jest.mock('@/features/chat/draftPersistence', () => ({}))jest.mock('@/features/hedgehog/useHedgehogWidgetSync', () => ({ useHedgehogWidgetSync: jest.fn() }))+jest.mock('@/features/widgets/useChartWidgetSync', () => ({ useChartWidgetSync: jest.fn() }))jest.mock('@/features/notifications/pushRegistration', () => ({ configureNotifications: jest.fn() }))jest.mock('@/features/notifications/usePushRegistration', () => ({ usePushRegistration: jest.fn() }))jest.mock('expo-notifications', () => ({diff --git a/products/mobile/src/features/views/list/tileEligibility.ts b/products/mobile/src/features/views/list/tileEligibility.tsindex dbca7e6308c1..eb914792f6b1 100644--- a/products/mobile/src/features/views/list/tileEligibility.ts+++ b/products/mobile/src/features/views/list/tileEligibility.ts@@ -9,8 +9,11 @@ export interface TilesByEligibility {unusable: { tile: DashboardTileView; reason: string }[]}-/** One short reason, shown after the tile's kind: "Line · Has 3 series". */-export function tileLimitReason(tile: DashboardTileView, mode: TileMode): string {+/** One short reason, shown after the tile's kind: "Line · Has 3 series". The home screen widget shows it too. */+export function tileLimitReason(+ tile: Pick<DashboardTileView, 'kind' | 'hasBreakdown' | 'seriesCount'>,+ mode: TileMode+): string {if (tile.kind === 'text') {return 'Text card'}diff --git a/products/mobile/src/features/views/listReads.ts b/products/mobile/src/features/views/listReads.tsindex 3428da9a8167..c180bba8626e 100644--- a/products/mobile/src/features/views/listReads.ts+++ b/products/mobile/src/features/views/listReads.ts@@ -1,6 +1,7 @@import { BudgetExceededError, type BudgetFamily } from '@/api/budget'import { ApiError } from '@/api/client'-import { retryUnlessMissing } from '@/api/reports'+import { type PaginatedApi, retryUnlessMissing } from '@/api/reports'+import { type FileSystemShortcutApi, fetchShortcuts } from '@/api/shortcuts'import { viewsQueue } from './refreshQueue'import { reportScopeError } from './useViewsAccess'@@ -35,3 +36,17 @@ export async function listRead<T>(throw error}}++/**+ * The pin list read that `usePins` and the home screen widget's prefetch share. `beforeRead` runs once the family's+ * pause ends, just before the request, so a caller can stop a read that belongs to an earlier session.+ */+export function readShortcuts(+ signal?: AbortSignal,+ beforeRead?: () => void+): Promise<PaginatedApi<FileSystemShortcutApi>> {+ return listRead('dashboards', signal, () => {+ beforeRead?.()+ return fetchShortcuts(signal)+ })+}diff --git a/products/mobile/src/features/views/pinHooks.ts b/products/mobile/src/features/views/pinHooks.tsindex a53020469d19..d677fb5da1a0 100644--- a/products/mobile/src/features/views/pinHooks.ts+++ b/products/mobile/src/features/views/pinHooks.ts@@ -8,7 +8,7 @@ import {createShortcut,deleteShortcut,type FileSystemShortcutApi,- fetchShortcuts,+ isCompleteShortcutPage,SHORTCUT_PAGE_SIZE,} from '@/api/shortcuts'import { useAuthStore } from '@/auth/authStore'@@ -40,7 +40,7 @@ import {} from './analytics'import { cacheTargetPassed, hasGoodValue, isDue, READ_FLOOR_MS } from './freshness'import { type InsightTarget, insightItem, insightItemKey, insightQueryKey, pinTarget } from './items'-import { listRead, retryListRead } from './listReads'+import { listRead, readShortcuts, retryListRead } from './listReads'import { movedOrder, usePinPrefs, useProjectPinPrefs } from './pinPrefsStore'import { useDeviceRecent } from './recentStore'import { viewsQueue } from './refreshQueue'@@ -58,13 +58,6 @@ type ShortcutPage = PaginatedApi<FileSystemShortcutApi>const EMPTY_ROWS: FileSystemShortcutApi[] = []const EMPTY_RECENT: DeviceRecentEntry[] = []-function readShortcuts(signal?: AbortSignal, beforeRead?: () => void): Promise<ShortcutPage> {- return listRead('dashboards', signal, () => {- beforeRead?.()- return fetchShortcuts(signal)- })-}-function projectKey(scope: ProjectScope): string {return `${scope.host}|${scope.projectId}`}@@ -111,11 +104,10 @@ export function usePins({ refetchOnMount = false }: { refetchOnMount?: boolean }if (!page || demo || !prefsKey) {return}- const complete = !page.next && page.results.length < SHORTCUT_PAGE_SIZEusePinPrefs.getState().prune(prefsKey,page.results.map((row) => row.id),- complete+ isCompleteShortcutPage(page))}, [page, demo, prefsKey])diff --git a/products/mobile/src/features/views/viewRoutes.ts b/products/mobile/src/features/views/viewRoutes.tsindex 0e07cc34c5ce..483be3eee937 100644--- a/products/mobile/src/features/views/viewRoutes.ts+++ b/products/mobile/src/features/views/viewRoutes.ts@@ -3,7 +3,7 @@ import type { Href } from 'expo-router'import type { PinDisplayMode, ViewEntry, ViewRef } from '@/model/views'-const ENTRIES: readonly ViewEntry[] = ['pinned', 'recent', 'browse', 'search', 'deep_link', 'dashboard']+const ENTRIES: readonly ViewEntry[] = ['pinned', 'recent', 'browse', 'search', 'deep_link', 'dashboard', 'widget']const MODES: readonly PinDisplayMode[] = ['row', 'number', 'chart']/** How a view was opened. Sent with `mobile_view_opened`, so it travels in the route. */diff --git a/products/mobile/src/features/widgets/chartWidgetCatalog.test.ts b/products/mobile/src/features/widgets/chartWidgetCatalog.test.tsnew file mode 100644index 000000000000..c31b947b01cb--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetCatalog.test.ts@@ -0,0 +1,203 @@+import type { InsightApi } from '@/api/insights'+import { isCompleteShortcutPage, SHORTCUT_PAGE_SIZE } from '@/api/shortcuts'+import { insightSnapshot } from '@/model/adapters/insightSnapshot'+import type { PinDisplay, PinKind, PinView } from '@/model/views'++import { buildCatalog, type WidgetPinInsight } from './chartWidgetCatalog'++function pin(shortcutId: string, kind: PinKind, ref: string, name: string, display: PinDisplay = { mode: 'row' }) {+ return {+ kind,+ ref,+ href: null,+ name,+ shortcutId,+ shortcutIds: [shortcutId],+ serverOrder: 0,+ rank: null,+ display,+ } satisfies PinView+}++function trends(series: number, display: string, breakdown = false): unknown {+ return {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ series: Array.from({ length: series }, () => ({ kind: 'EventsNode', event: '$pageview' })),+ trendsFilter: { display },+ ...(breakdown ? { breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' } } : {}),+ },+ }+}++function insight(insightId: number, shortId: string, name: string, query: unknown): WidgetPinInsight {+ return { insightId, shortId, name, query }+}++describe('buildCatalog', () => {+ it('lists every pin in Views order with what the widget can show and why not', () => {+ const pins = [+ pin('s-signups', 'insight', 'sig1', 'Signups'),+ pin('s-kpis', 'dashboard', '12', 'Product KPIs', {+ mode: 'chart',+ tileId: 3,+ insightId: 456,+ insightShortId: 'dau1',+ }),+ pin('s-board', 'dashboard', '13', 'Growth'),+ pin('s-funnel', 'insight', 'fun1', 'Checkout funnel'),+ pin('s-sql', 'insight', 'sql1', 'Revenue by plan'),+ pin('s-browsers', 'insight', 'brw1', 'Browsers'),+ pin('s-steps', 'insight', 'stp1', 'Steps'),+ pin('s-unread', 'insight', 'new1', 'Fresh pin'),+ pin('s-gone', 'insight', 'old1', 'Removed'),+ ]+ const metadata = new Map<string, WidgetPinInsight | null>([+ ['sig1', insight(123, 'sig1', 'Signups', trends(1, 'ActionsLineGraph'))],+ ['dau1', insight(456, 'dau1', 'Daily active users', trends(1, 'ActionsBar'))],+ [+ 'fun1',+ insight(789, 'fun1', 'Checkout funnel', { kind: 'InsightVizNode', source: { kind: 'FunnelsQuery' } }),+ ],+ [+ 'sql1',+ insight(790, 'sql1', 'Revenue by plan', {+ kind: 'DataVisualizationNode',+ source: { kind: 'HogQLQuery' },+ }),+ ],+ ['brw1', insight(791, 'brw1', 'Browsers', trends(1, 'ActionsPie', true))],+ ['stp1', insight(792, 'stp1', 'Steps', trends(3, 'ActionsLineGraph'))],+ ['old1', null],+ ])++ const catalog = buildCatalog(pins, metadata, {+ host: 'https://us.posthog.com',+ projectId: 2,+ projectName: 'Example project',+ })++ expect(catalog).toMatchObject({ version: 1, host: 'https://us.posthog.com', projectId: 2 })+ expect(catalog.pins.map(({ displayMode: _mode, ...pin }) => pin)).toEqual([+ {+ id: 's-signups',+ kind: 'insight',+ name: 'Signups',+ subtitle: 'Insight',+ insightId: 123,+ shortId: 'sig1',+ dashboardId: null,+ eligible: true,+ number: true,+ chart: true,+ reason: null,+ },+ {+ id: 's-kpis',+ kind: 'dashboard',+ name: 'Product KPIs',+ subtitle: 'Product KPIs · Daily active users',+ insightId: 456,+ shortId: 'dau1',+ dashboardId: 12,+ eligible: true,+ number: true,+ chart: true,+ reason: null,+ },+ expect.objectContaining({+ id: 's-board',+ subtitle: 'Dashboard',+ insightId: null,+ shortId: null,+ dashboardId: 13,+ eligible: false,+ reason: 'Choose a tile in Views first',+ }),+ expect.objectContaining({ id: 's-funnel', eligible: true, reason: null }),+ expect.objectContaining({ id: 's-sql', eligible: true, reason: null }),+ expect.objectContaining({ id: 's-browsers', eligible: true, number: false, chart: false }),+ expect.objectContaining({ id: 's-steps', eligible: true, number: false, chart: true }),+ expect.objectContaining({+ id: 's-unread',+ insightId: null,+ eligible: false,+ reason: 'Open it in Views first',+ }),+ expect.objectContaining({ id: 's-gone', eligible: false, reason: "Couldn't find this insight" }),+ ])+ })+})++test('keeps dashboard tile values and display modes scoped to each pin', () => {+ const query = { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery' }, display: 'BoldNumber' }+ const pins = [10, 20].map((id) =>+ pin(`pin-${id}`, 'dashboard', String(id), `Dashboard ${id}`, { mode: 'number', insightId: 101 })+ )+ const metadata = new Map(+ pins.map((pin, index) => {+ const response: InsightApi = {+ id: 101,+ short_id: 'same-insight',+ name: 'Example',+ derived_name: null,+ query,+ result: [[index + 1]],+ columns: ['value'],+ types: [['value', 'UInt64']],+ last_refresh: null,+ cache_target_age: null,+ next_allowed_client_refresh: null,+ }+ return [+ pin.shortcutId,+ {+ insightId: 101,+ shortId: 'same-insight',+ name: 'Example',+ query,+ snapshot: insightSnapshot(response, undefined, { readAt: 1000, serverNow: 1000 }),+ },+ ] as const+ })+ )+ const catalog = buildCatalog(pins, metadata, { host: 'https://example.com', projectId: 1, projectName: 'Example' })+ expect(+ catalog.pins.map((pin) => [+ pin.dashboardId,+ pin.eligible,+ pin.displayMode,+ pin.shortId,+ pin.snapshot?.valueText,+ ])+ ).toEqual([+ [10, true, 'number', 'same-insight', '1'],+ [20, true, 'number', 'same-insight', '2'],+ ])+ const selected = buildCatalog(+ pins,+ metadata,+ { host: 'https://example.com', projectId: 1, projectName: 'Example' },+ new Set(['pin-10'])+ )+ expect(selected.pins.map((pin) => pin.snapshot?.valueText)).toEqual(['1', undefined])+ expect(selected.pins.map((pin) => pin.eligible)).toEqual([true, true])+})++test('accepts a full final pin page and keeps every visible pin', () => {+ const results = Array.from({ length: SHORTCUT_PAGE_SIZE }, (_, index) => ({+ id: `pin-${index}`,+ path: `Example ${index}`,+ type: 'insight',+ ref: `insight-${index}`,+ href: null,+ order: index,+ created_at: '',+ }))+ expect(isCompleteShortcutPage({ count: results.length, next: null, results })).toBe(true)+ expect(isCompleteShortcutPage({ count: results.length + 1, next: 'https://example.com/next', results })).toBe(false)+ const pins = results.map((result) => pin(result.id, 'insight', result.ref, result.path))+ const catalog = buildCatalog(pins, new Map(), { host: 'https://example.com', projectId: 1, projectName: 'Example' })+ expect(catalog.pins.map((item) => item.id)).toEqual(results.map((item) => item.id))+})diff --git a/products/mobile/src/features/widgets/chartWidgetCatalog.ts b/products/mobile/src/features/widgets/chartWidgetCatalog.tsnew file mode 100644index 000000000000..eb81b292330e--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetCatalog.ts@@ -0,0 +1,143 @@+import { SHORTCUT_PAGE_SIZE } from '@/api/shortcuts'+import { capabilitiesOf, queryKindOf } from '@/model/adapters/insightSnapshot'+import type { InsightSnapshot, PinKind, PinView } from '@/model/views'++import { type WidgetSnapshot, widgetSnapshot } from './chartWidgetSnapshot'++// The pin catalog the Chart home screen widget offers in its OS picker. The JSON shape is a contract with the native+// widgets: see modules/chart-widget/README.md before changing a field.++/** The OS pickers list at most this many pins, in Views order, and a sync reads metadata for at most this many. */+export const CATALOG_PIN_LIMIT = SHORTCUT_PAGE_SIZE++export interface WidgetPinInsight {+ insightId: number+ shortId: string+ name: string+ query: unknown+ snapshot?: InsightSnapshot+}++export interface WidgetCatalogPin {+ /** The pin's `shortcutId`, which the widget configuration stores. */+ id: string+ kind: PinKind+ name: string+ subtitle: string+ /** Null until the app has read the insight; the widget then reads by `shortId`. */+ insightId: number | null+ shortId: string | null+ /** The dashboard's numeric id, sent as `from_dashboard`. Null for an insight pin. */+ dashboardId: number | null+ eligible: boolean+ number: boolean+ chart: boolean+ reason: string | null+ displayMode: PinView['display']['mode']+ snapshot?: WidgetSnapshot+}++export interface WidgetCatalogProject {+ host: string+ projectId: number+ projectName: string+}++/** The catalog without `writtenAt`, so two syncs of the same pins compare equal. */+export interface WidgetCatalogBody extends WidgetCatalogProject {+ version: 1+ pins: WidgetCatalogPin[]+}++export const PICK_TILE_REASON = 'Choose a tile in Views first'+export const UNREAD_REASON = 'Open it in Views first'+export const MISSING_REASON = "Couldn't find this insight"++export function pinInsightShortId(pin: PinView): string | null {+ if (pin.kind === 'insight') {+ return pin.ref+ }+ return typeof pin.display.insightId === 'number'+ ? (pin.display.insightShortId ?? `#${pin.display.insightId}`)+ : null+}++function dashboardIdOf(pin: PinView): number | null {+ if (pin.kind !== 'dashboard') {+ return null+ }+ const id = Number(pin.ref)+ return Number.isInteger(id) ? id : null+}++type Eligibility = Pick<WidgetCatalogPin, 'eligible' | 'number' | 'chart' | 'reason'>++function ineligible(reason: string): Eligibility {+ return { eligible: false, number: false, chart: false, reason }+}++function eligibilityOf(insight: WidgetPinInsight): Eligibility {+ if (!queryKindOf(insight.query)) {+ return ineligible(UNREAD_REASON)+ }+ const capabilities = insight.snapshot?.capabilities ?? capabilitiesOf(insight.query)+ return { eligible: true, number: capabilities.number, chart: capabilities.chart, reason: null }+}++/** Keyed by pin id (or `short_id` for callers without a pin context). Null: the server no longer returns the insight. Missing: the app has not read it yet. */+export type WidgetPinMetadata = ReadonlyMap<string, WidgetPinInsight | null>++function catalogPin(pin: PinView, metadata: WidgetPinMetadata, includeSnapshot: boolean): WidgetCatalogPin {+ const shortId = pinInsightShortId(pin)+ const insight = metadata.has(pin.shortcutId)+ ? metadata.get(pin.shortcutId)+ : shortId+ ? metadata.get(shortId)+ : undefined+ const snapshot =+ includeSnapshot && insight?.snapshot ? widgetSnapshot(pin.shortcutId, insight.snapshot, pin.display.mode) : null+ const base = {+ id: pin.shortcutId,+ kind: pin.kind,+ name: pin.name,+ subtitle: pin.kind === 'insight' ? 'Insight' : insight ? `${pin.name} · ${insight.name}` : 'Dashboard',+ insightId: insight?.insightId ?? pin.display.insightId ?? null,+ shortId: insight?.shortId ?? shortId,+ dashboardId: dashboardIdOf(pin),+ displayMode: pin.display.mode,+ ...(snapshot ? { snapshot } : {}),+ }+ if (pin.kind === 'dashboard' && typeof pin.display.insightId !== 'number') {+ return { ...base, ...ineligible(PICK_TILE_REASON) }+ }+ if (insight === null) {+ return { ...base, ...ineligible(MISSING_REASON) }+ }+ if (!insight) {+ return { ...base, ...ineligible(UNREAD_REASON) }+ }+ return { ...base, ...eligibilityOf(insight) }+}++export function buildCatalog(+ pins: readonly PinView[],+ metadata: WidgetPinMetadata,+ project: WidgetCatalogProject,+ snapshotPinIds?: ReadonlySet<string>+): WidgetCatalogBody {+ return {+ version: 1,+ host: project.host,+ projectId: project.projectId,+ projectName: project.projectName,+ pins: pins+ .slice(0, CATALOG_PIN_LIMIT)+ .map((pin) => catalogPin(pin, metadata, snapshotPinIds?.has(pin.shortcutId) ?? true)),+ }+}++/** The JSON the native module stores: the body with `writtenAt` before `pins`, as the contract lists the fields. */+export function catalogJson(body: WidgetCatalogBody, writtenAt: number): string {+ const { pins, ...head } = body+ return JSON.stringify({ ...head, writtenAt, pins })+}diff --git a/products/mobile/src/features/widgets/chartWidgetSnapshot.test.ts b/products/mobile/src/features/widgets/chartWidgetSnapshot.test.tsnew file mode 100644index 000000000000..b9e84256e2e1--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetSnapshot.test.ts@@ -0,0 +1,90 @@+import type { InsightApi } from '@/api/insights'+import { insightSnapshot } from '@/model/adapters/insightSnapshot'++import fixtures from '../../../modules/chart-widget/fixtures/insights.json'+import { widgetSnapshot } from './chartWidgetSnapshot'++// The native parser checks consume the same invented responses, so numeric and display semantics stay aligned.+describe('widget snapshots use the Views representation', () => {+ test.each(fixtures)('$name', ({ response, expected }) => {+ const at = Date.parse('2026-11-02T12:00:00Z')+ const source = insightSnapshot(response as InsightApi, undefined, { readAt: at, serverNow: at })+ const snapshot = widgetSnapshot('pin-example', source, 'row')+ if ('appSnapshot' in expected && !expected.appSnapshot) {+ expect(snapshot).toBeNull()+ return+ }+ expect(snapshot).not.toBeNull()+ expect(snapshot?.display).toBe(expected.display)+ for (const field of ['chartValueText', 'axisLowText', 'axisHighText'] as const) {+ if (field in expected) expect(snapshot?.[field]).toBe(expected[field])+ }+ if ('intervalLabel' in expected) expect(snapshot?.intervalLabel).toBe(expected.intervalLabel)+ if ('valueText' in expected) expect(snapshot?.valueText).toBe(expected.valueText)+ if ('firstRowValue' in expected) expect(snapshot?.rows[0]?.value).toBe(expected.firstRowValue)+ if (typeof expected.rowCount === 'number') expect(snapshot?.rows).toHaveLength(expected.rowCount)+ if (typeof expected.seriesCount === 'number') expect(snapshot?.series).toHaveLength(expected.seriesCount)+ if ('firstAt' in expected) expect(snapshot?.series[0]?.points[0]?.at).toBe(expected.firstAt)+ if ('firstValue' in expected) expect(snapshot?.series[0]?.points[0]?.value).toBe(expected.firstValue)+ if ('lastIsGap' in expected) expect(snapshot?.series[0]?.points.at(-1)?.value).toBeNull()+ if ('lastValue' in expected) expect(snapshot?.series[0]?.points.at(-1)?.value).toBe(expected.lastValue)+ })+})++test('number mode keeps a single-series category insight as a number', () => {+ const response = fixtures.find((fixture) => fixture.name === 'Trends breakdown')?.response+ if (!response) throw new Error('Missing trends fixture')+ const source = insightSnapshot(+ {+ ...response,+ query: {+ kind: 'InsightVizNode',+ source: {+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', event: 'example' }],+ trendsFilter: { display: 'ActionsTable' },+ },+ },+ result: [{ label: 'Example', aggregated_value: 12 }],+ } as InsightApi,+ undefined,+ { readAt: 1000, serverNow: 1000 }+ )+ const snapshot = widgetSnapshot('example', source, 'number')+ expect(snapshot).toMatchObject({ display: 'number', valueText: '12', rows: [] })+})++test('formats only the compact rows retained by the widget', () => {+ const at = Date.now()+ const source = insightSnapshot(+ {+ id: 101,+ short_id: 'table1',+ name: 'Table',+ query: {+ kind: 'DataVisualizationNode',+ source: { kind: 'HogQLQuery', query: 'select example' },+ display: 'ActionsTable',+ },+ columns: ['label', 'value'],+ types: [+ ['label', 'String'],+ ['value', 'UInt64'],+ ],+ result: Array.from({ length: 50_000 }, (_, i) => [`Row ${i}`, i]),+ last_refresh: null,+ cache_target_age: null,+ next_allowed_client_refresh: null,+ } as InsightApi,+ undefined,+ { readAt: at, serverNow: at }+ )+ const row = source.sqlTable?.rows[12]+ if (!row) throw new Error('Missing SQL row')+ Object.defineProperty(row, 0, {+ get: () => {+ throw new Error('Formatted a discarded row')+ },+ })+ expect(widgetSnapshot('example', source, 'row')?.rows).toHaveLength(12)+})diff --git a/products/mobile/src/features/widgets/chartWidgetSnapshot.ts b/products/mobile/src/features/widgets/chartWidgetSnapshot.tsnew file mode 100644index 000000000000..2487e8b46501--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetSnapshot.ts@@ -0,0 +1,128 @@+import {+ deltaBasisText,+ deltaText,+ insightDisplay,+ pinRangeLabel,+ snapshotFormatter,+} from '@/features/views/snapshotChart'+import { formatInsightValue } from '@/model/adapters/insightFormatting'+import { sqlCellNumber } from '@/model/adapters/sqlVisualization'+import type { InsightSnapshot, PinDisplay } from '@/model/views'++export interface WidgetSnapshot {+ version: 1+ pinId: string+ fetchedAt: number+ lastRefreshAt: string | null+ rangeLabel: string | null+ intervalLabel: string+ chartValueText: string | null+ axisLowText: string | null+ axisHighText: string | null+ valueText: string | null+ deltaPercent: number | null+ deltaText: string | null+ deltaBasis: string | null+ series: { label: string; points: { at: string; value: number | null }[]; previous: boolean }[]+ chartKind: 'line' | 'bar'+ display: 'number' | 'chart' | 'rows'+ rows: { label: string; value: string }[]+}++export function widgetSnapshot(+ pinId: string,+ snapshot: InsightSnapshot,+ mode: PinDisplay['mode']+): WidgetSnapshot | null {+ if (!snapshot.dataReadAt || snapshot.refreshFailed) {+ return null+ }+ const format = snapshotFormatter(snapshot)+ const display = insightDisplay(snapshot)+ if (display === 'web') {+ return null+ }+ const rows: WidgetSnapshot['rows'] = []+ if (snapshot.funnel) {+ rows.push(+ ...snapshot.funnel.steps+ .slice(0, 12)+ .map((step) => ({ label: step.name, value: step.count.toLocaleString('en-US') }))+ )+ } else if (snapshot.retention) {+ for (const cohort of snapshot.retention.cohorts.slice(0, 12)) {+ rows.push({+ label: cohort.date.slice(0, 10),+ value: cohort.cells.map((cell) => `${Math.round(cell.percent)}%`).join(' · '),+ })+ }+ } else if (snapshot.ranking) {+ rows.push(...snapshot.ranking.rows.slice(0, 12).map((row) => ({ label: row.label, value: format(row.value) })))+ } else if (snapshot.sqlTable && display !== 'chart' && display !== 'number') {+ const { columns } = snapshot.sqlTable+ for (const row of snapshot.sqlTable.rows.slice(0, 12)) {+ rows.push({+ label: String(row[0] ?? '–'),+ value: row+ .slice(1)+ .map((cell, index) => {+ const column = columns[index + 1]+ const numeric = column?.isNumerical ? sqlCellNumber(cell) : undefined+ return numeric !== undefined && column?.format+ ? formatInsightValue(numeric, { ...snapshot.format, presentation: column.format })+ : String(cell ?? '–')+ })+ .join(' · '),+ })+ }+ }+ const plotted = snapshot.allSeries.slice(0, 10)+ const current = plotted.filter((series) => series.compare !== 'previous')+ const values = plotted+ .filter((series) => snapshot.chartKind !== 'bar' || series.compare !== 'previous')+ .flatMap((series) => series.points.slice(-60).map((point) => point.value))+ .filter(Number.isFinite)+ const latest =+ current.length === 1 ? current[0]?.points.slice(-60).findLast((point) => Number.isFinite(point.value)) : null+ const low = values.length ? Math.min(...values, ...(snapshot.chartKind === 'bar' ? [0] : [])) : null+ const high = values.length ? Math.max(...values, ...(snapshot.chartKind === 'bar' ? [0] : [])) : null+ return {+ chartValueText: latest ? format(latest.value) : null,+ axisLowText: low === null ? null : format(low),+ axisHighText: high === null ? null : format(high),+ version: 1,+ pinId,+ fetchedAt: snapshot.dataReadAt,+ lastRefreshAt: snapshot.lastRefreshAt,+ rangeLabel: pinRangeLabel(snapshot),+ intervalLabel: snapshot.interval,+ valueText:+ snapshot.funnel?.conversion !== null && snapshot.funnel?.conversion !== undefined+ ? `${Number(snapshot.funnel.conversion.toFixed(1))}%`+ : snapshot.value === null+ ? display === 'number' && snapshot.sqlTable?.rows[0]?.[0] != null+ ? String(snapshot.sqlTable.rows[0][0])+ : null+ : format(snapshot.value),+ deltaPercent: snapshot.delta?.unit === 'points' ? snapshot.delta.change : (snapshot.delta?.percent ?? null),+ deltaText: snapshot.delta ? deltaText(snapshot.delta, format) : null,+ deltaBasis: snapshot.delta ? deltaBasisText(snapshot.delta, snapshot.interval) : null,+ series: plotted.map((series) => ({+ label: series.label,+ points: series.points+ .slice(-60)+ .map((point) => ({ at: point.at, value: Number.isFinite(point.value) ? point.value : null })),+ previous: series.compare === 'previous',+ })),+ chartKind: snapshot.chartKind ?? 'line',+ display:+ mode === 'number' && snapshot.capabilities.number+ ? 'number'+ : rows.length > 0+ ? 'rows'+ : display === 'number'+ ? 'number'+ : 'chart',+ rows: mode === 'number' && snapshot.capabilities.number ? [] : rows.slice(0, 12),+ }+}diff --git a/products/mobile/src/features/widgets/chartWidgetSync.test.ts b/products/mobile/src/features/widgets/chartWidgetSync.test.tsnew file mode 100644index 000000000000..05331b299426--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetSync.test.ts@@ -0,0 +1,713 @@+import { QueryClient } from '@tanstack/react-query'+import { waitFor } from '@testing-library/react-native'+import { resetBudgets, trySpend } from '@/api/budget'+import { ApiError, apiJson } from '@/api/client'+import type { InsightApi, InsightBasicApi } from '@/api/insights'+import { queryClient } from '@/api/queryClient'+import type { PaginatedApi } from '@/api/reports'+import type { FileSystemShortcutApi } from '@/api/shortcuts'+import { addSessionEndTask, installAuthProvider, useAuthStore } from '@/auth/authStore'+import {+ type SessionIdentity,+ type SessionTokens,+ saveRefreshedTokens,+ sessionGeneration,+ setSessionTokens,+} from '@/auth/tokens'+import { useDemoMode } from '@/demo/demoMode'+import { usePinPrefs } from '@/features/views/pinPrefsStore'+import { viewsQueue } from '@/features/views/refreshQueue'+import { useScopeErrorStore } from '@/features/views/useViewsAccess'+import { useItemErrors, viewsKeys } from '@/features/views/viewsCache'+import { insightSnapshot } from '@/model/adapters/insightSnapshot'++import { clearWidgetState, startChartWidgetSync, syncWidgetCatalog, syncWidgetCredentials } from './chartWidgetSync'++const mockWidgetState = jest.fn()+const mockSetCredentials = jest.fn()+const mockClearCredentials = jest.fn()+const mockSetCatalog = jest.fn()+jest.mock('../../../modules/chart-widget', () => ({+ isAvailable: () => true,+ getWidgetState: () => mockWidgetState(),+ setCredentials: (credentials: unknown) => mockSetCredentials(credentials),+ clearCredentials: () => mockClearCredentials(),+ setCatalog: (json: string) => mockSetCatalog(json),+ clearCatalog: () => undefined,+ reloadWidgets: () => undefined,+}))+jest.mock('expo-secure-store', () => {+ const items = new Map<string, string>()+ return {+ getItemAsync: async (key: string) => items.get(key) ?? null,+ setItemAsync: async (key: string, value: string) => {+ items.set(key, value)+ },+ deleteItemAsync: async (key: string) => {+ items.delete(key)+ },+ }+})++const HOST = 'https://us.posthog.com'+const USER = { uuid: 'user-1', distinctId: 'user-1', email: '[email protected]', name: 'Ada' }+const KEY: SessionTokens = {+ kind: 'personal_api_key',+ accessToken: 'phx_example_key',+ refreshToken: null,+ expiresAt: null,+ grantedScopes: null,+ requestedScopes: null,+}+const OAUTH: SessionTokens = {+ kind: 'oauth',+ accessToken: 'example-access',+ refreshToken: 'example-refresh',+ expiresAt: Date.now() + 3_600_000,+ grantedScopes: null,+ requestedScopes: null,+}++function owner(tokens: SessionTokens): SessionIdentity {+ return {+ host: HOST,+ clientId: tokens.kind === 'oauth' ? 'example-client' : null,+ method: tokens.kind,+ userUuid: USER.uuid,+ }+}++function signIn(tokens: SessionTokens): void {+ setSessionTokens(tokens, owner(tokens))+ useAuthStore.setState({+ status: 'signed_in',+ signedIn: true,+ host: HOST,+ clientId: owner(tokens).clientId,+ method: tokens.kind,+ user: USER,+ projects: [{ id: 2, name: 'Example project', organizationId: 'org-1', organizationName: 'Example org' }],+ projectId: 2,+ projectName: 'Example project',+ })+}++// No garbage collection timer, so Jest can exit when the tests finish.+function testClient(): QueryClient {+ return new QueryClient({ defaultOptions: { queries: { gcTime: Number.POSITIVE_INFINITY } } })+}++function shortcut(id: string, ref: string, type = 'insight'): FileSystemShortcutApi {+ return { id, path: `Pin ${id}`, type, ref, href: null, order: 0, created_at: '2026-10-01T10:00:00Z' }+}++function json(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })+}++describe('chart widget sync', () => {+ let stop: (() => void) | null = null++ beforeAll(async () => {+ queryClient.setQueryDefaults(['views'], { gcTime: Number.POSITIVE_INFINITY })+ await useDemoMode.persist.rehydrate()+ })++ const fetchMock = jest.fn<Promise<Response>, [string, RequestInit | undefined]>()++ beforeEach(() => {+ // A sync without a cached pin list prefetches it, so no test may reach the network.+ viewsQueue.reset()+ useItemErrors.getState().reset()+ useScopeErrorStore.getState().clear()+ mockWidgetState.mockResolvedValue({+ installed: true,+ pinIds: ['s-signups', 's-kpis', 'a', 'b'],+ usesDefault: false,+ })+ resetBudgets()+ fetchMock.mockReset()+ fetchMock.mockResolvedValue(json(404, { detail: 'Not found.' }))+ globalThis.fetch = fetchMock as unknown as typeof fetch+ installAuthProvider()+ setSessionTokens(null)+ useAuthStore.setState({ status: 'signed_out', signedIn: false, user: null, projectId: null, projectName: null })+ useDemoMode.setState({ enabled: false })+ usePinPrefs.getState().clear()+ clearWidgetState()+ mockSetCredentials.mockClear()+ mockClearCredentials.mockClear()+ mockSetCatalog.mockClear()+ })++ afterEach(() => {+ stop?.()+ stop = null+ })++ it('writes the session once while it stays the same, and again when a refresh rotates the token', async () => {+ signIn(OAUTH)+ const client = testClient()+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)++ useAuthStore.setState({ accountLoading: true })+ syncWidgetCredentials('launch')++ expect(mockSetCredentials).toHaveBeenCalledTimes(1)++ await saveRefreshedTokens({ ...OAUTH, accessToken: 'example-rotated' }, sessionGeneration())++ expect(mockSetCredentials).toHaveBeenCalledTimes(2)+ expect(mockSetCredentials).toHaveBeenLastCalledWith({+ host: HOST,+ projectId: 2,+ projectName: 'Example project',+ accessToken: 'example-rotated',+ expiresAt: OAUTH.expiresAt,+ userUuid: USER.uuid,+ })+ })++ it('clears the widget when the session ends, and writes again when the same account signs in', async () => {+ signIn(KEY)+ const client = testClient()+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)++ await useAuthStore.getState().signOut()++ expect(mockClearCredentials).toHaveBeenCalled()+ expect(mockSetCredentials).toHaveBeenCalledTimes(1)++ signIn(KEY)++ await syncWidgetCatalog(client)+ expect(mockSetCredentials).toHaveBeenCalledTimes(2)+ })++ it.each([USER.uuid, 'user-2'])('keeps an ended widget session retired while signing in %s', async (userUuid) => {+ signIn(KEY)+ const client = queryClient+ client.clear()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ client.setQueryData(+ viewsKeys.insight(scope, 'sig1', null, '-'),+ insightSnapshot(+ {+ id: 123,+ short_id: 'sig1',+ name: 'Example',+ query: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery' }, display: 'BoldNumber' },+ result: [[42]],+ columns: ['value'],+ types: [['value', 'UInt64']],+ } as unknown as InsightApi,+ undefined,+ { readAt: Date.now(), serverNow: Date.now() }+ )+ )+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].snapshot.valueText).toBe('42')+ let finishCleanup!: () => void+ let reachedCleanup!: () => void+ const cleanupStarted = new Promise<void>((resolve) => {+ reachedCleanup = resolve+ })+ const removeCleanup = addSessionEndTask(+ () =>+ new Promise<void>((resolve) => {+ finishCleanup = resolve+ reachedCleanup()+ })+ )+ fetchMock.mockImplementation(async (url) =>+ url.endsWith('/api/users/@me/')+ ? json(200, {+ id: 2,+ uuid: userUuid,+ distinct_id: userUuid,+ email: '[email protected]',+ first_name: 'Example',+ last_name: '',+ team: { id: 2, name: 'Example project' },+ organization: { id: 'org-1', name: 'Example org', teams: [{ id: 2, name: 'Example project' }] },+ organizations: [],+ })+ : json(404, {})+ )+ const signingIn = useAuthStore.getState().signInWithPersonalApiKey(HOST, 'phx_example_replacement')+ try {+ await cleanupStarted+ mockSetCredentials.mockClear()+ mockSetCatalog.mockClear()+ // The account commit is paused, so cleanup subscribers and a foreground sync still see the old auth state.+ await syncWidgetCatalog(client)+ syncWidgetCredentials('launch')+ expect(mockSetCredentials).not.toHaveBeenCalled()+ expect(mockSetCatalog).not.toHaveBeenCalled()+ finishCleanup()+ await signingIn+ await syncWidgetCatalog(client)+ expect(mockSetCredentials).toHaveBeenLastCalledWith(+ expect.objectContaining({+ userUuid,+ accessToken: 'phx_example_replacement',+ projectId: 2,+ })+ )+ expect(mockSetCatalog).not.toHaveBeenCalled()+ } finally {+ finishCleanup()+ await signingIn+ removeCleanup()+ stop?.()+ stop = null+ await client.cancelQueries()+ client.clear()+ }+ })++ it('clears the widget when demo mode starts and writes nothing while it lasts, even with a session', async () => {+ signIn(OAUTH)+ const client = testClient()+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)++ useDemoMode.setState({ enabled: true })+ await saveRefreshedTokens({ ...OAUTH, accessToken: 'example-rotated' }, sessionGeneration())++ expect(mockClearCredentials).toHaveBeenCalled()+ expect(mockSetCredentials).toHaveBeenCalledTimes(1)+ })++ it('writes the catalog from a complete pin list only, so pins past a cut list never vanish from the widget', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ const metadata: InsightBasicApi = {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ derived_name: null,+ query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode' }] } },+ }+ client.setQueryData(viewsKeys.pinMetadata(scope, 'sig1'), metadata)+ client.setQueryData<PaginatedApi<FileSystemShortcutApi>>(viewsKeys.shortcuts(scope), {+ count: 101,+ next: `${HOST}/api/projects/2/file_system_shortcut/?offset=100`,+ results: [shortcut('s-signups', 'sig1')],+ })+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)++ expect(mockSetCatalog).not.toHaveBeenCalled()++ client.setQueryData<PaginatedApi<FileSystemShortcutApi>>(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ await syncWidgetCatalog(client)++ expect(mockSetCatalog).toHaveBeenCalledTimes(1)+ expect(JSON.parse(mockSetCatalog.mock.calls[0][0])).toMatchObject({+ projectId: 2,+ pins: [{ id: 's-signups', insightId: 123, eligible: true }],+ })+ })++ it('reads the pin list itself after a sign in, so the widget has a catalog before Views opens', async () => {+ fetchMock.mockImplementation(async (url) =>+ url.includes('/api/projects/2/file_system_shortcut/')+ ? json(200, { count: 1, next: null, results: [shortcut('s-kpis', '12', 'dashboard')] })+ : json(404, { detail: 'Not found.' })+ )+ const client = testClient()+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)++ signIn(KEY)++ await waitFor(() => expect(mockSetCatalog).toHaveBeenCalledTimes(1))+ expect(JSON.parse(mockSetCatalog.mock.calls[0][0])).toMatchObject({+ projectId: 2,+ pins: [{ id: 's-kpis', dashboardId: 12, eligible: false, reason: 'Choose a tile in Views first' }],+ })+ })+ it('offers an insight after opening it recovers a failed metadata read', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ stop = startChartWidgetSync(client)+ await waitFor(() => expect(mockSetCatalog).toHaveBeenCalled())+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].eligible).toBe(false)+ const response: InsightApi = {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ derived_name: null,+ query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode' }] } },+ result: [],+ last_refresh: null,+ cache_target_age: null,+ next_allowed_client_refresh: null,+ }+ client.setQueryData(+ viewsKeys.insight(scope, 'sig1', null, '-'),+ insightSnapshot(response, undefined, { readAt: Date.now(), serverNow: Date.now() })+ )+ await waitFor(() =>+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({+ eligible: true,+ insightId: 123,+ })+ )+ })++ it('uses the newer opened insight instead of an older unsupported metadata response', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ client.setQueryData(+ viewsKeys.pinMetadata(scope, 'sig1'),+ {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ query: { kind: 'FunnelsQuery' },+ },+ { updatedAt: Date.now() - 1000 }+ )+ const response: InsightApi = {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ derived_name: null,+ query: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode' }] },+ result: [],+ last_refresh: null,+ cache_target_age: null,+ next_allowed_client_refresh: null,+ }+ client.setQueryData(+ viewsKeys.insight(scope, 'sig1', null, '-'),+ insightSnapshot(response, undefined, { readAt: Date.now(), serverNow: Date.now() })+ )+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].eligible).toBe(true)+ })++ it.each([true, false])('selects a dashboard tile before selection, with a placed widget: %s', async (installed) => {+ signIn(KEY)+ mockWidgetState.mockResolvedValue({ installed, pinIds: [], usesDefault: false })+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-kpis', '12', 'dashboard')],+ })+ fetchMock.mockImplementation(async (url) =>+ url.includes('/dashboards/12/')+ ? json(200, {+ id: 12,+ name: 'Product KPIs',+ tiles: [+ {+ id: 3,+ insight: {+ id: 456,+ short_id: 'dau1',+ name: 'Daily active users',+ query: {+ kind: 'InsightVizNode',+ source: { kind: 'TrendsQuery', series: [{ kind: 'EventsNode' }] },+ },+ result: [],+ last_refresh: null,+ },+ },+ ],+ })+ : json(404, {})+ )+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({+ id: 's-kpis',+ dashboardId: 12,+ insightId: 456,+ shortId: 'dau1',+ eligible: true,+ })+ expect(usePinPrefs.getState().projects).toEqual({})+ })++ it('uses cached automatic dashboard choices while preserving an explicit choice', async () => {+ signIn(KEY)+ mockWidgetState.mockResolvedValue({ installed: false, pinIds: [], usesDefault: false })+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-kpis', '12', 'dashboard')],+ })+ for (const [shortId, id] of [+ ['auto', 456],+ ['manual', 789],+ ] as const) {+ client.setQueryData(viewsKeys.pinMetadata(scope, shortId), {+ id,+ short_id: shortId,+ query: { kind: 'TrendsQuery' },+ })+ }+ client.setQueryData(viewsKeys.smartPinDisplays(scope, 'views-list'), {+ 's-kpis': { mode: 'chart', tileId: 3, insightId: 456, insightShortId: 'auto' },+ })+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({+ eligible: true,+ insightId: 456,+ })+ usePinPrefs.getState().setDisplay(`${HOST}|2`, 's-kpis', {+ mode: 'chart',+ tileId: 4,+ insightId: 789,+ insightShortId: 'manual',+ })+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].insightId).toBe(789)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('publishes selected data and cache updates while another metadata read is pending', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 2,+ next: null,+ results: [shortcut('s-signups', 'sig1'), shortcut('unread', 'pending')],+ })+ const response = {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ query: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery' }, display: 'BoldNumber' },+ result: [[42]],+ columns: ['value'],+ types: [['value', 'UInt64']],+ } as unknown as InsightApi+ const update = (value: number): void => {+ client.setQueryData(+ viewsKeys.insight(scope, 'sig1', null, '-'),+ insightSnapshot({ ...response, result: [[value]] }, undefined, {+ readAt: Date.now(),+ serverNow: Date.now(),+ })+ )+ }+ update(42)+ let finishRead!: (value: Response) => void+ fetchMock.mockImplementation(+ () =>+ new Promise((resolve) => {+ finishRead = resolve+ })+ )+ stop = startChartWidgetSync(client)+ await waitFor(() => expect(fetchMock).toHaveBeenCalled())+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({+ snapshot: expect.objectContaining({ valueText: '42' }),+ })+ update(84)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].snapshot.valueText).toBe('84')+ client.setQueryData(+ viewsKeys.insight(scope, 'pending', null, '-'),+ insightSnapshot({ ...response, short_id: 'pending', result: [[88]] }, undefined, {+ readAt: Date.now() + 1,+ serverNow: Date.now(),+ })+ )+ finishRead(json(200, { id: 456, short_id: 'pending', query: { kind: 'unsupported' } }))+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[1].eligible).toBe(true)+ })++ it('prefetches the new project after the project-switch query reset', async () => {+ signIn(KEY)+ const client = testClient()+ client.setQueryData(viewsKeys.shortcuts({ host: HOST, projectId: 2 }), { count: 0, next: null, results: [] })+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)+ fetchMock.mockImplementation(async (url) =>+ url.includes('/api/projects/3/file_system_shortcut/')+ ? json(200, { count: 0, next: null, results: [] })+ : json(404, {})+ )+ useAuthStore.setState({ projectId: 3, projectName: 'Second project' })+ await client.resetQueries()+ await waitFor(() => expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').projectId).toBe(3))+ })+ it('does not keep the next project waiting on an old insight rate-limit pause', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ viewsQueue.notePause('insights', new ApiError(429, {}, new Headers({ 'Retry-After': '60' })))+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ client.setQueryData(viewsKeys.shortcuts({ host: HOST, projectId: 3 }), { count: 0, next: null, results: [] })+ stop = startChartWidgetSync(client)+ await Promise.resolve()+ expect(mockSetCatalog).not.toHaveBeenCalled()++ useAuthStore.setState({ projectId: 3, projectName: 'Second project' })+ await syncWidgetCatalog(client)++ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').projectId).toBe(3)+ expect(fetchMock).not.toHaveBeenCalled()+ })+ it('paces background metadata and leaves capacity for a foreground read', async () => {+ jest.useFakeTimers()+ try {+ signIn(KEY)+ const client = testClient()+ client.setQueryData(viewsKeys.shortcuts({ host: HOST, projectId: 2 }), {+ count: 2,+ next: null,+ results: [shortcut('a', 'a'), shortcut('b', 'b')],+ })+ for (let i = 0; i < 29; i++) expect(trySpend('insights')).toBe(true)+ fetchMock.mockImplementation(async () =>+ json(200, {+ id: 123,+ short_id: 'a',+ query: { kind: 'TrendsQuery', series: [] },+ result: [],+ })+ )+ stop = startChartWidgetSync(client)+ await jest.advanceTimersByTimeAsync(0)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ await apiJson('/api/projects/2/insights/foreground/')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(999)+ expect(fetchMock).toHaveBeenCalledTimes(2)+ await jest.advanceTimersByTimeAsync(1001)+ expect(fetchMock).toHaveBeenCalledTimes(3)+ await syncWidgetCatalog(client)+ } finally {+ stop?.()+ await jest.advanceTimersByTimeAsync(0)+ jest.useRealTimers()+ }+ })+ it('keeps picker metadata but sends no credentials, results or background reads without a placed widget', async () => {+ signIn(KEY)+ mockWidgetState.mockResolvedValue({ installed: false, pinIds: [], usesDefault: false })+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ client.setQueryData(viewsKeys.pinMetadata(scope, 'sig1'), {+ id: 123,+ short_id: 'sig1',+ query: { kind: 'TrendsQuery' },+ })+ client.setQueryData(+ viewsKeys.insight(scope, 'sig1', null, '-'),+ insightSnapshot(+ {+ id: 123,+ short_id: 'sig1',+ name: 'Example',+ query: { kind: 'DataVisualizationNode', source: { kind: 'HogQLQuery' }, display: 'BoldNumber' },+ result: [[42]],+ columns: ['value'],+ types: [['value', 'UInt64']],+ } as unknown as InsightApi,+ undefined,+ { readAt: Date.now(), serverNow: Date.now() }+ )+ )+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)+ expect(fetchMock).not.toHaveBeenCalled()+ expect(mockSetCredentials).not.toHaveBeenCalled()+ expect(mockClearCredentials).toHaveBeenCalled()+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({+ id: 's-signups',+ eligible: true,+ })+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].snapshot).toBeUndefined()+ })++ it('removes cached values from a pin that loses access', async () => {+ signIn(KEY)+ const client = testClient()+ const scope = { host: HOST, projectId: 2 }+ const key = viewsKeys.insight(scope, 'sig1', null, '-')+ client.setQueryData(viewsKeys.shortcuts(scope), {+ count: 1,+ next: null,+ results: [shortcut('s-signups', 'sig1')],+ })+ client.setQueryData(+ key,+ insightSnapshot(+ {+ id: 123,+ short_id: 'sig1',+ name: 'Signups',+ query: { kind: 'TrendsQuery' },+ result: [],+ } as unknown as InsightApi,+ undefined,+ { readAt: Date.now(), serverNow: Date.now() }+ )+ )+ stop = startChartWidgetSync(client)+ await syncWidgetCatalog(client)+ useItemErrors.getState().set(JSON.stringify(key), 'no_access')+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0]).toMatchObject({ eligible: false })+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').pins[0].snapshot).toBeUndefined()+ })+ it('lets a new project sync while the old placement check is pending', async () => {+ signIn(KEY)+ const client = testClient()+ for (const projectId of [2, 3]) {+ client.setQueryData(viewsKeys.shortcuts({ host: HOST, projectId }), { count: 0, next: null, results: [] })+ }+ mockWidgetState.mockImplementationOnce(() => new Promise(() => undefined))+ stop = startChartWidgetSync(client)+ await waitFor(() => expect(mockWidgetState).toHaveBeenCalled())+ useAuthStore.setState({ projectId: 3, projectName: 'Second project' })+ await syncWidgetCatalog(client)+ expect(JSON.parse(mockSetCatalog.mock.calls.at(-1)?.[0] ?? '{}').projectId).toBe(3)+ })+})diff --git a/products/mobile/src/features/widgets/chartWidgetSync.ts b/products/mobile/src/features/widgets/chartWidgetSync.tsnew file mode 100644index 000000000000..67c305dcf5ad--- /dev/null+++ b/products/mobile/src/features/widgets/chartWidgetSync.ts@@ -0,0 +1,670 @@+import type { QueryClient, QueryKey } from '@tanstack/react-query'+import { AppState } from 'react-native'++import { backgroundReadDelay } from '@/api/budget'+import { ApiError } from '@/api/client'+import { fetchInsightMetadata, type InsightBasicApi, readInsight as readInsightResponse } from '@/api/insights'+import type { PaginatedApi, ProjectScope } from '@/api/reports'+import { serverNow } from '@/api/serverClock'+import { type FileSystemShortcutApi, isCompleteShortcutPage } from '@/api/shortcuts'+import { type AuthState, addSessionEndTask, useAuthStore } from '@/auth/authStore'+import { getSessionIdentity, getSessionTokens, onSessionTokensChanged, sessionGeneration } from '@/auth/tokens'+import { useDemoMode } from '@/demo/demoMode'+import { READ_FLOOR_MS } from '@/features/views/freshness'+import { listRead, readShortcuts, retryListRead } from '@/features/views/listReads'+import { NO_PIN_PREFS, usePinPrefs } from '@/features/views/pinPrefsStore'+import { discoverPinDisplays } from '@/features/views/useSmartPinDisplays'+import { featureAccessFor, useScopeErrorStore } from '@/features/views/useViewsAccess'+import { overrideKey, useItemErrors, viewsKeys } from '@/features/views/viewsCache'+import { abortError } from '@/lib/abort'+import { track } from '@/lib/analytics'+import { sleep } from '@/lib/sleep'+import { insightSnapshot } from '@/model/adapters/insightSnapshot'+import { pinsFromShortcuts } from '@/model/adapters/viewPins'+import type { InsightSnapshot, PinDisplay, PinView } from '@/model/views'++// Local Expo modules have no node_modules entry, so they are imported by path.+import {+ clearCatalog,+ clearCredentials,+ getWidgetState,+ isAvailable,+ setCatalog,+ setCredentials,+ type WidgetCredentials,+ type WidgetState,+} from '../../../modules/chart-widget'++import {+ buildCatalog,+ CATALOG_PIN_LIMIT,+ catalogJson,+ pinInsightShortId,+ type WidgetPinInsight,+} from './chartWidgetCatalog'++export type CredentialsSyncReason = 'sign_in' | 'refresh' | 'project_switch' | 'launch'++type ShortcutPage = PaginatedApi<FileSystemShortcutApi>++interface WidgetSession {+ scope: ProjectScope+ projectName: string+ generation: number+}++// Every write makes the OS reload each placed widget, so the sync remembers what it wrote and skips an identical write.+let writtenCredentials: string | null = null+let writtenCatalog: string | null = null+// `{host}|{project id}` of the catalog the widget holds, so a project without one gets its pin list prefetched.+let writtenCatalogProject: string | null = null+// False until the first clear of this launch, so a signed-out launch clears once whatever an earlier session left.+let cleared = false+// A catalog sync that started before a clear must not write the catalog of the session that ended.+let clearEpoch = 0+// Account replacement runs cleanup before publishing its new tokens. Retired sessions must not start another sync.+let retiredGeneration: number | null = null+let catalogController: AbortController | null = null+let nextMetadataReadAt = 0+let widgetState: WidgetState | null = null+// Keyed by `{host}|{project id}|{short_id}`: insights the server no longer returns, so a sync does not ask again.+const missingInsights = new Set<string>()+const prefetchedPinLists = new Set<string>()++function dataMode(): 'loading' | 'demo' | 'live' {+ if (!useDemoMode.persist.hasHydrated()) {+ return 'loading'+ }+ return useDemoMode.getState().enabled ? 'demo' : 'live'+}++function currentSession(): WidgetSession | null {+ const state = useAuthStore.getState()+ const owner = getSessionIdentity()+ const generation = sessionGeneration()+ if (generation === retiredGeneration) return null+ if (state.status !== 'signed_in' || !state.host || !state.user || state.projectId === null) {+ return null+ }+ // A sign in stores the new tokens a moment before the store shows the new account. Until both agree, a write+ // would pair one account's token with another account's project.+ if (!getSessionTokens() || owner?.host !== state.host || owner.userUuid !== state.user.uuid) {+ return null+ }+ return {+ scope: { host: state.host.replace(/\/$/, ''), projectId: state.projectId },+ projectName: state.projectName ?? '',+ generation,+ }+}++function isSameSession(session: WidgetSession, other: WidgetSession | null): boolean {+ return (+ other !== null &&+ other.generation === session.generation &&+ other.scope.host === session.scope.host &&+ other.scope.projectId === session.scope.projectId+ )+}++function currentCredentials(): WidgetCredentials | null {+ const session = currentSession()+ const tokens = getSessionTokens()+ const userUuid = useAuthStore.getState().user?.uuid+ if (!session || !tokens || !userUuid) {+ return null+ }+ return {+ host: session.scope.host,+ projectId: session.scope.projectId,+ projectName: session.projectName,+ accessToken: tokens.accessToken,+ expiresAt: tokens.expiresAt,+ userUuid,+ }+}++/** Removes the session copy, the catalog and every cached chart, so placed widgets ask to sign in. */+export function clearWidgetState(): void {+ writtenCredentials = null+ writtenCatalog = null+ writtenCatalogProject = null+ clearEpoch += 1+ catalogController?.abort()+ widgetState = null+ nextMetadataReadAt = 0+ prefetchedPinLists.clear()+ missingInsights.clear()+ if (!isAvailable()) {+ return+ }+ // Each runs even when the other throws, because the token copy must go whatever happens to the catalog.+ // A failure leaves `cleared` false, so the next signed-out or demo sync tries again.+ let ok = true+ try {+ clearCredentials()+ } catch {+ ok = false+ }+ try {+ clearCatalog()+ } catch {+ ok = false+ }+ cleared = ok+}++export function syncWidgetCredentials(reason: CredentialsSyncReason): void {+ if (!isAvailable()) {+ return+ }+ const mode = dataMode()+ if (mode === 'loading') {+ return+ }+ if (mode === 'demo' || useAuthStore.getState().status === 'signed_out') {+ if (!cleared) {+ clearWidgetState()+ }+ return+ }+ if (!widgetState?.installed || !viewsAccessible()) {+ return+ }+ const credentials = currentCredentials()+ if (!credentials) {+ return+ }+ const json = JSON.stringify(credentials)+ if (json === writtenCredentials) {+ return+ }+ try {+ setCredentials(credentials)+ } catch {+ // Nothing is recorded, so the next token or project change writes again.+ return+ }+ writtenCredentials = json+ cleared = false+ track('mobile_widget_credentials_synced', { reason })+}++function prefsKey(scope: ProjectScope): string {+ return `${scope.host}|${scope.projectId}`+}++function missingKey(scope: ProjectScope, shortId: string): string {+ return `${prefsKey(scope)}|${shortId}`+}++function insightOf(basic: InsightBasicApi): WidgetPinInsight | null {+ if (basic.deleted) {+ return null+ }+ return {+ insightId: basic.id,+ shortId: basic.short_id,+ name: basic.name || basic.derived_name || 'Untitled',+ query: basic.query,+ }+}++function cachedInsight(+ client: QueryClient,+ scope: ProjectScope,+ pin: PinView,+ shortId: string+): WidgetPinInsight | null | undefined {+ const denied = Object.entries(useItemErrors.getState().errors).some(([key, error]) => {+ if (!['deleted', 'no_access', 'scope'].includes(error)) return false+ try {+ const queryKey: unknown[] = JSON.parse(key)+ return (+ queryKey[0] === 'views' &&+ queryKey[1] === scope.host &&+ queryKey[2] === scope.projectId &&+ ((queryKey[3] === 'insight' && queryKey[4] === shortId) ||+ (queryKey[3] === 'dashboard' && pin.kind === 'dashboard' && queryKey[4] === pin.ref))+ )+ } catch {+ return false+ }+ })+ if (denied) return null+ const basic = client.getQueryState<InsightBasicApi>(viewsKeys.pinMetadata(scope, shortId))+ const snapshot = client.getQueryState<InsightSnapshot>(+ viewsKeys.insight(scope, shortId, pin.kind === 'dashboard' ? pin.ref : null, overrideKey(null))+ )+ if (snapshot?.data && (!basic?.data || snapshot.data.readAt >= basic.dataUpdatedAt)) {+ return {+ insightId: snapshot.data.insightId,+ shortId: snapshot.data.shortId,+ name: snapshot.data.name,+ query: snapshot.data.query,+ snapshot: snapshot.data,+ }+ }+ if (basic?.data) {+ return insightOf(basic.data)+ }+ if (missingInsights.has(missingKey(scope, shortId))) {+ return null+ }+ return undefined+}++async function readInsight(+ client: QueryClient,+ scope: ProjectScope,+ pin: PinView,+ shortId: string,+ isCurrent: () => boolean,+ signal: AbortSignal,+ includeSnapshot: boolean+): Promise<WidgetPinInsight | null> {+ let startedAt = 0+ // `projectPath()` reads the project when the request starts, so the session must still be the one the pins are from.+ const response = await listRead('insights', signal, async () => {+ for (+ let delay = Math.max(nextMetadataReadAt - Date.now(), backgroundReadDelay('insights'));+ delay > 0;+ delay = Math.max(nextMetadataReadAt - Date.now(), backgroundReadDelay('insights'))+ ) {+ await sleep(delay, signal)+ }+ if (signal.aborted || !isCurrent()) {+ throw abortError()+ }+ startedAt = Date.now()+ nextMetadataReadAt = startedAt + 1000+ if (!includeSnapshot) return fetchInsightMetadata(shortId, signal)+ return readInsightResponse(+ { shortId, id: pin.display.insightId },+ {+ refresh: 'force_cache',+ signal,+ fromDashboard: pin.kind === 'dashboard' ? Number(pin.ref) : null,+ }+ )+ })+ if (signal.aborted || !isCurrent()) {+ throw abortError()+ }+ if (!response) {+ missingInsights.add(missingKey(scope, shortId))+ return null+ }+ // The shared cache entry, so the Views list's previews and later syncs read it without a request.+ const metadataKey = viewsKeys.pinMetadata(scope, shortId)+ if ((client.getQueryState(metadataKey)?.dataUpdatedAt ?? 0) <= startedAt) {+ client.setQueryData(metadataKey, response, { updatedAt: startedAt })+ }+ if (!('result' in response)) return insightOf(response)+ const snapshot = insightSnapshot(response, undefined, { readAt: startedAt, serverNow: serverNow() })+ const snapshotKey = viewsKeys.insight(scope, shortId, pin.kind === 'dashboard' ? pin.ref : null, overrideKey(null))+ if ((client.getQueryData<InsightSnapshot>(snapshotKey)?.readAt ?? 0) <= startedAt) {+ client.setQueryData(snapshotKey, snapshot)+ }+ const insight = insightOf(response)+ return insight ? { ...insight, snapshot } : null+}++async function loadPinMetadata(+ client: QueryClient,+ scope: ProjectScope,+ pins: readonly PinView[],+ isCurrent: () => boolean,+ signal: AbortSignal,+ selected: ReadonlySet<string>,+ publish: () => void+): Promise<void> {+ // Selected pins go first; a ready chart must not wait behind the rest of the picker.+ const prioritized = [+ ...pins.filter((pin) => selected.has(pin.shortcutId)),+ ...pins.filter((pin) => !selected.has(pin.shortcutId)),+ ]+ for (const pin of prioritized) {+ const shortId = pinInsightShortId(pin)+ if (!shortId || cachedInsight(client, scope, pin, shortId) !== undefined) continue+ try {+ await readInsight(client, scope, pin, shortId, isCurrent, signal, selected.has(pin.shortcutId))+ publish()+ } catch (error) {+ // A shared pause holds the remaining reads; an inaccessible insight concerns only its own pin.+ if (!(error instanceof ApiError) || error.status === 429 || error.status === 503) break+ }+ }+}++function viewsAccessible(): boolean {+ const access = featureAccessFor(+ {+ method: useAuthStore.getState().method,+ tokens: getSessionTokens(),+ reported: useScopeErrorStore.getState().reported.views,+ },+ 'views'+ )+ return access.state === 'ok'+}++/**+ * Reads the pin list the way `usePins` does, same key and lane, so the catalog exists before the Views tab opens. Once+ * per project per session: after a failure the catalog waits for the next Views read.+ */+function prefetchPinList(client: QueryClient, session: WidgetSession): void {+ const key = `${session.generation}|${prefsKey(session.scope)}`+ if (prefetchedPinLists.has(key) || !viewsAccessible()) {+ return+ }+ prefetchedPinLists.add(key)+ void client.prefetchQuery({+ queryKey: viewsKeys.shortcuts(session.scope),+ // `projectPath()` reads the project when the request starts, so a read for an earlier session must not start.+ queryFn: ({ signal }) =>+ readShortcuts(signal, () => {+ if (!isSameSession(session, currentSession())) {+ throw abortError()+ }+ }),+ staleTime: READ_FLOOR_MS,+ retry: retryListRead,+ })+}++function readWidgetState(signal: AbortSignal): Promise<WidgetState> {+ return new Promise((resolve, reject) => {+ if (signal.aborted) {+ reject(abortError())+ return+ }+ const onAbort = (): void => reject(abortError())+ signal.addEventListener('abort', onAbort, { once: true })+ void getWidgetState()+ .then(resolve, reject)+ .finally(() => signal.removeEventListener('abort', onAbort))+ })+}++function cachedPins(client: QueryClient, session: WidgetSession): PinView[] | null {+ const page = client.getQueryData<ShortcutPage>(viewsKeys.shortcuts(session.scope))+ // A partial page cannot replace the complete picker.+ if (!page || !isCompleteShortcutPage(page)) return null+ const prefs = usePinPrefs.getState().projects[prefsKey(session.scope)] ?? NO_PIN_PREFS+ const automatic: Record<string, PinDisplay> = {}+ const previews = client.getQueryCache().findAll({+ queryKey: ['views', session.scope.host, session.scope.projectId, 'smart_pin_displays'],+ })+ for (const query of previews.sort((a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt)) {+ Object.assign(automatic, query.state.data)+ }+ return pinsFromShortcuts(page.results, { ...prefs, display: { ...automatic, ...prefs.display } }).slice(+ 0,+ CATALOG_PIN_LIMIT+ )+}++function selectedPins(+ client: QueryClient,+ session: WidgetSession,+ pins: readonly PinView[],+ presence: WidgetState+): Set<string> {+ const selected = new Set(presence.pinIds)+ if (presence.installed && presence.usesDefault) {+ const defaultPin =+ pins.find((pin) => {+ const shortId = pinInsightShortId(pin)+ return shortId && cachedInsight(client, session.scope, pin, shortId)+ }) ?? pins[0]+ if (defaultPin) selected.add(defaultPin.shortcutId)+ }+ return selected+}++function publishCachedCatalog(client: QueryClient): PinView[] | null {+ const session = currentSession()+ if (!isAvailable() || dataMode() !== 'live' || !session || !widgetState || !viewsAccessible()) return null+ const pins = cachedPins(client, session)+ if (!pins) return null+ const metadata = new Map<string, WidgetPinInsight | null>()+ for (const pin of pins) {+ const shortId = pinInsightShortId(pin)+ const cached = shortId ? cachedInsight(client, session.scope, pin, shortId) : undefined+ if (cached !== undefined) metadata.set(pin.shortcutId, cached)+ }+ const body = buildCatalog(+ pins,+ metadata,+ { ...session.scope, projectName: session.projectName },+ selectedPins(client, session, pins, widgetState)+ )+ const key = JSON.stringify(body)+ if (key !== writtenCatalog) {+ setCatalog(catalogJson(body, Date.now()))+ writtenCatalog = key+ writtenCatalogProject = prefsKey(session.scope)+ cleared = false+ track('mobile_widget_catalog_synced', {+ pin_count: body.pins.length,+ eligible_count: body.pins.filter((pin) => pin.eligible).length,+ })+ }+ return pins+}++async function writeCatalog(client: QueryClient, signal: AbortSignal): Promise<void> {+ if (!isAvailable() || dataMode() !== 'live') return+ const session = currentSession()+ if (!session) return+ if (!viewsAccessible()) {+ clearWidgetState()+ return+ }+ const presence = await readWidgetState(signal)+ if (signal.aborted || !isSameSession(session, currentSession())) return+ widgetState = presence+ if (!presence.installed) {+ writtenCredentials = null+ clearCredentials()+ } else {+ syncWidgetCredentials('launch')+ }+ let pins = publishCachedCatalog(client)+ if (!pins) {+ if (writtenCatalogProject !== prefsKey(session.scope)) prefetchPinList(client, session)+ return+ }+ const epoch = clearEpoch+ const isCurrent = (): boolean => !signal.aborted && epoch === clearEpoch && isSameSession(session, currentSession())+ const publish = (): void => {+ if (isCurrent()) publishCachedCatalog(client)+ }+ const selected = selectedPins(client, session, pins, presence)+ await loadPinMetadata(+ client,+ session.scope,+ pins.filter((pin) => selected.has(pin.shortcutId)),+ isCurrent,+ signal,+ selected,+ publish+ )+ // Resolve picker choices even before a widget selects them. Reuse Views previews, and keep manual choices intact.+ const prefs = usePinPrefs.getState().projects[prefsKey(session.scope)] ?? NO_PIN_PREFS+ const dashboards = pins.filter(+ (pin) => pin.kind === 'dashboard' && !pinInsightShortId(pin) && !prefs.display[pin.shortcutId]+ )+ dashboards.sort((a, b) => Number(selected.has(b.shortcutId)) - Number(selected.has(a.shortcutId)))+ for (const pin of dashboards) {+ if (!isCurrent()) return+ try {+ const displays = await discoverPinDisplays(+ { client, scope: session.scope, demo: false },+ [pin],+ signal,+ `widget-catalog:${prefsKey(session.scope)}`+ )+ if (!isCurrent()) return+ if (Object.keys(displays).length > 0) {+ client.setQueryData<Record<string, PinDisplay>>(+ viewsKeys.smartPinDisplays(session.scope, 'widget-catalog'),+ (previous) => ({ ...previous, ...displays })+ )+ publish()+ }+ } catch {+ // Keep the remaining picker choices available when one dashboard cannot be read.+ }+ }+ if (!isCurrent()) return+ pins = cachedPins(client, session) ?? []+ await loadPinMetadata(+ client,+ session.scope,+ pins,+ isCurrent,+ signal,+ selectedPins(client, session, pins, presence),+ publish+ )+}++let catalogRun: Promise<void> | null = null+let catalogQueued = false++async function drainCatalog(client: QueryClient): Promise<void> {+ do {+ catalogQueued = false+ try {+ const controller = new AbortController()+ catalogController = controller+ await writeCatalog(client, controller.signal)+ } catch {+ // The widget keeps its last catalog; the next pin list read or display change tries again.+ }+ } while (catalogQueued)+}++export function syncWidgetCatalog(client: QueryClient): Promise<void> {+ // Cache successes publish even while an unrelated metadata request is waiting.+ try {+ publishCachedCatalog(client)+ } catch {+ /* The next sync retries a failed native write. */+ }+ catalogQueued = true+ if (!catalogRun) {+ // Auth subscribers run before selectProject resets queries. Start after that reset so it cannot cancel our prefetch.+ catalogRun = Promise.resolve()+ .then(() => drainCatalog(client))+ .finally(() => {+ catalogRun = null+ if (catalogQueued) {+ void syncWidgetCatalog(client)+ }+ })+ }+ return catalogRun+}++function credentialsReason(state: AuthState, previous: AuthState): CredentialsSyncReason | null {+ if (state.status !== previous.status) {+ return previous.status === 'loading' ? 'launch' : 'sign_in'+ }+ if (state.status !== 'signed_in') {+ return null+ }+ if (state.host !== previous.host || state.user?.uuid !== previous.user?.uuid) {+ return 'sign_in'+ }+ if (state.projectId !== previous.projectId || state.projectName !== previous.projectName) {+ return 'project_switch'+ }+ return null+}++function isCurrentCatalogData(queryKey: QueryKey): boolean {+ const scope = currentSession()?.scope+ return Boolean(+ scope &&+ queryKey[0] === 'views' &&+ queryKey[1] === scope.host &&+ queryKey[2] === scope.projectId &&+ ['shortcuts', 'pin_metadata', 'insight', 'dashboard', 'smart_pin_displays'].includes(String(queryKey[3]))+ )+}++export function startChartWidgetSync(client: QueryClient): () => void {+ const syncCatalog = (): void => {+ void syncWidgetCatalog(client)+ }+ const foreground = AppState.addEventListener('change', (state) => {+ if (state === 'active') {+ catalogController?.abort()+ syncCatalog()+ }+ })+ const stops = [+ addSessionEndTask(() => {+ retiredGeneration = sessionGeneration()+ clearWidgetState()+ }),+ () => foreground.remove(),+ useScopeErrorStore.subscribe(() => {+ catalogController?.abort()+ syncCatalog()+ }),+ useItemErrors.subscribe(syncCatalog),+ onSessionTokensChanged((change) => {+ syncWidgetCredentials(change === 'refresh' ? 'refresh' : 'sign_in')+ // The same account signing in again leaves the auth store's fields as they were, so only this sees it.+ if (change === 'session') {+ catalogController?.abort()+ syncCatalog()+ }+ }),+ useAuthStore.subscribe((state, previous) => {+ const reason = credentialsReason(state, previous)+ if (reason) {+ catalogController?.abort()+ syncWidgetCredentials(reason)+ syncCatalog()+ }+ }),+ useDemoMode.subscribe((state, previous) => {+ if (state.enabled !== previous.enabled) {+ syncWidgetCredentials('sign_in')+ syncCatalog()+ }+ }),+ useDemoMode.persist.onFinishHydration(() => {+ syncWidgetCredentials('launch')+ syncCatalog()+ }),+ usePinPrefs.subscribe((state, previous) => {+ if (state.projects !== previous.projects) {+ catalogController?.abort()+ syncCatalog()+ }+ }),+ client.getQueryCache().subscribe((event) => {+ if (+ event.type === 'updated' &&+ event.action.type === 'success' &&+ isCurrentCatalogData(event.query.queryKey)+ ) {+ syncCatalog()+ }+ }),+ ]+ syncWidgetCredentials('launch')+ syncCatalog()+ return () => {+ catalogController?.abort()+ for (const stop of stops) {+ stop()+ }+ }+}diff --git a/products/mobile/src/features/widgets/useChartWidgetSync.ts b/products/mobile/src/features/widgets/useChartWidgetSync.tsnew file mode 100644index 000000000000..928461dd7291--- /dev/null+++ b/products/mobile/src/features/widgets/useChartWidgetSync.ts@@ -0,0 +1,17 @@+import { useEffect } from 'react'++import { queryClient } from '@/api/queryClient'++// Local Expo modules have no node_modules entry, so they are imported by path.+import { isAvailable } from '../../../modules/chart-widget'++import { startChartWidgetSync } from './chartWidgetSync'++export function useChartWidgetSync(): void {+ useEffect(() => {+ if (!isAvailable()) {+ return+ }+ return startChartWidgetSync(queryClient)+ }, [])+}diff --git a/products/mobile/src/features/widgets/useWidgetOpenedEvent.ts b/products/mobile/src/features/widgets/useWidgetOpenedEvent.tsnew file mode 100644index 000000000000..41742beaf23c--- /dev/null+++ b/products/mobile/src/features/widgets/useWidgetOpenedEvent.ts@@ -0,0 +1,24 @@+import { useEffect, useRef } from 'react'++import { track } from '@/lib/analytics'+import type { PinKind, ViewEntry } from '@/model/views'++export type WidgetFamily = 'small' | 'medium' | 'large'++const FAMILIES: readonly WidgetFamily[] = ['small', 'medium', 'large']++export function widgetFamilyParam(value: string | string[] | undefined): WidgetFamily | null {+ const first = Array.isArray(value) ? value[0] : value+ return FAMILIES.find((family) => family === first) ?? null+}++export function useWidgetOpenedEvent(kind: PinKind, from: ViewEntry, family: WidgetFamily | null): void {+ const sent = useRef(false)+ useEffect(() => {+ if (sent.current || from !== 'widget') {+ return+ }+ sent.current = true+ track('mobile_widget_opened', { kind, family: family ?? undefined })+ }, [kind, from, family])+}diff --git a/products/mobile/src/lib/analytics.ts b/products/mobile/src/lib/analytics.tsindex 48af9de53a6a..119dcd75efc6 100644--- a/products/mobile/src/lib/analytics.ts+++ b/products/mobile/src/lib/analytics.ts@@ -115,6 +115,9 @@ export type AnalyticsEvent =| 'mobile_project_switched'| 'mobile_push_opened'| 'mobile_hedgehog_widget_synced'+ | 'mobile_widget_catalog_synced'+ | 'mobile_widget_credentials_synced'+ | 'mobile_widget_opened'| 'mobile_views_opened'| 'mobile_view_opened'| 'mobile_view_opened_in_web'diff --git a/products/mobile/src/model/views.ts b/products/mobile/src/model/views.tsindex ac3917e83e67..ab9f8ca66055 100644--- a/products/mobile/src/model/views.ts+++ b/products/mobile/src/model/views.ts@@ -9,8 +9,11 @@ export type PinKind = Extract<ViewKind, 'dashboard' | 'insight'>export type PinDisplayMode = 'row' | 'number' | 'chart'-/** Where a view was opened from, for `mobile_view_opened`. `dashboard`: a tile on a dashboard screen. */-export type ViewEntry = 'pinned' | 'recent' | 'browse' | 'search' | 'deep_link' | 'dashboard'+/**+ * Where a view was opened from, for `mobile_view_opened`. `dashboard`: a tile on a dashboard screen. `widget`: the+ * Chart home screen widget.+ */+export type ViewEntry = 'pinned' | 'recent' | 'browse' | 'search' | 'deep_link' | 'dashboard' | 'widget'export interface ViewRef {kind: ViewKinddiff --git a/products/mobile/targets/HedgehogWidget/ChartFetcher.swift b/products/mobile/targets/HedgehogWidget/ChartFetcher.swiftindex 2cd712ad6bbf..96997ca938ec 100644--- a/products/mobile/targets/HedgehogWidget/ChartFetcher.swift+++ b/products/mobile/targets/HedgehogWidget/ChartFetcher.swift@@ -115,7 +115,7 @@ struct ChartFetcher {if response["result"] == nil || response["result"] is NSNull {return .failed(.noResult)}- guard let snapshot = try? TrendsParser.snapshot(response: response, pinId: pin.id, now: now) else {+ guard let snapshot = try? InsightParser.snapshot(response: response, pin: pin, now: now) else {return .failed(.badData)}return .snapshot(snapshot)@@ -149,34 +149,44 @@ actor ChartRefresh {private struct RequestKey: Hashable {let pinId: Stringlet url: URL+ let displayMode: String?+ let accessToken: String+ let userUuid: String?}- private let store: UserDefaults?+ private let store: ChartStorage?+ private let currentCredentials: @Sendable () -> ChartCredentials?private let fetch: @Sendable (ChartPin, ChartCredentials, Date) async -> ChartFetchOutcomeprivate var running: [RequestKey: Task<Void, Never>] = [:]init(- store: UserDefaults? = ChartStore.defaults,+ store: ChartStorage? = ChartStore.storage,+ currentCredentials: @escaping @Sendable () -> ChartCredentials? = { ChartStore.credentials() },fetch: @escaping @Sendable (ChartPin, ChartCredentials, Date) async -> ChartFetchOutcome = {await ChartFetcher().fetch(pin: $0, credentials: $1, now: $2)}) {self.store = store+ self.currentCredentials = currentCredentialsself.fetch = fetch}- private static func key(for pin: ChartPin, host: String, projectId: Int) -> RequestKey? {- ChartFetcher.url(for: pin, host: host, projectId: projectId).map { RequestKey(pinId: pin.id, url: $0) }+ private static func key(for pin: ChartPin, credentials: ChartCredentials) -> RequestKey? {+ ChartFetcher.url(for: pin, host: credentials.host, projectId: credentials.projectId).map {+ RequestKey(pinId: pin.id, url: $0, displayMode: pin.displayMode,+ accessToken: credentials.accessToken, userUuid: credentials.userUuid)+ }}func refresh(_ pin: ChartPin, credentials: ChartCredentials, now: Date) async {- guard let key = Self.key(for: pin, host: credentials.host, projectId: credentials.projectId) else { return }+ guard let key = Self.key(for: pin, credentials: credentials) else { return }if let task = running[key] {await task.valuereturn}let task = Task {let outcome = await fetch(pin, credentials, now)+ guard currentCredentials() == credentials else { return }Self.record(outcome, pin: pin, credentials: credentials, at: now, store: store)}running[key] = task@@ -186,12 +196,12 @@ actor ChartRefresh {static func record(_ outcome: ChartFetchOutcome, pin: ChartPin, credentials: ChartCredentials, at now: Date,- store: UserDefaults? = ChartStore.defaults+ store: ChartStorage? = ChartStore.storage) {guard let catalog = ChartStore.catalog(store: store), catalog.belongs(to: credentials),let current = catalog.pin(id: pin.id), current.eligible,- let originalKey = key(for: pin, host: credentials.host, projectId: credentials.projectId),- key(for: current, host: catalog.host, projectId: catalog.projectId) == originalKey+ let originalKey = key(for: pin, credentials: credentials),+ key(for: current, credentials: credentials) == originalKeyelse {return}@@ -199,6 +209,11 @@ actor ChartRefresh {case .snapshot(let snapshot):ChartStore.save(snapshot, store: store)case .failed(let kind):+ let startedAt = (now.timeIntervalSince1970 * 1000).rounded()+ if let snapshot = ChartStore.snapshot(pinId: pin.id, store: store), snapshot.fetchedAt > startedAt { return }+ if kind == .auth || kind == .notFound {+ store?.removeObject(forKey: ChartStore.snapshotKey(pin.id))+ }ChartStore.save(ChartSnapshotError(at: (now.timeIntervalSince1970 * 1000).rounded(), kind: kind), pinId: pin.id, store: store)}}diff --git a/products/mobile/targets/HedgehogWidget/ChartModels.swift b/products/mobile/targets/HedgehogWidget/ChartModels.swiftindex f7034c595642..9d8aade19aac 100644--- a/products/mobile/targets/HedgehogWidget/ChartModels.swift+++ b/products/mobile/targets/HedgehogWidget/ChartModels.swift@@ -39,6 +39,8 @@ struct ChartPin: Codable, Equatable, Identifiable, Sendable {let chart: Boollet reason: String?+ var displayMode: String? = nil+var isDashboard: Bool { kind == "dashboard" }}@@ -88,6 +90,11 @@ struct ChartSeries: Codable, Equatable, Sendable {let previous: Bool}+struct ChartRow: Codable, Equatable, Sendable {+ let label: String+ let value: String+}+struct ChartSnapshot: Codable, Equatable, Sendable {static let supportedVersion = 1@@ -96,18 +103,23 @@ struct ChartSnapshot: Codable, Equatable, Sendable {/// Epoch ms of the read that wrote this snapshot.let fetchedAt: Doublelet lastRefreshAt: String?- let rangeLabel: String?+ var rangeLabel: String?/// The trends interval: "hour", "day", "week" or "month".- let intervalLabel: String+ var intervalLabel: String/// Nil when the insight has no single number, such as two series.- let valueText: String?+ var valueText: String?/// The signed change that sets the pill's direction: percent, or points for a percentage insight.let deltaPercent: Double?let deltaText: String?let deltaBasis: String?/// Up to five current series, then the previous-period series of those. Up to 60 points each.- let series: [ChartSeries]- let chartKind: ChartKind+ var series: [ChartSeries]+ var chartKind: ChartKind+ var chartValueText: String? = nil+ var axisLowText: String? = nil+ var axisHighText: String? = nil+ var display: String? = nil+ var rows: [ChartRow]? = nil}enum ChartErrorKind: String, Codable, Sendable {diff --git a/products/mobile/targets/HedgehogWidget/ChartState.swift b/products/mobile/targets/HedgehogWidget/ChartState.swiftindex 3f293cdf8d84..8c77b492b6f2 100644--- a/products/mobile/targets/HedgehogWidget/ChartState.swift+++ b/products/mobile/targets/HedgehogWidget/ChartState.swift@@ -88,10 +88,11 @@ enum ChartResolver {static let signedOut = ChartSlot.State.message("Sign in to see your pins", detail: "Open PostHog to sign in")static let reauthenticate = ChartSlot.State.message("Open PostHog to update", detail: nil)- static let notConfigured = ChartSlot.State.message("Choose a pin", detail: "Touch and hold to pick a pin from your Views tab")+ static let notConfigured = ChartSlot.State.message("No pinned views available", detail: "Open Views to pin an insight or choose a dashboard tile")static let noResult = ChartSlot.State.message("Open it in PostHog to load this insight", detail: nil)- static func selections(primary: ChartSelection?, extras: [ChartSelection], family: ChartFamily) -> (ChartSelection?, [ChartSelection]) {+ static func selections(primary: ChartSelection?, extras: [ChartSelection], family: ChartFamily, catalog: ChartCatalog? = nil) -> (ChartSelection?, [ChartSelection]) {+ let primary = primary ?? catalog?.pickerPins.first.map { ChartSelection(id: $0.id, name: $0.name) }guard family == .large else { return (primary, []) }var seen = Set(primary.map { [$0.id] } ?? [])var unique: [ChartSelection] = []@@ -147,6 +148,10 @@ enum ChartResolver {if credentials.isExpired(at: now) {return ChartContent(primary: ChartSlot(title: primary?.name, state: reauthenticate, link: links.root), extras: [])}+ let (primary, extras) = selections(+ primary: primary, extras: extras, family: links.family,+ catalog: store.catalog.flatMap { $0.belongs(to: credentials) ? $0 : nil }+ )return ChartContent(primary: slot(primary, credentials: credentials, store: store, links: links),extras: extras.map { slot($0, credentials: credentials, store: store, links: links) }@@ -157,6 +162,9 @@ enum ChartResolver {_ selection: ChartSelection?, credentials: ChartCredentials, store: ChartStoreState, links: ChartLinks) -> ChartSlot {guard let selection else {+ if store.catalog == nil {+ return ChartSlot(title: nil, state: .message("Open PostHog to load your pins", detail: nil), link: links.root)+ }return ChartSlot(title: nil, state: notConfigured, link: links.root)}// The app writes the catalog after its first pin list read.@@ -197,7 +205,7 @@ enum ChartResolver {// Opening the insight in the app computes it; the widget then reads the result.return ChartSlot(title: pin.name, state: failure(error.kind), link: error.kind == .noResult ? links.pin(pin) : links.root)}- return ChartSlot(title: pin.name, state: .loading, link: links.root)+ return ChartSlot(title: pin.name, state: .loading, link: links.pin(pin))}private static func otherProject(title: String, projectName: String?, links: ChartLinks) -> ChartSlot {diff --git a/products/mobile/targets/HedgehogWidget/ChartStorage.swift b/products/mobile/targets/HedgehogWidget/ChartStorage.swiftnew file mode 100644index 000000000000..9ab3ff06bcbe--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/ChartStorage.swift@@ -0,0 +1,69 @@+import CryptoKit+import Foundation+import Security++final class ChartStorage {+ private let defaults: UserDefaults+ private let key: SymmetricKey?++ init(defaults: UserDefaults, key: SymmetricKey? = ChartStorage.loadKey()) {+ self.defaults = defaults+ self.key = key+ for name in defaults.dictionaryRepresentation().keys where name.hasPrefix("chart.") {+ if defaults.object(forKey: name) is String {+ defaults.removeObject(forKey: name)+ }+ }+ }++ var keys: [String] { Array(defaults.dictionaryRepresentation().keys) }++ func string(forKey name: String) -> String? {+ guard let key, let data = defaults.data(forKey: name),+ let box = try? AES.GCM.SealedBox(combined: data),+ let clear = try? AES.GCM.open(box, using: key, authenticating: Data(name.utf8))+ else { return nil }+ return String(data: clear, encoding: .utf8)+ }++ func set(_ value: String, forKey name: String) {+ guard let key,+ let box = try? AES.GCM.seal(Data(value.utf8), using: key, authenticating: Data(name.utf8)),+ let data = box.combined+ else { return }+ defaults.set(data, forKey: name)+ }++ func removeObject(forKey name: String) {+ defaults.removeObject(forKey: name)+ }++ private static func loadKey() -> SymmetricKey? {+ let query: [String: Any] = [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: "com.posthog.code.mobile.chart-widget",+ kSecAttrAccount as String: "data-key",+ kSecAttrAccessGroup as String: AppGroup.suiteName,+ ]+ func read() -> SymmetricKey? {+ var result: CFTypeRef?+ let search = query.merging([+ kSecReturnData as String: true,+ kSecMatchLimit as String: kSecMatchLimitOne,+ ]) { _, new in new }+ guard SecItemCopyMatching(search as CFDictionary, &result) == errSecSuccess,+ let data = result as? Data, data.count == 32+ else { return nil }+ return SymmetricKey(data: data)+ }+ if let key = read() { return key }+ let key = SymmetricKey(size: .bits256)+ let item = query.merging([+ kSecValueData as String: key.withUnsafeBytes { Data($0) },+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,+ ]) { _, new in new }+ let status = SecItemAdd(item as CFDictionary, nil)+ if status == errSecDuplicateItem { return read() }+ return status == errSecSuccess ? key : nil+ }+}diff --git a/products/mobile/targets/HedgehogWidget/ChartStore.swift b/products/mobile/targets/HedgehogWidget/ChartStore.swiftindex 71b1b066bd83..a7a65d9fcc1c 100644--- a/products/mobile/targets/HedgehogWidget/ChartStore.swift+++ b/products/mobile/targets/HedgehogWidget/ChartStore.swift@@ -2,7 +2,7 @@ import Foundationimport Security/// The chart widget's side of the store it shares with the app (modules/chart-widget/ios/ChartWidgetModule.swift).-/// Foundation and Security only, so scripts/check_chart_widget.swift can compile it.+/// Foundation, CryptoKit and Security only, so scripts/check_chart_widget.swift can compile it.enum ChartStore {static let catalogKey = "chart.catalog"static let keychainService = "com.posthog.code.mobile.chart-widget"@@ -12,70 +12,103 @@ enum ChartStore {static func snapshotErrorKey(_ pinId: String) -> String { "chart.snapshotError.\(pinId)" }static func pinProjectKey(_ pinId: String) -> String { "chart.pinProject.\(pinId)" }- static var defaults: UserDefaults? { UserDefaults(suiteName: AppGroup.suiteName) }+ static var storage: ChartStorage? {+ UserDefaults(suiteName: AppGroup.suiteName).map { ChartStorage(defaults: $0) }+ }static func decodeCatalog(_ json: String) -> ChartCatalog? {guard let catalog = try? JSONDecoder().decode(ChartCatalog.self, from: Data(json.utf8)),- catalog.version == ChartCatalog.supportedVersion+ catalog.version == ChartCatalog.supportedVersionelse {return nil}return catalog}- static func catalog(store: UserDefaults? = ChartStore.defaults) -> ChartCatalog? {+ static func catalog(store: ChartStorage? = ChartStore.storage) -> ChartCatalog? {store?.string(forKey: catalogKey).flatMap(decodeCatalog)}- static func snapshot(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartSnapshot? {+ static func snapshot(pinId: String, store: ChartStorage? = ChartStore.storage) -> ChartSnapshot? {guard let json = store?.string(forKey: snapshotKey(pinId)),- let snapshot = try? JSONDecoder().decode(ChartSnapshot.self, from: Data(json.utf8)),- snapshot.version == ChartSnapshot.supportedVersion+ let snapshot = try? JSONDecoder().decode(ChartSnapshot.self, from: Data(json.utf8)),+ snapshot.version == ChartSnapshot.supportedVersionelse {return nil}return snapshot}- static func save(_ snapshot: ChartSnapshot, store: UserDefaults? = ChartStore.defaults) {- guard let data = try? JSONEncoder().encode(snapshot), let json = String(data: data, encoding: .utf8) else {+ static func save(_ snapshot: ChartSnapshot, store: ChartStorage? = ChartStore.storage) {+ guard+ (Self.snapshot(pinId: snapshot.pinId, store: store)?.fetchedAt ?? 0) <= snapshot.fetchedAt,+ let data = try? JSONEncoder().encode(snapshot), let json = String(data: data, encoding: .utf8)+ else {return}store?.set(json, forKey: snapshotKey(snapshot.pinId))store?.removeObject(forKey: snapshotErrorKey(snapshot.pinId))}- static func error(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartSnapshotError? {+ static func error(pinId: String, store: ChartStorage? = ChartStore.storage) -> ChartSnapshotError? {guard let json = store?.string(forKey: snapshotErrorKey(pinId)) else { return nil }return try? JSONDecoder().decode(ChartSnapshotError.self, from: Data(json.utf8))}- static func save(_ error: ChartSnapshotError, pinId: String, store: UserDefaults? = ChartStore.defaults) {- guard let data = try? JSONEncoder().encode(error), let json = String(data: data, encoding: .utf8) else {+ static func save(+ _ error: ChartSnapshotError, pinId: String, store: ChartStorage? = ChartStore.storage+ ) {+ guard let data = try? JSONEncoder().encode(error),+ let json = String(data: data, encoding: .utf8)+ else {return}store?.set(json, forKey: snapshotErrorKey(pinId))}- static func pinProject(pinId: String, store: UserDefaults? = ChartStore.defaults) -> ChartPinProject? {+ static func pinProject(pinId: String, store: ChartStorage? = ChartStore.storage)+ -> ChartPinProject?+ {guard let json = store?.string(forKey: pinProjectKey(pinId)) else { return nil }return try? JSONDecoder().decode(ChartPinProject.self, from: Data(json.utf8))}/// Writes only a changed marker, because every timeline call resolves its pins again.- static func save(_ project: ChartPinProject, pinId: String, store: UserDefaults? = ChartStore.defaults) {+ static func save(+ _ project: ChartPinProject, pinId: String, store: ChartStorage? = ChartStore.storage+ ) {guard pinProject(pinId: pinId, store: store) != project,- let data = try? JSONEncoder().encode(project), let json = String(data: data, encoding: .utf8)+ let data = try? JSONEncoder().encode(project), let json = String(data: data, encoding: .utf8)else {return}store?.set(json, forKey: pinProjectKey(pinId))}+ static func retainSnapshots(_ pinIds: Set<String>, store: ChartStorage? = ChartStore.storage) {+ for key in store?.keys ?? [] {+ for prefix in ["chart.snapshot.", "chart.snapshotError."] where key.hasPrefix(prefix) {+ if !pinIds.contains(String(key.dropFirst(prefix.count))) {+ store?.removeObject(forKey: key)+ }+ }+ }+ }++ static func clearCredentials() -> OSStatus {+ SecItemDelete(+ [+ kSecClass as String: kSecClassGenericPassword,+ kSecAttrService as String: keychainService,+ kSecAttrAccount as String: keychainAccount,+ kSecAttrAccessGroup as String: AppGroup.suiteName,+ ] as CFDictionary)+ }+static func decodeCredentials(_ data: Data) -> ChartCredentials? {guard let credentials = try? JSONDecoder().decode(ChartCredentials.self, from: data),- credentials.version == ChartCredentials.supportedVersion,- !credentials.accessToken.isEmpty+ credentials.version == ChartCredentials.supportedVersion,+ !credentials.accessToken.isEmptyelse {return nil}@@ -94,7 +127,9 @@ enum ChartStore {kSecMatchLimit as String: kSecMatchLimitOne,]var item: CFTypeRef?- guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess, let data = item as? Data else {+ guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,+ let data = item as? Data+ else {return nil}return decodeCredentials(data)diff --git a/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swift b/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swiftindex 6fbc75a0c2b8..630ccfa92c10 100644--- a/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swift+++ b/products/mobile/targets/HedgehogWidget/ChartTimelineProvider.swift@@ -18,17 +18,19 @@ struct ChartTimelineProvider: AppIntentTimelineProvider {func snapshot(for configuration: ChartWidgetIntent, in context: Context) async -> ChartEntry {let now = Date()- if context.isPreview {+ let store = Self.storeState()+ if context.isPreview && store.credentials == nil && store.catalog == nil {return ChartEntry(date: now, content: ChartSample.content(family: Self.family(context), now: now))}- return ChartEntry(date: now, content: Self.content(configuration, family: Self.family(context), store: Self.storeState(), now: now))+ return ChartEntry(date: now, content: Self.content(configuration, family: Self.family(context), store: store, now: now))}func timeline(for configuration: ChartWidgetIntent, in context: Context) async -> Timeline<ChartEntry> {+ _ = try? await chartWidgetState()let now = Date()let family = Self.family(context)- let (primary, extras) = Self.selections(configuration, family: family)let before = Self.storeState()+ let (primary, extras) = Self.selections(configuration, family: family, store: before)for marker in ChartResolver.pinProjects([primary].compactMap { $0 } + extras, catalog: before.catalog) {ChartStore.save(marker.project, pinId: marker.pinId)}@@ -53,14 +55,19 @@ struct ChartTimelineProvider: AppIntentTimelineProvider {}}- private static func selections(_ configuration: ChartWidgetIntent, family: ChartFamily) -> (ChartSelection?, [ChartSelection]) {+ private static func selections(_ configuration: ChartWidgetIntent, family: ChartFamily, store: ChartStoreState) -> (ChartSelection?, [ChartSelection]) {let primary = configuration.pin.map { ChartSelection(id: $0.id, name: $0.name) }let extras = (configuration.extraPins ?? []).map { ChartSelection(id: $0.id, name: $0.name) }- return ChartResolver.selections(primary: primary, extras: extras, family: family)+ return ChartResolver.selections(+ primary: primary, extras: extras, family: family,+ catalog: store.catalog.flatMap { catalog in+ store.credentials.map { catalog.belongs(to: $0) } == true ? catalog : nil+ }+ )}private static func storeState() -> ChartStoreState {- let defaults = ChartStore.defaults+ let defaults = ChartStore.storagereturn ChartStoreState(credentials: ChartStore.credentials(),catalog: ChartStore.catalog(store: defaults),@@ -71,7 +78,7 @@ struct ChartTimelineProvider: AppIntentTimelineProvider {}private static func content(_ configuration: ChartWidgetIntent, family: ChartFamily, store: ChartStoreState, now: Date) -> ChartContent {- let (primary, extras) = selections(configuration, family: family)+ let (primary, extras) = selections(configuration, family: family, store: store)let links = ChartLinks(scheme: ChartLinks.scheme(forAppId: AppGroup.appId), family: family)return ChartResolver.content(primary: primary, extras: extras, store: store, links: links, now: now)}diff --git a/products/mobile/targets/HedgehogWidget/ChartViews.swift b/products/mobile/targets/HedgehogWidget/ChartViews.swiftindex 981f66a545ac..5cec49965681 100644--- a/products/mobile/targets/HedgehogWidget/ChartViews.swift+++ b/products/mobile/targets/HedgehogWidget/ChartViews.swift@@ -78,9 +78,14 @@ struct ChartWidgetView: View {case .systemLarge, .systemExtraLarge:LargeChartLayout(content: entry.content, now: entry.date, colors: colors)default:- MediumChartLayout(content: entry.content, now: entry.date, colors: colors)+ Link(destination: entry.content.primary.link) {+ MediumChartLayout(content: entry.content, now: entry.date, colors: colors)+ .contentShape(Rectangle())+ }+ .buttonStyle(.plain)}}+ .privacySensitive().widgetURL(entry.content.primary.link)}}@@ -92,22 +97,8 @@ private struct SmallChartLayout: View {var body: some View {if let snapshot = slot.snapshot {- VStack(alignment: .leading, spacing: 2) {- PinTitle(text: slot.title, colors: colors)- if let value = snapshot.valueText {- ValueText(text: value, size: 26, colors: colors)- HStack(spacing: 4) {- DeltaPill(snapshot: snapshot, colors: colors)- RangeText(text: snapshot.rangeLabel, colors: colors)- }- } else {- RangeText(text: snapshot.rangeLabel, colors: colors)- }- PlotArea(snapshot: snapshot, window: PointWindow.compact, kind: .line, style: .sparkline, colors: colors)- .padding(.top, 4)- AgeLabel(dataDate: snapshot.dataDate, now: now, colors: colors)- }- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ ChartPanel(title: slot.title, snapshot: snapshot, window: PointWindow.compact,+ axisLabels: false, dataDate: snapshot.dataDate, now: now, colors: colors, compact: true)} else {StateView(slot: slot, colors: colors)}@@ -122,7 +113,7 @@ private struct MediumChartLayout: View {var body: some View {if let snapshot = content.primary.snapshot {ChartPanel(- title: content.primary.title, snapshot: snapshot, window: PointWindow.compact, axisLabels: false,+ title: content.primary.title, snapshot: snapshot, window: PointWindow.large, axisLabels: true,dataDate: content.oldestData, now: now, colors: colors)} else {@@ -138,14 +129,21 @@ private struct LargeChartLayout: View {var body: some View {VStack(alignment: .leading, spacing: 10) {- if let snapshot = content.primary.snapshot {- ChartPanel(- title: content.primary.title, snapshot: snapshot, window: PointWindow.large, axisLabels: true,- dataDate: content.oldestData, now: now, colors: colors- )- } else {- StateView(slot: content.primary, colors: colors)+ Link(destination: content.primary.link) {+ Group {+ if let snapshot = content.primary.snapshot {+ ChartPanel(+ title: content.primary.title, snapshot: snapshot, window: PointWindow.large, axisLabels: true,+ dataDate: content.oldestData, now: now, colors: colors+ )+ } else {+ StateView(slot: content.primary, colors: colors)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .contentShape(Rectangle())}+ .buttonStyle(.plain)if !content.extras.isEmpty {HStack(spacing: 8) {ForEach(Array(content.extras.enumerated()), id: \.offset) { _, slot in@@ -175,45 +173,101 @@ private struct ChartPanel: View {let dataDate: Date?let now: Datelet colors: ChartColors+ var compact = false++ private var isNumber: Bool {+ snapshot.display == "number" || (!snapshot.hasPoints && (snapshot.rows ?? []).isEmpty && snapshot.valueText != nil)+ }var body: some View {- VStack(alignment: .leading, spacing: 4) {- HStack(spacing: 5) {- Image(systemName: snapshot.chartKind == .bar ? "chart.bar.fill" : "chart.xyaxis.line")- .font(.system(size: 10, weight: .semibold))- .foregroundStyle(colors.secondary)+ VStack(alignment: .leading, spacing: compact ? 5 : 5) {+ HStack(spacing: 6) {+ Circle().fill(isNumber ? colors.orange : colors.seriesColor(0)).frame(width: 5, height: 5)PinTitle(text: title, colors: colors)+ if !isNumber && !compact && snapshot.hasPoints, let dataDate {+ Spacer(minLength: 4)+ AgeLabel(dataDate: dataDate, now: now, colors: colors, concise: true)+ }}- if let value = snapshot.valueText {- HStack(alignment: .firstTextBaseline, spacing: 6) {- ValueText(text: value, size: 26, colors: colors)- .layoutPriority(1)- DeltaPill(snapshot: snapshot, colors: colors)- if snapshot.pillText != nil, let basis = snapshot.deltaBasis {- Text(basis)- .font(.system(size: 10.5))- .foregroundStyle(colors.secondary)- .lineLimit(1)+ if isNumber {+ Spacer(minLength: 0)+ VStack(spacing: 6) {+ ValueText(text: snapshot.valueText ?? "–", size: compact ? 36 : axisLabels ? 48 : 44, colors: colors)+ .frame(maxWidth: .infinity)+ HStack(spacing: 6) {+ DeltaPill(snapshot: snapshot, colors: colors)+ RangeText(text: snapshot.deltaBasis ?? snapshot.rangeLabel, colors: colors)}+ .frame(maxWidth: .infinity)}- }- PlotArea(snapshot: snapshot, window: window, kind: snapshot.chartKind, style: .chart, colors: colors)- .padding(.top, 2)- if axisLabels, let ends = snapshot.axisLabels(limit: window) {- HStack {- Text(ends.0)- Spacer(minLength: 8)- Text(ends.1)+ .frame(maxWidth: .infinity)+ Spacer(minLength: 0)+ if snapshot.hasPoints {+ PlotArea(snapshot: snapshot, window: window, kind: .line, style: .sparkline, colors: colors)+ .frame(height: compact ? 20 : 26)+ }+ } else {+ if let value = snapshot.valueText ?? snapshot.chartValueText {+ HStack(alignment: .firstTextBaseline, spacing: 7) {+ ValueText(text: value, size: 28, colors: colors)+ .layoutPriority(1)+ if snapshot.valueText == nil {+ Text("Latest").font(.system(size: 10)).foregroundStyle(colors.secondary)+ }+ DeltaPill(snapshot: snapshot, colors: colors)+ Spacer(minLength: 0)+ }+ }+ if let rows = snapshot.rows, !rows.isEmpty {+ SnapshotRows(rows: rows, limit: compact ? 3 : axisLabels ? 8 : 4, colors: colors)+ } else if snapshot.hasPoints {+ if !compact && snapshot.series.filter({ !$0.previous }).count > 1 {+ HStack(spacing: 10) {+ ForEach(Array(snapshot.series.filter { !$0.previous }.prefix(3).enumerated()), id: \.offset) { index, series in+ HStack(spacing: 4) {+ Circle().fill(colors.seriesColor(index)).frame(width: 5, height: 5)+ Text(series.label).lineLimit(1)+ }+ }+ }+ .font(.system(size: 9.5)).foregroundStyle(colors.secondary)+ }+ VStack(spacing: 4) {+ HStack(spacing: 8) {+ PlotArea(snapshot: snapshot, window: window, kind: snapshot.chartKind,+ style: compact ? .sparkline : .chart, colors: colors)+ if !compact, let high = snapshot.axisHighText, let low = snapshot.axisLowText {+ VStack(alignment: .trailing) {+ Text(high)+ Spacer(minLength: 0)+ if low != high { Text(low) }+ }+ .font(.system(size: 9, weight: .medium)).monospacedDigit()+ .foregroundStyle(colors.tertiary).lineLimit(1).minimumScaleFactor(0.7)+ .frame(maxWidth: 62).padding(.vertical, 3)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ if !compact, let ends = snapshot.axisLabels(limit: window) {+ HStack {+ Text(ends.0)+ Spacer(minLength: 0)+ Text(ends.1)+ }+ .font(.system(size: 9)).foregroundStyle(colors.tertiary)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ } else {+ Text("No data for this range").font(.system(size: 11)).foregroundStyle(colors.secondary)+ .frame(maxWidth: .infinity, maxHeight: .infinity)}- .font(.system(size: 10.5))- .foregroundStyle(colors.tertiary)- .lineLimit(1)}- HStack(spacing: 8) {- RangeText(text: snapshot.rangeLabel, colors: colors)- Spacer(minLength: 0)- if let dataDate {- AgeLabel(dataDate: dataDate, now: now, colors: colors)+ if isNumber || compact || !snapshot.hasPoints {+ HStack(spacing: 6) {+ if !isNumber { RangeText(text: snapshot.rangeLabel, colors: colors) }+ Spacer(minLength: 0)+ if let dataDate { AgeLabel(dataDate: dataDate, now: now, colors: colors) }}}}@@ -235,7 +289,11 @@ private struct NumberTile: View {ValueText(text: snapshot.valueText ?? "", size: 20, colors: colors)DeltaPill(snapshot: snapshot, colors: colors)}- PlotArea(snapshot: snapshot, window: PointWindow.compact, kind: .line, style: .sparkline, colors: colors)+ if let rows = snapshot.rows, !rows.isEmpty {+ SnapshotRows(rows: rows, limit: 2, colors: colors)+ } else if snapshot.hasPoints {+ PlotArea(snapshot: snapshot, window: PointWindow.compact, kind: .line, style: .sparkline, colors: colors)+ }case .loading:Text("Loading…").font(.system(size: 12))@@ -261,6 +319,32 @@ private struct NumberTile: View {}}+private struct SnapshotRows: View {+ let rows: [ChartRow]+ let limit: Int+ let colors: ChartColors++ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ ForEach(Array(rows.prefix(limit).enumerated()), id: \.offset) { _, row in+ HStack(spacing: 8) {+ Text(row.label).foregroundStyle(colors.secondary)+ Spacer(minLength: 0)+ Text(row.value).monospacedDigit().foregroundStyle(colors.ink)+ }+ .font(.system(size: 11))+ .lineLimit(1)+ }+ if rows.count > limit {+ Text("+\(rows.count - limit) more in PostHog")+ .font(.system(size: 10)).foregroundStyle(colors.tertiary)+ }+ Spacer(minLength: 0)+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)+ }+}+private struct StateView: View {let slot: ChartSlotlet colors: ChartColors@@ -306,7 +390,7 @@ private struct PinTitle: View {var body: some View {Text(text ?? "").font(.system(size: 12, weight: .semibold))- .foregroundStyle(colors.ink)+ .foregroundStyle(colors.secondary).lineLimit(1)}}@@ -318,7 +402,8 @@ private struct ValueText: View {var body: some View {Text(text)- .font(.system(size: size, weight: .bold))+ .font(.system(size: size, weight: .bold, design: .rounded))+ .tracking(-0.7).monospacedDigit().foregroundStyle(colors.ink).lineLimit(1)@@ -344,10 +429,12 @@ private struct AgeLabel: View {let dataDate: Datelet now: Datelet colors: ChartColors+ var concise = falsevar body: some View {- Text(ChartAge.text(dataDate: dataDate, at: now))- .font(.system(size: 10.5))+ let text = ChartAge.text(dataDate: dataDate, at: now)+ Text(concise ? text.replacingOccurrences(of: "Updated ", with: "") : text)+ .font(.system(size: 9)).foregroundStyle(ChartAge.isStale(dataDate: dataDate, at: now) ? colors.orange : colors.tertiary).lineLimit(1)}@@ -437,7 +524,7 @@ private struct Plot: View {let scale = PlotScale(series: current + previous, kind: kind, style: style, size: proxy.size)ZStack {if style == .chart {- scale.gridPath().stroke(colors.hairline, lineWidth: 1)+ scale.gridPath().stroke(colors.hairline.opacity(0.7), style: StrokeStyle(lineWidth: 0.65, dash: [2, 3]))}if kind == .bar && style == .chart {bars(scale)@@ -453,7 +540,7 @@ private struct Plot: View {if fillsArea, current.count == 1, let only = current.first {scale.areaPath(only.points).fill(LinearGradient(- colors: [colors.seriesColor(0).opacity(0.18), colors.seriesColor(0).opacity(0.02)],+ colors: [colors.seriesColor(0).opacity(0.16), colors.seriesColor(0).opacity(0.01)],startPoint: .top, endPoint: .bottom))@@ -464,7 +551,12 @@ private struct Plot: View {}ForEach(Array(current.enumerated()), id: \.offset) { index, line inscale.linePath(line.points)- .stroke(tint ?? colors.seriesColor(index), style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))+ .stroke(tint ?? colors.seriesColor(index), style: StrokeStyle(lineWidth: 2.3, lineCap: .round, lineJoin: .round))+ if tint == nil, let last = line.points.enumerated().last(where: { $0.element.value != nil }), let value = last.element.value {+ Circle().fill(colors.surface).frame(width: 8, height: 8)+ .overlay(Circle().fill(colors.seriesColor(index)).padding(2))+ .position(x: scale.x(last.offset), y: scale.y(value))+ }}}@@ -472,8 +564,8 @@ private struct Plot: View {private func bars(_ scale: PlotScale) -> some View {if current.count == 1, let only = current.first {let last = only.points.count - 1- scale.barsPath(only.points, series: 0, of: 1) { $0 != last }.fill(colors.barNeutral)- scale.barsPath(only.points, series: 0, of: 1) { $0 == last }.fill(colors.ink)+ scale.barsPath(only.points, series: 0, of: 1) { $0 != last }.fill(colors.seriesColor(0).opacity(0.3))+ scale.barsPath(only.points, series: 0, of: 1) { $0 == last }.fill(colors.seriesColor(0))} else {ForEach(Array(current.enumerated()), id: \.offset) { index, bar inscale.barsPath(bar.points, series: index, of: current.count) { _ in true }.fill(colors.seriesColor(index))@@ -488,7 +580,7 @@ private struct PlotScale {let low: Doublelet high: Double/// Room above and below, so a 2pt stroke at the extremes is not clipped.- let inset: CGFloat = 2+ let inset: CGFloat = 4init(series: [ChartSeries], kind: ChartKind, style: PlotStyle, size: CGSize) {self.size = size@@ -510,7 +602,7 @@ private struct PlotScale {low = min(0, minimum)high = max(0, maximum)case (.chart, .line):- let pad = span > 0 ? span * 0.05 : (abs(maximum) * 0.1 == 0 ? 1 : abs(maximum) * 0.1)+ let pad = span > 0 ? 0 : (abs(maximum) * 0.1 == 0 ? 1 : abs(maximum) * 0.1)low = minimum - padhigh = maximum + padif minimum >= 0 && low < 0 {@@ -536,7 +628,7 @@ private struct PlotScale {func gridPath() -> Path {var path = Path()- for fraction in [0.0, 0.5, 1.0] {+ for fraction in [0.0, 1.0] {let y = inset + CGFloat(fraction) * max(0, size.height - inset * 2)path.move(to: CGPoint(x: 0, y: y))path.addLine(to: CGPoint(x: size.width, y: y))@@ -564,14 +656,25 @@ private struct PlotScale {}func areaPath(_ points: [ChartPoint]) -> Path {- let drawn = points.enumerated().compactMap { index, point in point.value.map { CGPoint(x: x(index), y: y($0)) } }- guard let first = drawn.first, let last = drawn.last, drawn.count > 1 else { return Path() }var path = Path()- path.move(to: first)- drawn.dropFirst().forEach { path.addLine(to: $0) }- path.addLine(to: CGPoint(x: last.x, y: size.height))- path.addLine(to: CGPoint(x: first.x, y: size.height))- path.closeSubpath()+ var first: CGPoint?+ var last: CGPoint?+ func closeRun() {+ guard let start = first, let end = last else { return }+ path.addLine(to: CGPoint(x: end.x, y: size.height))+ path.addLine(to: CGPoint(x: start.x, y: size.height))+ path.closeSubpath()+ first = nil+ last = nil+ }+ for (index, point) in points.enumerated() {+ guard let value = point.value else { closeRun(); continue }+ let location = CGPoint(x: x(index), y: y(value))+ if first == nil { first = location; path.move(to: location) }+ else { path.addLine(to: location) }+ last = location+ }+ closeRun()return path}diff --git a/products/mobile/targets/HedgehogWidget/ChartWidget.swift b/products/mobile/targets/HedgehogWidget/ChartWidget.swiftindex 483d293ae8e4..0e03766a6afa 100644--- a/products/mobile/targets/HedgehogWidget/ChartWidget.swift+++ b/products/mobile/targets/HedgehogWidget/ChartWidget.swift@@ -12,7 +12,7 @@ struct ChartWidget: Widget {}}.configurationDisplayName("Chart")- .description("A pinned insight from your Views tab, with its latest value.")+ .description("A pinned view, with its latest value or chart.").supportedFamilies([.systemSmall, .systemMedium, .systemLarge])}}diff --git a/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swift b/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swiftindex 94ebff374c3f..4fe9a21965c0 100644--- a/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swift+++ b/products/mobile/targets/HedgehogWidget/ChartWidgetIntent.swift@@ -2,6 +2,7 @@ import AppIntentsimport WidgetKit/// A pin from the catalog the app writes (`chart.catalog`). The configuration stores its id.+@available(iOS 17.0, *)struct PinEntity: AppEntity {static var typeDisplayRepresentation: TypeDisplayRepresentation { "Pin" }static var defaultQuery: PinQuery { PinQuery() }@@ -28,9 +29,12 @@ struct PinEntity: AppEntity {}}+@available(iOS 17.0, *)struct PinQuery: EntityStringQuery {private var pickerPins: [PinEntity] {- (ChartStore.catalog()?.pickerPins ?? []).map(PinEntity.init(pin:))+ (ChartStore.catalog()?.pins ?? []).map { pin in+ PinEntity(id: pin.id, name: pin.name, subtitle: pin.eligible ? pin.subtitle : pin.reason)+ }}/// A stored id that left the catalog still resolves, so the widget can say the pin is gone instead of@@ -38,13 +42,15 @@ struct PinQuery: EntityStringQuery {func entities(for identifiers: [PinEntity.ID]) async throws -> [PinEntity] {let catalog = ChartStore.catalog()return identifiers.map { id in- catalog?.pin(id: id).map(PinEntity.init(pin:)) ?? PinEntity(id: id, name: "This pin", subtitle: nil)+ catalog?.pin(id: id).map(PinEntity.init(pin:))+ ?? PinEntity(id: id, name: "This pin", subtitle: nil)}}func entities(matching string: String) async throws -> [PinEntity] {pickerPins.filter {- $0.name.localizedCaseInsensitiveContains(string) || ($0.subtitle?.localizedCaseInsensitiveContains(string) ?? false)+ string.isEmpty || $0.name.localizedCaseInsensitiveContains(string)+ || ($0.subtitle?.localizedCaseInsensitiveContains(string) ?? false)}}@@ -53,13 +59,16 @@ struct PinQuery: EntityStringQuery {}func defaultResult() async -> PinEntity? {- pickerPins.first+ ChartStore.catalog()?.pickerPins.first.map(PinEntity.init(pin:))}}+@available(iOS 17.0, *)struct ChartWidgetIntent: WidgetConfigurationIntent {static var title: LocalizedStringResource { "Chart" }- static var description: IntentDescription { "Choose a pin from your Views tab." }+ static var description: IntentDescription {+ "Shows your first pinned view. Choose a different pin below."+ }@Parameter(title: "Pin")var pin: PinEntity?@@ -81,3 +90,29 @@ struct ChartWidgetIntent: WidgetConfigurationIntent {}}}++@available(iOS 17.0, *)+func chartWidgetState() async throws -> [String: Any] {+ let infos = try await withCheckedThrowingContinuation {+ (continuation: CheckedContinuation<[WidgetInfo], Error>) in+ WidgetCenter.shared.getCurrentConfigurations { continuation.resume(with: $0) }+ }.filter { $0.kind == "ChartWidget" }+ var ids = Set<String>()+ var usesDefault = false+ if #available(iOS 17.0, *) {+ for info in infos {+ if let intent = info.widgetConfigurationIntent(of: ChartWidgetIntent.self) {+ if let pin = intent.pin { ids.insert(pin.id) } else { usesDefault = true }+ if info.family == .systemLarge {+ ids.formUnion((intent.extraPins ?? []).prefix(2).map(\.id))+ }+ } else {+ usesDefault = true+ }+ }+ }+ if usesDefault, let pin = ChartStore.catalog()?.pickerPins.first { ids.insert(pin.id) }+ ChartStore.retainSnapshots(ids)+ if infos.isEmpty { _ = ChartStore.clearCredentials() }+ return ["installed": !infos.isEmpty, "pinIds": Array(ids), "usesDefault": usesDefault]+}diff --git a/products/mobile/targets/HedgehogWidget/InsightParser.swift b/products/mobile/targets/HedgehogWidget/InsightParser.swiftnew file mode 100644index 000000000000..5f434f215c8d--- /dev/null+++ b/products/mobile/targets/HedgehogWidget/InsightParser.swift@@ -0,0 +1,388 @@+import CoreFoundation+import Foundation++/// Uses the same result shapes as the Views adapters; the widget never evaluates a query itself.+enum InsightParser {+ static func snapshot(response: JSONObject, pin: ChartPin, now: Date) throws -> ChartSnapshot {+ let query = response["query"] as? JSONObject ?? [:]+ let source = query["source"] as? JSONObject ?? query+ let kind = source["kind"] as? String+ if kind == "TrendsQuery" {+ var snapshot = try TrendsParser.snapshot(response: response, pinId: pin.id, now: now)+ chartLabels(&snapshot) {+ TrendsParser.formatValue($0, TrendsParser.valueFormat(source: source))+ }+ let display = TrendsParser.displayOf(query)+ if pin.displayMode == "number" && pin.number {+ snapshot.display = "number"+ return snapshot+ }+ if [+ "ActionsPie", "ActionsTable", "WorldMap", "ActionsBarValue", "ActionsDonut",+ "ActionsProportionBar",+ ].contains(display) {+ let entries = response["result"] as? [JSONObject] ?? []+ let format = TrendsParser.valueFormat(source: source)+ snapshot.rows = entries.filter {+ $0["compare_label"] as? String != "previous" && number($0["aggregated_value"]) != nil+ }.sorted {+ let leftOther = $0["breakdown_value"] as? String == "$$_posthog_breakdown_other_$$"+ let rightOther = $1["breakdown_value"] as? String == "$$_posthog_breakdown_other_$$"+ return leftOther != rightOther+ ? !leftOther+ : (number($0["aggregated_value"]) ?? 0) > (number($1["aggregated_value"]) ?? 0)+ }.prefix(12).map { entry in+ let value = number(entry["aggregated_value"])+ return ChartRow(+ label: entry["label"] as? String ?? "Value",+ value: value.map { TrendsParser.formatValue($0, format) } ?? "–")+ }+ snapshot.display = "rows"+ } else {+ snapshot.display =+ pin.displayMode == "number" || display == "BoldNumber" ? "number" : "chart"+ }+ return snapshot+ }+ var snapshot = ChartSnapshot(+ version: 1, pinId: pin.id, fetchedAt: now.timeIntervalSince1970 * 1000,+ lastRefreshAt: response["last_refresh"] as? String, rangeLabel: nil, intervalLabel: "day",+ valueText: nil, deltaPercent: nil, deltaText: nil, deltaBasis: nil, series: [],+ chartKind: .line,+ display: "rows", rows: []+ )+ if kind == "HogQLQuery" {+ sql(response: response, query: query, snapshot: &snapshot)+ } else if kind == "FunnelsQuery", let result = response["result"] as? [Any] {+ let groups =+ result.first is [Any]+ ? result.compactMap { $0 as? [JSONObject] } : [result.compactMap { $0 as? JSONObject }]+ let first = groups.first ?? []+ let layout = (source["funnelsFilter"] as? JSONObject)?["funnelVizType"] as? String+ if (layout != nil && layout != "steps")+ || first.contains(where: { number($0["count"]) == nil })+ {+ snapshot.rows = genericRows(result)+ return snapshot+ }+ let counts = first.indices.map { index in+ groups.reduce(0.0) { $0 + (index < $1.count ? number($1[index]["count"]) ?? 0 : 0) }+ }+ snapshot.rows = first.enumerated().prefix(12).map { index, step in+ ChartRow(+ label: step["custom_name"] as? String ?? step["name"] as? String ?? "Step \(index + 1)",+ value: text(counts[index]))+ }+ // Cohort breakdowns can overlap, so their counts must never be added together.+ let breakdown = source["breakdownFilter"] as? JSONObject+ if breakdown?["breakdown_type"] as? String == "cohort", groups.count > 1 {+ snapshot.rows = genericRows(result)+ } else if let entered = counts.first, let converted = counts.last, counts.count > 1,+ entered > 0+ {+ snapshot.valueText = "\(TrendsParser.number(converted / entered * 100, maxDigits: 1))%"+ snapshot.rangeLabel = "Overall conversion"+ }+ } else if kind == "RetentionQuery", let result = response["result"] as? [JSONObject] {+ let filter = source["retentionFilter"] as? JSONObject ?? [:]+ let aggregation = filter["aggregationType"] as? String+ let breakdown = source["breakdownFilter"] as? JSONObject ?? [:]+ if (aggregation != nil && aggregation != "count") || breakdown["breakdown"] is String+ || !(breakdown["breakdowns"] as? [Any] ?? []).isEmpty+ || result.contains(where: {+ $0["breakdown_value"] != nil && !($0["breakdown_value"] is NSNull)+ })+ {+ snapshot.rows = genericRows(result)+ return snapshot+ }+ let period = filter["period"] as? String ?? "Day"+ let previous = filter["retentionReference"] as? String == "previous"+ snapshot.rows = result.prefix(12).compactMap { row in+ guard let date = row["date"] as? String, let start = ChartDates.parse(date) else {+ return nil+ }+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ let cells = row["values"] as? [JSONObject] ?? []+ let counts = cells.map { number($0["count"]) ?? 0 }+ let available = counts.indices.prefix { index in+ let component: Calendar.Component =+ period == "Month" ? .month : period == "Hour" ? .hour : .day+ let amount = period == "Week" ? index * 7 : index+ return calendar.date(byAdding: component, value: amount, to: start).map { $0 <= now }+ ?? false+ }+ let values = available.map { index in+ let count = counts[index]+ let base = previous && index > 0 ? counts[index - 1] : counts.first ?? 0+ return "\(TrendsParser.number(base > 0 ? count / base * 100 : 0, maxDigits: 0))%"+ }+ return ChartRow(+ label: String((row["date"] as? String ?? "Cohort").prefix(10)),+ value: values.joined(separator: " · "))+ }+ snapshot.rangeLabel = "\(filter["period"] as? String ?? "Day") retention"+ } else {+ snapshot.rows = genericRows(response["result"])+ }+ return snapshot+ }++ private static func chartLabels(_ snapshot: inout ChartSnapshot, format: (Double) -> String) {+ let current = snapshot.series.filter { !$0.previous }+ let values = snapshot.series.filter { snapshot.chartKind != .bar || !$0.previous }.flatMap {+ $0.points.compactMap(\.value)+ }+ if current.count == 1, let value = current[0].points.last(where: { $0.value != nil })?.value {+ snapshot.chartValueText = format(value)+ }+ if let low = values.min(), let high = values.max() {+ snapshot.axisLowText = format(snapshot.chartKind == .bar ? min(0, low) : low)+ snapshot.axisHighText = format(snapshot.chartKind == .bar ? max(0, high) : high)+ }+ }++ static func number(_ value: Any?) -> Double? {+ if let value = value as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID() {+ return value.doubleValue.isFinite ? value.doubleValue : nil+ }+ if let value = value as? String, value.utf8.count <= 128,+ value.range(+ of: "^\\s*[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?\\s*$",+ options: .regularExpression) != nil,+ let parsed = Double(value.trimmingCharacters(in: .whitespacesAndNewlines)), parsed.isFinite+ {+ return parsed+ }+ return nil+ }++ private static func text(_ value: Any?) -> String {+ guard let value, !(value is NSNull) else { return "–" }+ if let value = value as? String { return value }+ if let value = value as? NSNumber, CFGetTypeID(value) == CFBooleanGetTypeID() {+ return value.boolValue ? "true" : "false"+ }+ if let value = number(value) { return TrendsParser.number(value, maxDigits: 3) }+ if let list = value as? [Any] {+ return list.prefix(6).map { text($0) }.joined(separator: " · ")+ }+ return String(describing: value)+ }++ private static func genericRows(_ result: Any?) -> [ChartRow] {+ if let rows = result as? [Any] {+ return rows.prefix(12).enumerated().flatMap { index, row -> [ChartRow] in+ if let row = row as? JSONObject {+ let label =+ row["label"] as? String ?? row["name"] as? String ?? row["date"] as? String+ ?? "Row \(index + 1)"+ if let value = row["count"] ?? row["aggregated_value"] ?? row["value"] ?? row["data"] {+ return [ChartRow(label: label, value: text(value))]+ }+ return row.keys.sorted().prefix(6).map { ChartRow(label: $0, value: text(row[$0])) }+ }+ if let row = row as? [Any] {+ return [ChartRow(label: "Row \(index + 1)", value: text(row))]+ }+ return [ChartRow(label: "Value \(index + 1)", value: text(row))]+ }+ }+ if let result = result as? JSONObject {+ return result.keys.sorted().prefix(12).map { ChartRow(label: $0, value: text(result[$0])) }+ }+ return result == nil ? [] : [ChartRow(label: "Value", value: text(result))]+ }++ private static func formatting(_ query: JSONObject, column: String, display: String)+ -> JSONObject+ {+ let table = (query["tableSettings"] as? JSONObject)?["columns"] as? [JSONObject] ?? []+ let axes = (query["chartSettings"] as? JSONObject)?["yAxis"] as? [JSONObject] ?? []+ func format(_ entries: [JSONObject]) -> JSONObject? {+ let settings = entries.first { $0["column"] as? String == column }?["settings"] as? JSONObject+ return settings?["formatting"] as? JSONObject+ }+ switch display {+ case "number": return format(table) ?? [:]+ case "table": return format(table) ?? format(axes) ?? [:]+ default: return format(axes) ?? format(table) ?? [:]+ }+ }++ private static func sqlText(_ cell: Any?, format: JSONObject) -> String {+ guard let value = number(cell) else { return text(cell) }+ let style = format["style"] as? String+ let digits = (format["decimalPlaces"] as? Int).map { min(100, max(0, $0)) }+ let scaled = style == "percent" ? value * 100 : value+ let formatted: String+ if style == "short" {+ formatted = TrendsParser.formatValue(value, TrendsParser.ValueFormat(style: "short"))+ } else if style == "number" || style == "percent" {+ formatted =+ TrendsParser.number(scaled, maxDigits: digits ?? 3, minDigits: digits ?? 0)+ + (style == "percent" ? "%" : "")+ } else if let digits {+ formatted = String(format: "%.*f", digits, scaled)+ } else {+ formatted =+ value.rounded() == value && abs(value) < 1e16+ ? String(format: "%.0f", value) : String(value)+ }+ return "\(format["prefix"] as? String ?? "")\(formatted)\(format["suffix"] as? String ?? "")"+ }++ private static func sqlDate(_ value: Any) -> String? {+ guard let value = value as? String,+ let regex = try? NSRegularExpression(+ pattern:+ "^(\\d{4}-\\d{2}-\\d{2})(?:[T ](\\d{2}:\\d{2})(:\\d{2})?(?:\\.\\d+)?)?(?:Z|[+-]\\d{2}(?::?\\d{2})?)?$"+ ),+ let match = regex.firstMatch(+ in: value.trimmingCharacters(in: .whitespacesAndNewlines),+ range: NSRange(+ value.trimmingCharacters(in: .whitespacesAndNewlines).startIndex...,+ in: value.trimmingCharacters(in: .whitespacesAndNewlines)))+ else { return nil }+ let text = value.trimmingCharacters(in: .whitespacesAndNewlines) as NSString+ let date = text.substring(with: match.range(at: 1))+ let at =+ match.range(at: 2).location == NSNotFound+ ? date+ : date + " " + text.substring(with: match.range(at: 2))+ + (match.range(at: 3).location == NSNotFound+ ? ":00" : text.substring(with: match.range(at: 3)))+ return ChartDates.parse(at) == nil ? nil : at+ }++ private static func sqlInterval(_ dates: [String]) -> String {+ let times = Array(Set(dates.compactMap { ChartDates.parse($0)?.timeIntervalSince1970 }))+ .sorted()+ let gaps = zip(times, times.dropFirst()).map { $1 - $0 }.sorted()+ guard !gaps.isEmpty else { return "day" }+ let median = gaps[gaps.count / 2]+ if median < 21 * 3600 { return "hour" }+ if median < 6 * 86400 { return "day" }+ return median < 28 * 86400 ? "week" : "month"+ }++ private static func sql(response: JSONObject, query: JSONObject, snapshot: inout ChartSnapshot) {+ let rows = response["result"] as? [[Any]] ?? []+ let columns = response["columns"] as? [String] ?? []+ let types = response["types"] as? [[Any]] ?? []+ let settings = query["chartSettings"] as? JSONObject ?? [:]+ func type(_ index: Int) -> String {+ index < types.count && types[index].count > 1 ? types[index][1] as? String ?? "" : ""+ }+ func scalar(_ index: Int) -> String {+ var value = type(index).trimmingCharacters(in: .whitespaces)+ while value.hasPrefix("Nullable(") || value.hasPrefix("LowCardinality("),+ value.hasSuffix(")"),+ let open = value.firstIndex(of: "(")+ {+ value = String(value[value.index(after: open)...].dropLast()).trimmingCharacters(+ in: .whitespaces)+ }+ return value+ }+ func date(_ index: Int) -> Bool { scalar(index).hasPrefix("Date") }+ func numeric(_ index: Int) -> Bool {+ ["Int", "UInt", "Float", "Decimal"].contains { scalar(index).hasPrefix($0) }+ }+ let ySettings = settings["yAxis"] as? [JSONObject] ?? []+ let savedX = (settings["xAxis"] as? JSONObject)?["column"] as? String+ let x =+ savedX.flatMap { columns.firstIndex(of: $0) } ?? columns.indices.first(where: date)+ ?? columns.indices.first { !numeric($0) }+ let namedY = ySettings.compactMap { entry in+ (entry["column"] as? String).flatMap { columns.firstIndex(of: $0) }+ }+ let breakdownName = settings["seriesBreakdownColumn"] as? String+ let breakdown = breakdownName.flatMap { columns.firstIndex(of: $0) }+ let y = (namedY.isEmpty ? columns.indices.filter(numeric) : namedY).filter {+ $0 != x && $0 != breakdown+ }+ var display = query["display"] as? String ?? "ActionsTable"+ if display == "Auto" {+ display =+ columns.count == 1 && numeric(0)+ ? "BoldNumber"+ : x.map(date) == true && !y.isEmpty && rows.count > 1 ? "ActionsLineGraph" : "ActionsTable"+ }+ if display == "BoldNumber" {+ snapshot.valueText = rows.first?.first.flatMap {+ $0 is NSNull+ ? nil+ : sqlText($0, format: formatting(query, column: columns.first ?? "", display: "number"))+ }+ snapshot.display = "number"+ return+ }+ let overTime = [+ "ActionsLineGraph", "ActionsLineGraphCumulative", "ActionsAreaGraph", "ActionsBar",+ "ActionsStackedBar", "ActionsUnstackedBar",+ ].contains(display)+ if overTime, let x, date(x), !y.isEmpty {+ var dates = Set<String>()+ var groups: [String] = []+ var sums: [String: [Int: [String: Double]]] = [:]+ for row in rows {+ guard row.count > x, let at = sqlDate(row[x]) else { continue }+ dates.insert(at)+ let group = breakdown.map { $0 < row.count ? text(row[$0]) : "–" } ?? ""+ if sums[group] == nil {+ guard groups.count < 5 else { continue }+ groups.append(group)+ sums[group] = [:]+ }+ for column in y.prefix(5) {+ guard column < row.count, let value = number(row[column]) else { continue }+ sums[group, default: [:]][column, default: [:]][at, default: 0] += value+ }+ }+ let axis = dates.sorted()+ snapshot.intervalLabel = sqlInterval(axis)+ let visibleDates = axis.suffix(60)+ snapshot.series = y.prefix(5).flatMap { column in groups.map { (column, $0) } }.prefix(5).map+ {+ column, group -> ChartSeries in+ let byDate = sums[group]?[column] ?? [:]+ var total =+ display == "ActionsLineGraphCumulative"+ ? axis.dropLast(visibleDates.count).reduce(0.0) { $0 + (byDate[$1] ?? 0) } : 0.0+ return ChartSeries(+ label: group.isEmpty ? columns[column] : "\(columns[column]) · \(group)",+ points: visibleDates.map { at in+ var value = byDate[at]+ if display == "ActionsLineGraphCumulative", let v = value {+ total += v+ value = total+ }+ return ChartPoint(at: at, value: value)+ }, previous: false)+ }+ snapshot.display = "chart"+ snapshot.chartKind =+ display.contains("Bar")+ || ((ySettings.first?["settings"] as? JSONObject)?["display"] as? JSONObject)?[+ "displayType"] as? String == "bar"+ ? .bar : .line+ chartLabels(&snapshot) {+ sqlText($0, format: formatting(query, column: columns[y[0]], display: "chart"))+ }+ snapshot.rows = []+ return+ }+ snapshot.rows = rows.prefix(12).map { row in+ let label = x.flatMap { $0 < row.count ? text(row[$0]) : nil } ?? "Value"+ let values = columns.indices.filter { $0 != x }.map { index in+ let cell = index < row.count ? row[index] : nil+ return numeric(index)+ ? sqlText(cell, format: formatting(query, column: columns[index], display: "table"))+ : text(cell)+ }+ return ChartRow(label: label, value: values.joined(separator: " · "))+ }+ }+}