From b81c6be39b6e421bd5d2f27c7b2cb1af0666cbb8 Mon Sep 17 00:00:00 2001 From: wusumac <736139669@qq.com> Date: Fri, 6 Nov 2026 19:18:09 +0800 Subject: [PATCH] feat(ios): add lock-screen Live Activities for running sessions Hub: - add encrypted Live Activity token registry, registration API, and update/end pushes over direct APNs - enable only for HAPI_IOS_PUSH=apns; relay reports remote:false - keep content-state encrypted with the per-install push key and a domain-separated AAD iOS: - add ActivityKit coordinator, HapiWidgets extension, lock-screen and Dynamic Island UI, encrypted content-state, deep links, and settings toggle - cap concurrent activities and reconcile across hub switches Docs/tests: - native contract, privacy, READMEs, localization catalogs - cross-language cipher fixture and hub/iOS unit tests via [HAPI](https://hapi.run) Co-Authored-By: HAPI Co-Authored-By: Claude Code --- .github/workflows/ios.yml | 3 +- docs/api/native-companion-contract.md | 104 +++++ docs/privacy.md | 2 + hub/README.md | 15 + .../liveActivityContract.test.ts | 89 ++++ hub/src/live-activity/liveActivityContract.ts | 74 +++ hub/src/live-activity/liveActivityControl.ts | 11 + .../liveActivityNotifier.test.ts | 357 +++++++++++++++ hub/src/live-activity/liveActivityNotifier.ts | 408 +++++++++++++++++ hub/src/live-activity/liveActivityPayload.ts | 203 +++++++++ .../liveActivityPushTransport.ts | 21 + hub/src/push-ios/apnsClient.test.ts | 57 +++ hub/src/push-ios/apnsClient.ts | 145 ++++-- hub/src/push-native/envelope.ts | 41 +- hub/src/startHub.ts | 12 +- hub/src/store/index.ts | 31 ++ hub/src/store/liveActivities.test.ts | 61 +++ hub/src/store/liveActivities.ts | 149 ++++++ hub/src/store/liveActivityStore.ts | 71 +++ hub/src/store/types.ts | 13 + hub/src/web/routes/devices.ts | 2 +- hub/src/web/routes/liveActivities.test.ts | 228 +++++++++ hub/src/web/routes/liveActivities.ts | 100 ++++ hub/src/web/server.ts | 12 +- ios/Hapi.xcodeproj/project.pbxproj | 157 +++++++ .../LiveActivityControlling.swift | 50 ++ .../LiveActivityCoordinator.swift | 431 ++++++++++++++++++ ios/Hapi/Features/Settings/SettingsView.swift | 18 +- ios/Hapi/HapiApp.swift | 17 +- ios/Hapi/Info.plist | 2 + ios/Hapi/Models/AppModel.swift | 38 ++ ios/Hapi/Resources/Localizable.xcstrings | 34 ++ ios/HapiTests/LiveActivityRoutingTests.swift | 41 ++ ios/HapiWidgets/HapiWidgets.entitlements | 10 + ios/HapiWidgets/HapiWidgetsBundle.swift | 9 + ios/HapiWidgets/Info.plist | 11 + ios/HapiWidgets/Localizable.xcstrings | 159 +++++++ .../SessionLiveActivityWidget.swift | 242 ++++++++++ ios/HapiWidgets/WidgetKeychain.swift | 30 ++ .../Endpoints/LiveActivityEndpoints.swift | 71 +++ .../Settings/LiveActivityPrefs.swift | 26 ++ .../HapiClient/Stores/SessionListStore.swift | 8 + .../LiveActivity/LiveActivityCipher.swift | 126 +++++ .../LiveActivityContentState.swift | 123 +++++ .../SessionActivityAttributes.swift | 28 ++ .../HapiProtocol/Models/SessionSummary.swift | 2 +- .../HapiProtocol/Pairing/SessionLink.swift | 99 ++++ .../LiveActivityEndpointTests.swift | 48 ++ .../Settings/LiveActivityPrefsTests.swift | 30 ++ .../Stores/SessionListStoreTests.swift | 15 + .../HapiProtocolTests/LiveActivityTests.swift | 198 ++++++++ .../HapiProtocolTests/SessionLinkTests.swift | 68 +++ ios/README.md | 49 +- shared/fixtures/README.md | 7 + .../live-activity/content-state-v1.json | 7 + 55 files changed, 4302 insertions(+), 61 deletions(-) create mode 100644 hub/src/live-activity/liveActivityContract.test.ts create mode 100644 hub/src/live-activity/liveActivityContract.ts create mode 100644 hub/src/live-activity/liveActivityControl.ts create mode 100644 hub/src/live-activity/liveActivityNotifier.test.ts create mode 100644 hub/src/live-activity/liveActivityNotifier.ts create mode 100644 hub/src/live-activity/liveActivityPayload.ts create mode 100644 hub/src/live-activity/liveActivityPushTransport.ts create mode 100644 hub/src/store/liveActivities.test.ts create mode 100644 hub/src/store/liveActivities.ts create mode 100644 hub/src/store/liveActivityStore.ts create mode 100644 hub/src/web/routes/liveActivities.test.ts create mode 100644 hub/src/web/routes/liveActivities.ts create mode 100644 ios/Hapi/Features/LiveActivity/LiveActivityControlling.swift create mode 100644 ios/Hapi/Features/LiveActivity/LiveActivityCoordinator.swift create mode 100644 ios/HapiTests/LiveActivityRoutingTests.swift create mode 100644 ios/HapiWidgets/HapiWidgets.entitlements create mode 100644 ios/HapiWidgets/HapiWidgetsBundle.swift create mode 100644 ios/HapiWidgets/Info.plist create mode 100644 ios/HapiWidgets/Localizable.xcstrings create mode 100644 ios/HapiWidgets/SessionLiveActivityWidget.swift create mode 100644 ios/HapiWidgets/WidgetKeychain.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LiveActivityEndpoints.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Settings/LiveActivityPrefs.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/LiveActivityCipher.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/LiveActivityContentState.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/SessionActivityAttributes.swift create mode 100644 ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/SessionLink.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/LiveActivityEndpointTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/Settings/LiveActivityPrefsTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiProtocolTests/LiveActivityTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiProtocolTests/SessionLinkTests.swift create mode 100644 shared/fixtures/live-activity/content-state-v1.json diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index c4211636..8cd77f7b 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -42,6 +42,7 @@ jobs: PYTHONDONTWRITEBYTECODE: '1' run: | python3 ios/scripts/localizations.py --check + python3 ios/scripts/localizations.py --check ios/HapiWidgets/Localizable.xcstrings python3 -m unittest discover -s ios/scripts/tests -p 'test_localizations.py' - name: Build Hapi app for iOS Simulator run: xcodebuild build -project ios/Hapi.xcodeproj -scheme Hapi -destination 'generic/platform=iOS Simulator' CODE_SIGNING_ALLOWED=NO @@ -69,4 +70,4 @@ jobs: -only-testing:HapiTests/SessionSplitPresentationTests -only-testing:HapiTests/TranscriptGeometryTests - name: Verify localization catalog was not rewritten - run: git diff --exit-code -- ios/Hapi/Resources/Localizable.xcstrings + run: git diff --exit-code -- ios/Hapi/Resources/Localizable.xcstrings ios/HapiWidgets/Localizable.xcstrings diff --git a/docs/api/native-companion-contract.md b/docs/api/native-companion-contract.md index 7293ed01..d3292ddf 100644 --- a/docs/api/native-companion-contract.md +++ b/docs/api/native-companion-contract.md @@ -307,6 +307,110 @@ Like the FCM channel, iOS push fires unconditionally for registered devices and suppresses the Web Push fallback for the namespace when a send succeeds (one OS notification, not two). +### Live Activities (iOS) + +The iOS app can surface each running session as a Live Activity on the Lock +Screen / Dynamic Island. Live Activities are **app-started**: the app creates +the activity (while it runs), registers the activity's APNs push token, and +the hub sends update/end pushes after the app is suspended or killed. The hub +does not start activities in contract version 1; a remotely-started activity +cannot be updated until the app runs and exposes its per-activity token. + +`POST /api/live-activities/register` + +```json +{ + "token": "", + "deviceId": "", + "sessionId": "", + "pushKey": "" +} +``` + +- `pushKey` is the same per-install E2E key used by alert pushes. The hub + stores it with the token and uses it to encrypt `content-state`. +- Upsert on `(namespace, deviceId, sessionId)`. One activity per session per + device; the app re-registers whenever `Activity.pushTokenUpdates` yields a + rotated token. +- Response: `{ "ok": true, "remote": true|false }`. `remote` is true only + when the hub is in direct-APNs mode (`HAPI_IOS_PUSH=apns`). Relay-mode hubs + return false and send no Live Activity pushes; the app ends activities on + background so a frozen Lock Screen card is not left behind. +- `DELETE /api/live-activities/register` accepts `{ "token": "..." }` or + `{ "deviceId": "...", "sessionId": "..." }`. + +The app deletes its rows when an activity ends, the user disables Live +Activities, or the hub changes. The hub prunes dead activity tokens on APNs +`410 Unregistered` / `400 BadDeviceToken` and rows older than 24 hours. It +never prunes the normal alert device row from a Live Activity token failure. + +#### APNs request + +Direct APNs only (the relay contract does not carry liveactivity pushes in +version 1): + +``` +apns-topic: .push-type.liveactivity +apns-push-type: liveactivity +apns-priority: 5 (counter-only) | 10 (status change / end) +apns-expiration: (seconds; do not use 0) +``` + +```json +{ + "aps": { + "timestamp": 1700000060, + "event": "update", + "content-state": { "v": 1, "e": "" }, + "stale-date": 1700000180 + } +} +``` + +End pushes use `"event": "end"` and `"dismissal-date": ` instead of +`stale-date`. `timestamp`, `stale-date` and `dismissal-date` are epoch +seconds. + +#### Encrypted content-state + +`content-state` is an AES-256-GCM envelope over canonical JSON of: + +```json +{ + "status": "needsApproval", + "title": "Claude - hapi", + "project": "hapi", + "startedAt": 1700000000000, + "updatedAt": 1700000060000, + "pendingCount": 1, + "todoCompleted": 2, + "todoTotal": 5, + "backgroundTaskCount": 0 +} +``` + +- Envelope: `base64(nonce[12] || ciphertext || tag[16])`, key = the device's + 32-byte `pushKey`, AAD = ASCII `hapi-live-activity-v1` (domain-separated + from the alert channel's `hapi-push-v1`). +- The widget extension decrypts with the shared Keychain access group + `$(AppIdentifierPrefix)run.hapi.companion.push`; Apple and any proxy see + ciphertext plus routing metadata only. +- `startedAt`/`updatedAt` are epoch ms. `title` follows the web/iOS title + order (name → summary → promptTitle → path basename → id prefix). The hub + caps title/project to 120 code points and strips newlines. +- Golden vector: + [`shared/fixtures/live-activity/content-state-v1.json`](https://github.com/tiann/hapi/blob/main/shared/fixtures/live-activity/content-state-v1.json). + +Status precedence mirrors the app's session row: pending requests win over +working; input-only → `needsInput`, permission-only → `needsApproval`, mixed → +`needsAttention`; otherwise `working`. A session is tracked while +`active && (thinking || pendingRequestsCount > 0)`. End pushes carry `done` +(or `error` for an `error` end reason). + +The app starts at most five activities (attention states first) and only for +the **active** hub; switching hubs ends the previous hub's activities. Local +activities require iOS 17.0; iPadOS Live Activities require 17.2+. + --- ## Environment (hub operator) diff --git a/docs/privacy.md b/docs/privacy.md index cf4eaa42..06ff9ffd 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -44,6 +44,8 @@ Your hub, coding agents, plugins, and command-line tools may send prompts, sourc **iOS:** notifications are end-to-end encrypted. Your hub encrypts the content with a key that exists only on your device and your hub; Apple's push service and the HAPI push relay carry ciphertext and routing metadata only, and cannot read the notification content. Self-hosters using a separately signed app build with matching APNs credentials can bypass the relay; a different developer account's credentials alone cannot send notifications to an app signed by the official publisher. +iOS Live Activities use the same per-install key and an independently domain-separated AES-256-GCM envelope (`hapi-live-activity-v1`). Apple and any relay receive ciphertext plus routing metadata only; the widget extension decrypts on device with the shared Keychain key. Live Activity remote updates currently require a hub in direct-APNs mode; relay-mode hubs report `remote:false` and the app ends the activity on background rather than showing a frozen card. + ### HAPI native push relay The default hub configuration uses the official relay at `https://push.hapi.run` for iOS push and for Android push when no private Firebase credentials are configured. This service is separate from the optional network tunnel enabled by `hapi hub --relay`. Encryption protects notification content, **not all metadata**: diff --git a/hub/README.md b/hub/README.md index bd2acd50..65f6e5a8 100644 --- a/hub/README.md +++ b/hub/README.md @@ -74,6 +74,13 @@ Official native apps register their encryption keys automatically; no push provider setup is needed on a fresh hub. See the [native companion push contract](../docs/api/native-companion-contract.md). +With `HAPI_IOS_PUSH=apns`, the hub also sends iOS Live Activity update/end +pushes (`.push-type.liveactivity`) to activity tokens the app +registered. Relay mode advertises `remote:false` on Live Activity +registration and sends none; the app ends activities on background. Live +Activity `content-state` is encrypted with the same per-install key and a +separate AAD (`hapi-live-activity-v1`). + ## Running Binary (single executable): @@ -211,6 +218,13 @@ copy or snapshot files during archive. Native Android/iOS registration uses `POST`/`DELETE /api/devices/register` (`src/web/routes/devices.ts`); see the [native push contract](../docs/api/native-companion-contract.md). +### Live Activities (`src/web/routes/liveActivities.ts`) + +- `POST /api/live-activities/register` - Upsert an iOS Live Activity's APNs token (with the device push key). +- `DELETE /api/live-activities/register` - Remove by activity token or device/session. + +Direct-APNs hubs also push encrypted `liveactivity` update/end payloads; relay-mode hubs return `remote:false`. See the [Live Activities contract](../docs/api/native-companion-contract.md#live-activities-ios). + ### CLI (`src/web/routes/cli.ts`) - `POST /cli/sessions` - Create/load session. @@ -331,6 +345,7 @@ Maintenance scripts (run with the hub stopped before swapping files): - `src/sse/` - Server-Sent Events. - `src/config/` - Configuration loading and generation. - `src/notifications/` - Push and Telegram notifications. +- `src/live-activity/` - iOS Live Activity registration/state contract and encrypted update/end pushes. - `src/visibility/` - Client visibility tracking. ## Security model diff --git a/hub/src/live-activity/liveActivityContract.test.ts b/hub/src/live-activity/liveActivityContract.test.ts new file mode 100644 index 00000000..9bbd0159 --- /dev/null +++ b/hub/src/live-activity/liveActivityContract.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'bun:test' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' + +import { + LIVE_ACTIVITY_AAD, + encryptLiveActivityState, + decryptLiveActivityState, + type LiveActivityContentState +} from './liveActivityContract' +import { decryptEnvelope, encryptEnvelopeWithAad } from '../push-native/envelope' + +type Fixture = { + key_hex: string + nonce_hex: string + aad: string + plaintext: string + envelope_b64: string +} + +const FIXTURE_STATE: LiveActivityContentState = { + status: 'needsApproval', + title: 'Claude - hapi', + project: 'hapi', + startedAt: 1_700_000_000_000, + updatedAt: 1_700_000_060_000, + pendingCount: 1, + todoCompleted: 2, + todoTotal: 5, + backgroundTaskCount: 0 +} + +function loadFixture(): Fixture { + const path = join(import.meta.dir, '../../../shared/fixtures/live-activity/content-state-v1.json') + return JSON.parse(readFileSync(path, 'utf8')) as Fixture +} + +describe('Live Activity content-state v1', () => { + it('reproduces the cross-language golden vector', () => { + const fixture = loadFixture() + expect(fixture.aad).toBe(LIVE_ACTIVITY_AAD) + const encrypted = encryptLiveActivityState( + FIXTURE_STATE, + Buffer.from(fixture.key_hex, 'hex'), + Buffer.from(fixture.nonce_hex, 'hex') + ) + expect(encrypted.v).toBe(1) + expect(encrypted.e).toBe(fixture.envelope_b64) + }) + + it('decrypts the vector back to the fixture state', () => { + const fixture = loadFixture() + const state = decryptLiveActivityState( + { v: 1, e: fixture.envelope_b64 }, + Buffer.from(fixture.key_hex, 'hex') + ) + expect(state).toEqual(FIXTURE_STATE) + }) + + it('uses canonical JSON for the plaintext', () => { + const fixture = loadFixture() + const plaintext = JSON.stringify(JSON.parse(fixture.plaintext)) + // The fixture plaintext is already canonical: sorted keys, no spaces. + expect(plaintext).toBe(fixture.plaintext) + }) + + it('is domain-separated from the notification envelope AAD', () => { + const fixture = loadFixture() + const key = Buffer.from(fixture.key_hex, 'hex') + // A Live Activity envelope must not open with the notification AAD. + expect(() => decryptEnvelope(key, fixture.envelope_b64)).toThrow() + // And a notification envelope must not open as a Live Activity state. + const notificationEnvelope = encryptEnvelopeWithAad( + key, + fixture.plaintext, + 'hapi-push-v1', + Buffer.from(fixture.nonce_hex, 'hex') + ) + expect(() => decryptLiveActivityState({ v: 1, e: notificationEnvelope }, key)).toThrow() + }) + + it('rejects an unknown state version', () => { + const fixture = loadFixture() + expect(() => decryptLiveActivityState( + { v: 2, e: fixture.envelope_b64 }, + Buffer.from(fixture.key_hex, 'hex') + )).toThrow('unsupported Live Activity state version') + }) +}) diff --git a/hub/src/live-activity/liveActivityContract.ts b/hub/src/live-activity/liveActivityContract.ts new file mode 100644 index 00000000..5c4bdbd2 --- /dev/null +++ b/hub/src/live-activity/liveActivityContract.ts @@ -0,0 +1,74 @@ +import { + canonicalJson, + decryptEnvelopeWithAad, + encryptEnvelopeWithAad +} from '../push-native/envelope' + +/** + * Live Activity `content-state` contract (iOS ActivityKit). + * + * The APNs payload carries an AES-256-GCM envelope whose plaintext is the + * canonical JSON of {@link LiveActivityContentState}. The AAD is separated + * from the notification channel so a ciphertext cannot be replayed across + * channels. The iOS side (`HapiProtocol/LiveActivity/*`) implements the same + * wire format; `shared/fixtures/live-activity/content-state-v1.json` pins a + * byte-for-byte vector. + */ +export const LIVE_ACTIVITY_AAD = 'hapi-live-activity-v1' +export const LIVE_ACTIVITY_STATE_VERSION = 1 + +export type LiveActivityStatus = + | 'working' + | 'needsApproval' + | 'needsInput' + | 'needsAttention' + | 'done' + | 'error' + +export type LiveActivityContentState = { + status: LiveActivityStatus + title: string + project: string + startedAt: number + updatedAt: number + pendingCount: number + todoCompleted: number + todoTotal: number + backgroundTaskCount: number +} + +export type EncryptedLiveActivityState = { + v: number + e: string +} + +/** + * Encrypts the activity state into the APNs `content-state` shape. + * `nonce` is injectable only for tests / vector generation. + */ +export function encryptLiveActivityState( + state: LiveActivityContentState, + key: Uint8Array, + nonce?: Uint8Array +): EncryptedLiveActivityState { + const plaintext = canonicalJson(state) + return { + v: LIVE_ACTIVITY_STATE_VERSION, + e: encryptEnvelopeWithAad(key, plaintext, LIVE_ACTIVITY_AAD, nonce) + } +} + +/** + * Test / diagnostic counterpart: opens the wrapper and returns the state. + * The hub never needs to decrypt its own pushes in production. + */ +export function decryptLiveActivityState( + envelope: EncryptedLiveActivityState, + key: Uint8Array +): LiveActivityContentState { + if (envelope.v !== LIVE_ACTIVITY_STATE_VERSION) { + throw new Error(`unsupported Live Activity state version: ${envelope.v}`) + } + const plaintext = decryptEnvelopeWithAad(key, envelope.e, LIVE_ACTIVITY_AAD) + return JSON.parse(plaintext) as LiveActivityContentState +} diff --git a/hub/src/live-activity/liveActivityControl.ts b/hub/src/live-activity/liveActivityControl.ts new file mode 100644 index 00000000..f60976d3 --- /dev/null +++ b/hub/src/live-activity/liveActivityControl.ts @@ -0,0 +1,11 @@ +/** + * The narrow surface the registration route needs from the notifier. Keeping + * it separate avoids a route → notifier → route import cycle and lets tests + * inject a tiny fake. + */ +export type LiveActivityControl = { + /** True only when the hub is in direct-APNs mode. */ + isRemoteSupported(): boolean + /** Recompute and push the session's current state (optionally bypassing dedupe). */ + reconcile(sessionId: string, force?: boolean): void +} diff --git a/hub/src/live-activity/liveActivityNotifier.test.ts b/hub/src/live-activity/liveActivityNotifier.test.ts new file mode 100644 index 00000000..d74387ce --- /dev/null +++ b/hub/src/live-activity/liveActivityNotifier.test.ts @@ -0,0 +1,357 @@ +import { afterEach, describe, expect, it } from 'bun:test' + +import type { Session, SyncEvent, SyncEventListener, SyncEngine } from '../sync/syncEngine' +import { Store } from '../store' +import { + decryptLiveActivityState, + type EncryptedLiveActivityState +} from './liveActivityContract' +import { LiveActivityNotifier } from './liveActivityNotifier' +import type { + LiveActivityPushOutcome, + LiveActivityPushRequest, + LiveActivityPushTransport +} from './liveActivityPushTransport' + +const KEY = Buffer.alloc(32, 7) +const KEY_B64 = KEY.toString('base64') +const TOKEN = 'aa'.repeat(32) + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) + +class FakeSyncEngine { + private readonly listeners: Set = new Set() + private readonly sessions: Map = new Map() + + subscribe(listener: SyncEventListener): () => void { + this.listeners.add(listener) + return () => this.listeners.delete(listener) + } + + getSession(sessionId: string): Session | undefined { + return this.sessions.get(sessionId) + } + + setSession(session: Session): void { + this.sessions.set(session.id, session) + } + + emit(event: SyncEvent): void { + for (const listener of this.listeners) listener(event) + } +} + +class FakeTransport implements LiveActivityPushTransport { + requests: LiveActivityPushRequest[] = [] + outcome: LiveActivityPushOutcome = 'sent' + + async sendLiveActivity(request: LiveActivityPushRequest): Promise { + this.requests.push(request) + return this.outcome + } +} + +function createSession(overrides: Partial = {}): Session { + return { + id: 'sess-1', + namespace: 'default', + seq: 1, + createdAt: 0, + updatedAt: 0, + active: true, + activeAt: 1_700_000_000_000, + metadata: { + path: '/Users/x/projects/hapi', + host: 'm1', + name: 'Fix widget' + }, + metadataVersion: 0, + agentState: null, + agentStateVersion: 0, + thinking: true, + thinkingAt: 1_700_000_000_000, + activeTurnStartedAt: 1_700_000_000_000, + backgroundTaskCount: 0, + todos: [], + model: null, + modelReasoningEffort: null, + effort: null, + serviceTier: null, + ...overrides + } +} + +function setup(options: { enabled?: boolean; endGraceMs?: number } = {}) { + const store = new Store(':memory:') + store.liveActivities.upsert('default', 'dev-1', 'sess-1', TOKEN, KEY_B64) + const engine = new FakeSyncEngine() + const transport = new FakeTransport() + const clock = { now: 1_700_000_000_000 } + const notifier = new LiveActivityNotifier(engine as unknown as SyncEngine, store, transport, { + enabled: options.enabled ?? true, + now: () => clock.now, + statusThrottleMs: 0, + countThrottleMs: 0, + endGraceMs: options.endGraceMs ?? 5 + }) + return { store, engine, transport, clock, notifier } +} + +function decrypted(request: LiveActivityPushRequest) { + return decryptLiveActivityState( + request.payload.aps['content-state'] as EncryptedLiveActivityState, + KEY + ) +} + +describe('LiveActivityNotifier', () => { + let cleanup: (() => void) | null = null + afterEach(() => { + cleanup?.() + cleanup = null + }) + + it('sends an encrypted working update on boot and preserves the turn start', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + + expect(transport.requests).toHaveLength(1) + const request = transport.requests[0]! + expect(request.payload.aps.event).toBe('update') + expect(request.priority).toBe(10) + expect(String(request.payload.aps['stale-date'])).toMatch(/^\d+$/) + expect(JSON.stringify(request.payload)).not.toContain('Fix widget') + + const state = decrypted(request) + expect(state).toMatchObject({ + status: 'working', + title: 'Fix widget', + project: 'hapi', + startedAt: 1_700_000_000_000, + pendingCount: 0, + todoCompleted: 0, + todoTotal: 0 + }) + }) + + it('maps permission and input requests to the attention states', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession({ + agentState: { + requests: { + req1: { tool: 'Edit', arguments: {}, createdAt: 1 } + } + } + })) + + notifier.start() + await sleep(20) + expect(decrypted(transport.requests[0]!).status).toBe('needsApproval') + expect(decrypted(transport.requests[0]!).pendingCount).toBe(1) + + engine.setSession(createSession({ + agentState: { + requests: { + req2: { + tool: 'AskUserQuestion', + arguments: {}, + createdAt: 2 + } + } + } + })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(20) + expect(decrypted(transport.requests[1]!).status).toBe('needsInput') + }) + + it('dedupes unchanged state and sends count-only changes at lower priority', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + const initialCount = transport.requests.length + + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(20) + expect(transport.requests).toHaveLength(initialCount) + + engine.setSession(createSession({ + todos: [ + { content: 'one', status: 'completed', priority: 'medium', id: 't1' }, + { content: 'two', status: 'pending', priority: 'medium', id: 't2' } + ] + })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(20) + + expect(transport.requests).toHaveLength(initialCount + 1) + const last = transport.requests.at(-1)! + expect(last.priority).toBe(5) + expect(decrypted(last)).toMatchObject({ todoCompleted: 1, todoTotal: 2 }) + }) + + it('does not treat keep-alive activeAt movement as a new turn start', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + // No activeTurnStartedAt/thinkingAt: the previous state's startedAt + // must win over the volatile activeAt. + engine.setSession(createSession({ + activeTurnStartedAt: undefined, + thinkingAt: 0, + activeAt: 1_700_000_000_000 + })) + + notifier.start() + await sleep(20) + const initialCount = transport.requests.length + + engine.setSession(createSession({ + activeTurnStartedAt: undefined, + thinkingAt: 0, + activeAt: 1_700_000_010_000 + })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(20) + + expect(transport.requests).toHaveLength(initialCount) + }) + + it('ends on session-ended, maps errors, and removes the token rows', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + engine.emit({ type: 'session-ended', sessionId: 'sess-1', reason: 'error' }) + await sleep(30) + + const last = transport.requests.at(-1)! + expect(last.payload.aps.event).toBe('end') + expect(last.priority).toBe(10) + expect(decrypted(last).status).toBe('error') + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('handles a namespace-less session-removed by ending via the token row', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + engine.emit({ type: 'session-removed', sessionId: 'sess-1' }) + await sleep(30) + + expect(transport.requests.at(-1)!.payload.aps.event).toBe('end') + expect(decrypted(transport.requests.at(-1)!).status).toBe('done') + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('prunes a token on APNs invalid', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + transport.outcome = 'invalid' + + notifier.start() + await sleep(20) + + expect(transport.requests).toHaveLength(1) + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('ends registered activities whose session vanished before boot', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + // No engine.setSession: the token row is stale. + + notifier.start() + await sleep(20) + + expect(transport.requests).toHaveLength(1) + expect(transport.requests[0]!.payload.aps.event).toBe('end') + expect(decrypted(transport.requests[0]!).status).toBe('done') + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('ends a settled session after the grace window', async () => { + const { store, engine, transport, notifier } = setup({ endGraceMs: 20 }) + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + engine.setSession(createSession({ thinking: false, active: true })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(60) + + expect(transport.requests.at(-1)!.payload.aps.event).toBe('end') + expect(decrypted(transport.requests.at(-1)!).status).toBe('done') + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('prunes rows with invalid key material without sending', async () => { + const { store, engine, transport, notifier } = setup() + cleanup = () => { notifier.stop(); store.close() } + store.liveActivities.upsert( + 'default', + 'dev-1', + 'sess-1', + TOKEN, + Buffer.alloc(16, 1).toString('base64') + ) + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + + expect(transport.requests).toHaveLength(0) + expect(store.liveActivities.listAll()).toHaveLength(0) + }) + + it('sends nothing when disabled', async () => { + const { store, engine, transport, notifier } = setup({ enabled: false }) + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(10) + + expect(transport.requests).toHaveLength(0) + expect(notifier.isRemoteSupported()).toBe(false) + // Disabled hubs leave registrations alone for a later APNs deployment. + expect(store.liveActivities.listAll()).toHaveLength(1) + }) + + it('delays an end and cancels it when the session starts working again', async () => { + const { store, engine, transport, notifier } = setup({ endGraceMs: 100 }) + cleanup = () => { notifier.stop(); store.close() } + engine.setSession(createSession()) + + notifier.start() + await sleep(20) + const before = transport.requests.length + + // Settled but not ended: schedule the grace end. + engine.setSession(createSession({ thinking: false })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(10) + + // A new turn starts inside the grace window. + engine.setSession(createSession({ thinking: true })) + engine.emit({ type: 'session-updated', sessionId: 'sess-1' }) + await sleep(150) + + expect(transport.requests.length).toBe(before) + expect(store.liveActivities.listAll()).toHaveLength(1) + }) +}) diff --git a/hub/src/live-activity/liveActivityNotifier.ts b/hub/src/live-activity/liveActivityNotifier.ts new file mode 100644 index 00000000..ac8b7fd7 --- /dev/null +++ b/hub/src/live-activity/liveActivityNotifier.ts @@ -0,0 +1,408 @@ +import type { SessionEndReason } from '@hapi/protocol' + +import type { Store } from '../store' +import type { StoredLiveActivityToken } from '../store/types' +import type { SyncEngine, SyncEvent } from '../sync/syncEngine' +import { extractMessageEventType } from '../notifications/eventParsing' +import type { LiveActivityControl } from './liveActivityControl' +import type { LiveActivityContentState } from './liveActivityContract' +import { + buildLiveActivityEndState, + buildLiveActivityPayload, + buildLiveActivityState, + isCountOnlyChange, + liveActivityStateKey, + type LiveActivityApnsPayload +} from './liveActivityPayload' +import type { LiveActivityPushTransport } from './liveActivityPushTransport' + +export type LiveActivityNotifierOptions = { + /** True only when the hub is in direct-APNs mode. */ + enabled: boolean + /** Injectable for tests; defaults to Date.now. */ + now?: () => number + /** Minimum gap between status/title changes. */ + statusThrottleMs?: number + /** Minimum gap between counter-only changes. */ + countThrottleMs?: number + /** Flicker guard: wait this long before ending a settled session. */ + endGraceMs?: number + maxConcurrentSends?: number +} + +type Timer = ReturnType + +const DAY_MS = 24 * 60 * 60 * 1000 +const APNS_UPDATE_EXPIRATION_SECONDS = 300 +const APNS_END_EXPIRATION_SECONDS = 300 + +/** + * Turns `SyncEngine` session transitions into iOS Live Activity pushes. + * + * This deliberately does not reuse `NotificationHub`: that hub only fires on + * four discrete notification triggers and suppresses ready/permission updates + * with its own debounces. Live Activities need every attention/working edge. + * + * The hub never *starts* an activity (the app does, then registers the + * per-activity token); it only updates and ends registered activities. + */ +export class LiveActivityNotifier implements LiveActivityControl { + private readonly now: () => number + private readonly statusThrottleMs: number + private readonly countThrottleMs: number + private readonly endGraceMs: number + private readonly maxConcurrentSends: number + + private unsubscribe: (() => void) | null = null + private stopped = false + + private readonly namespaces = new Map() + private readonly lastStates = new Map() + private readonly stateKeys = new Map() + private readonly lastSentAt = new Map() + private readonly lastSentSeconds = new Map() + private readonly reconcileTimers = new Map() + private readonly endTimers = new Map() + private readonly sendChains = new Map>() + + constructor( + private readonly syncEngine: SyncEngine, + private readonly store: Store, + private readonly transport: LiveActivityPushTransport | null, + private readonly options: LiveActivityNotifierOptions + ) { + this.now = options.now ?? Date.now + this.statusThrottleMs = options.statusThrottleMs ?? 2_000 + this.countThrottleMs = options.countThrottleMs ?? 5_000 + this.endGraceMs = options.endGraceMs ?? 3_000 + this.maxConcurrentSends = Math.max(1, options.maxConcurrentSends ?? 4) + } + + isRemoteSupported(): boolean { + return this.options.enabled + } + + start(): void { + if (!this.options.enabled || this.unsubscribe) return + this.stopped = false + this.reconcileAll() + this.unsubscribe = this.syncEngine.subscribe((event) => this.handleEvent(event)) + } + + stop(): void { + this.stopped = true + this.unsubscribe?.() + this.unsubscribe = null + for (const timer of this.reconcileTimers.values()) clearTimeout(timer) + for (const timer of this.endTimers.values()) clearTimeout(timer) + this.reconcileTimers.clear() + this.endTimers.clear() + } + + /** + * Boot reconcile: the app may have registered activities while the hub + * was down, and `SyncEngine` loads stored sessions before any subscriber + * exists. Push the current view (or end sessions that vanished) and drop + * rows older than a Live Activity's maximum lifetime. + */ + private reconcileAll(): void { + const now = this.now() + for (const ref of this.store.liveActivities.listSessionRefs()) { + this.namespaces.set(ref.sessionId, ref.namespace) + const session = this.syncEngine.getSession(ref.sessionId) + if (!session) { + this.endNow(ref.sessionId, 'cleared') + continue + } + this.reconcile(ref.sessionId, true) + } + this.store.liveActivities.pruneOlderThan(now - DAY_MS) + } + + private handleEvent(event: SyncEvent): void { + if (!this.options.enabled || this.stopped) return + const sessionId = 'sessionId' in event ? event.sessionId : undefined + if (!sessionId) return + + if (event.type === 'session-added' || event.type === 'session-updated') { + const session = this.syncEngine.getSession(sessionId) + const namespace = event.namespace ?? session?.namespace + if (namespace) this.namespaces.set(sessionId, namespace) + this.reconcile(sessionId) + return + } + + if (event.type === 'message-received') { + // Ready is a user-facing completion edge; let reconcile decide + // whether the cached session actually settled (it may still be + // thinking until the follow-up alive patch). + if (extractMessageEventType(event) === 'ready') { + this.reconcile(sessionId) + } + return + } + + if (event.type === 'session-ended') { + const namespace = event.namespace + ?? this.syncEngine.getSession(sessionId)?.namespace + ?? this.namespaces.get(sessionId) + if (namespace) this.namespaces.set(sessionId, namespace) + this.endNow(sessionId, event.reason) + return + } + + if (event.type === 'session-removed') { + // This event may omit the namespace (sessionCache evicts the + // cache first). The token store has a namespace-agnostic fallback. + this.endNow(sessionId, 'cleared') + } + } + + /** + * Recomputes one session. `force` bypasses dedupe and throttle for boot + * reconcile and genuine token-registration changes. + */ + reconcile(sessionId: string, force: boolean = false): void { + if (!this.options.enabled || this.stopped) return + const tokens = this.tokensFor(sessionId) + if (tokens.length === 0) { + this.clearSessionState(sessionId) + return + } + + const session = this.syncEngine.getSession(sessionId) + if (!session) { + this.endNow(sessionId, 'cleared') + return + } + this.namespaces.set(sessionId, session.namespace) + + const now = this.now() + const previous = this.lastStates.get(sessionId) + const state = buildLiveActivityState(session, now, previous) + if (!state) { + this.scheduleEnd(sessionId) + return + } + this.cancelEnd(sessionId) + + const key = liveActivityStateKey(state) + if (!force && this.stateKeys.get(sessionId) === key) return + + const urgent = !isCountOnlyChange(previous, state) + const throttle = urgent ? this.statusThrottleMs : this.countThrottleMs + const lastSentAt = this.lastSentAt.get(sessionId) ?? 0 + const wait = force ? 0 : Math.max(0, lastSentAt + throttle - now) + if (wait > 0) { + this.scheduleReconcile(sessionId, wait) + return + } + + this.stateKeys.set(sessionId, key) + this.lastStates.set(sessionId, state) + this.lastSentAt.set(sessionId, now) + // Use the tokens that existed when this state was computed. A fresh + // token registered by a new turn must not receive the old state; its + // own registration reconcile will send the current one. + this.enqueue(sessionId, () => this.sendUpdate(sessionId, state, urgent, tokens)) + } + + private scheduleReconcile(sessionId: string, delayMs: number): void { + this.cancelReconcile(sessionId) + const timer = setTimeout(() => { + this.reconcileTimers.delete(sessionId) + this.reconcile(sessionId, true) + }, Math.max(1, delayMs)) + this.reconcileTimers.set(sessionId, timer) + } + + private scheduleEnd(sessionId: string): void { + if (this.endTimers.has(sessionId)) return + const timer = setTimeout(() => { + this.endTimers.delete(sessionId) + this.endNow(sessionId) + }, Math.max(1, this.endGraceMs)) + this.endTimers.set(sessionId, timer) + } + + private endNow(sessionId: string, reason?: SessionEndReason): void { + if (!this.options.enabled || this.stopped) return + this.cancelReconcile(sessionId) + this.cancelEnd(sessionId) + + const tokens = this.tokensFor(sessionId) + const session = this.syncEngine.getSession(sessionId) + if (tokens.length === 0) { + this.clearSessionState(sessionId) + return + } + const previous = this.lastStates.get(sessionId) + const state = buildLiveActivityEndState({ + session, + previous, + reason, + now: this.now() + }) + this.lastStates.set(sessionId, state) + this.enqueue(sessionId, async () => { + // End the tokens that existed when the end was scheduled. A new + // turn that registers a fresh token while this is queued must + // not receive the previous turn's end. + const endedTokens = await this.sendEnd(sessionId, state, tokens) + for (const row of endedTokens) { + this.store.liveActivities.removeByToken(row.namespace, row.token) + } + this.clearSessionState(sessionId) + }) + } + + private async sendUpdate( + sessionId: string, + state: LiveActivityContentState, + urgent: boolean, + tokens: StoredLiveActivityToken[] + ): Promise { + if (tokens.length === 0) return + const timestamp = this.nextTimestamp(sessionId) + await this.sendToTokens({ + tokens, + event: 'update', + state, + priority: urgent ? 10 : 5, + expiration: timestamp + APNS_UPDATE_EXPIRATION_SECONDS, + timestamp + }) + } + + private async sendEnd( + sessionId: string, + state: LiveActivityContentState, + tokens: StoredLiveActivityToken[] + ): Promise { + if (tokens.length === 0) return [] + const timestamp = this.nextTimestamp(sessionId) + await this.sendToTokens({ + tokens, + event: 'end', + state, + priority: 10, + expiration: timestamp + APNS_END_EXPIRATION_SECONDS, + timestamp + }) + return tokens + } + + private async sendToTokens(args: { + tokens: StoredLiveActivityToken[] + event: 'update' | 'end' + state: LiveActivityContentState + priority: number + expiration: number + timestamp: number + }): Promise { + const transport = this.transport + if (!transport) return + for (let index = 0; index < args.tokens.length; index += this.maxConcurrentSends) { + const chunk = args.tokens.slice(index, index + this.maxConcurrentSends) + await Promise.all(chunk.map(async (row) => { + const key = Buffer.from(row.pushKey, 'base64') + if (key.length !== 32) { + console.error('[LiveActivity] Device row has an invalid pushKey; pruning') + this.store.liveActivities.removeByToken(row.namespace, row.token) + return + } + const payload: LiveActivityApnsPayload | null = buildLiveActivityPayload({ + event: args.event, + state: args.state, + pushKeyB64: row.pushKey, + timestamp: args.timestamp + }) + if (!payload) { + console.error('[LiveActivity] Skipping oversized/unencodable payload') + return + } + let outcome: 'sent' | 'invalid' | 'failed' + try { + outcome = await transport.sendLiveActivity({ + token: row.token, + payload, + priority: args.priority, + expiration: args.expiration + }) + } catch (error) { + console.error( + '[LiveActivity] Transport threw:', + error instanceof Error ? error.message : error + ) + return + } + if (outcome === 'invalid') { + this.store.liveActivities.removeByToken(row.namespace, row.token) + } else if (outcome === 'failed') { + console.error('[LiveActivity] Push failed for a device token') + } + })) + } + } + + private tokensFor(sessionId: string): StoredLiveActivityToken[] { + const namespace = this.namespaces.get(sessionId) + if (namespace) { + const rows = this.store.liveActivities.getForSession(namespace, sessionId) + if (rows.length > 0) return rows + } + return this.store.liveActivities.listForSessionAnyNamespace(sessionId) + } + + private nextTimestamp(sessionId: string): number { + const seconds = Math.floor(this.now() / 1000) + const last = this.lastSentSeconds.get(sessionId) ?? 0 + const next = Math.max(seconds, last + 1) + this.lastSentSeconds.set(sessionId, next) + return next + } + + private enqueue(sessionId: string, task: () => Promise): void { + const previous = this.sendChains.get(sessionId) ?? Promise.resolve() + const next = previous + .then(task) + .catch((error) => { + console.error( + '[LiveActivity] Send task failed:', + error instanceof Error ? error.message : error + ) + }) + this.sendChains.set(sessionId, next) + void next.finally(() => { + if (this.sendChains.get(sessionId) === next) { + this.sendChains.delete(sessionId) + } + }) + } + + private cancelReconcile(sessionId: string): void { + const timer = this.reconcileTimers.get(sessionId) + if (timer) { + clearTimeout(timer) + this.reconcileTimers.delete(sessionId) + } + } + + private cancelEnd(sessionId: string): void { + const timer = this.endTimers.get(sessionId) + if (timer) { + clearTimeout(timer) + this.endTimers.delete(sessionId) + } + } + + private clearSessionState(sessionId: string): void { + this.cancelReconcile(sessionId) + this.cancelEnd(sessionId) + this.lastStates.delete(sessionId) + this.stateKeys.delete(sessionId) + this.lastSentAt.delete(sessionId) + this.lastSentSeconds.delete(sessionId) + this.namespaces.delete(sessionId) + } +} diff --git a/hub/src/live-activity/liveActivityPayload.ts b/hub/src/live-activity/liveActivityPayload.ts new file mode 100644 index 00000000..e442e096 --- /dev/null +++ b/hub/src/live-activity/liveActivityPayload.ts @@ -0,0 +1,203 @@ +import { toSessionSummary } from '@hapi/protocol' + +import type { SessionEndReason } from '@hapi/protocol' +import type { Session } from '../sync/syncEngine' +import { + encryptLiveActivityState, + type EncryptedLiveActivityState, + type LiveActivityContentState, + type LiveActivityStatus +} from './liveActivityContract' + +export const LIVE_ACTIVITY_TITLE_LIMIT = 120 +export const LIVE_ACTIVITY_PROJECT_LIMIT = 120 +const LIVE_ACTIVITY_STALE_SECONDS = 120 +const LIVE_ACTIVITY_END_DISMISSAL_SECONDS = 60 +export const LIVE_ACTIVITY_PAYLOAD_LIMIT_BYTES = 4096 + +/** + * Session title precedence used by web/iOS (`web/src/lib/sessionTitle.ts`). + * `notifications/sessionInfo.ts` omits `promptTitle`; reusing it here would + * make the lock-screen title disagree with the app after a reconcile. + */ +export function getLiveActivityTitle(session: Session): string { + const metadata = session.metadata + if (metadata?.name?.trim()) return sanitize(metadata.name, LIVE_ACTIVITY_TITLE_LIMIT) + if (metadata?.summary?.text?.trim()) return sanitize(metadata.summary.text, LIVE_ACTIVITY_TITLE_LIMIT) + if (metadata?.promptTitle?.trim()) return sanitize(metadata.promptTitle, LIVE_ACTIVITY_TITLE_LIMIT) + if (metadata?.path) { + const parts = metadata.path.split('/').filter(Boolean) + if (parts.length > 0) return sanitize(parts[parts.length - 1]!, LIVE_ACTIVITY_TITLE_LIMIT) + } + return session.id.slice(0, 8) +} + +export function getLiveActivityProject(session: Session): string { + const path = session.metadata?.path + if (!path) return '' + const parts = path.split('/').filter(Boolean) + return parts.length > 0 ? sanitize(parts[parts.length - 1]!, LIVE_ACTIVITY_PROJECT_LIMIT) : '' +} + +/** + * The state the lock screen should show, or null when the session is settled + * and its activity should end. Pending requests win over `working`. + */ +export function buildLiveActivityState( + session: Session, + now: number, + previous?: LiveActivityContentState +): LiveActivityContentState | null { + if (!session.active) return null + const summary = toSessionSummary(session) + const pendingKinds = new Set(summary.pendingRequestKinds) + let status: LiveActivityStatus | null + if (summary.pendingRequestsCount > 0) { + status = pendingKinds.size === 1 && pendingKinds.has('input') + ? 'needsInput' + : pendingKinds.size === 1 && pendingKinds.has('permission') + ? 'needsApproval' + : 'needsAttention' + } else { + status = session.thinking ? 'working' : null + } + if (!status) return null + + return { + status, + title: getLiveActivityTitle(session), + project: getLiveActivityProject(session), + startedAt: startedAtFor(session, previous, now), + updatedAt: now, + pendingCount: summary.pendingRequestsCount, + todoCompleted: summary.todoProgress?.completed ?? 0, + todoTotal: summary.todoProgress?.total ?? 0, + backgroundTaskCount: summary.backgroundTaskCount + } +} + +/** + * Final content for an end push. Uses the last rendered state for identity/ + * timing; `error` is the only reason that maps to a non-done terminal state. + */ +export function buildLiveActivityEndState(args: { + session?: Session + previous?: LiveActivityContentState + reason?: SessionEndReason + now: number +}): LiveActivityContentState { + const { session, previous, reason, now } = args + const title = session ? getLiveActivityTitle(session) : previous?.title ?? 'HAPI session' + const project = session ? getLiveActivityProject(session) : previous?.project ?? '' + const startedAt = session + ? startedAtFor(session, previous, now) + : previous?.startedAt ?? now + const summary = session ? toSessionSummary(session) : null + return { + status: reason === 'error' ? 'error' : 'done', + title, + project, + startedAt, + updatedAt: now, + pendingCount: summary?.pendingRequestsCount ?? previous?.pendingCount ?? 0, + todoCompleted: summary?.todoProgress?.completed ?? previous?.todoCompleted ?? 0, + todoTotal: summary?.todoProgress?.total ?? previous?.todoTotal ?? 0, + backgroundTaskCount: summary?.backgroundTaskCount ?? previous?.backgroundTaskCount ?? 0 + } +} + +/** + * True when only counter fields differ. Status/title/project/startedAt + * changes are urgent; pending/todo/background counts can wait for the longer + * throttle window. + */ +export function isCountOnlyChange( + previous: LiveActivityContentState | undefined, + next: LiveActivityContentState +): boolean { + if (!previous) return false + return previous.status === next.status + && previous.title === next.title + && previous.project === next.project + && previous.startedAt === next.startedAt +} + +export function liveActivityStateKey(state: LiveActivityContentState): string { + return [ + state.status, + state.title, + state.project, + state.startedAt, + state.pendingCount, + state.todoCompleted, + state.todoTotal, + state.backgroundTaskCount + ].join('|') +} + +export type LiveActivityApnsPayload = { + aps: Record +} + +/** + * Encrypts the state and builds the raw APNs body. Returns null when the + * envelope would exceed APNs' 4 KB limit (skip + log rather than fail the + * whole fan-out). + */ +export function buildLiveActivityPayload(args: { + event: 'update' | 'end' + state: LiveActivityContentState + pushKeyB64: string + timestamp: number +}): LiveActivityApnsPayload | null { + let envelope: EncryptedLiveActivityState + try { + envelope = encryptLiveActivityState( + args.state, + Buffer.from(args.pushKeyB64, 'base64') + ) + } catch { + return null + } + const aps: Record = { + timestamp: args.timestamp, + event: args.event, + 'content-state': envelope + } + if (args.event === 'update') { + aps['stale-date'] = args.timestamp + LIVE_ACTIVITY_STALE_SECONDS + } else { + aps['dismissal-date'] = args.timestamp + LIVE_ACTIVITY_END_DISMISSAL_SECONDS + } + const payload = { aps } + if (Buffer.byteLength(JSON.stringify(payload), 'utf8') > LIVE_ACTIVITY_PAYLOAD_LIMIT_BYTES) { + return null + } + return payload +} + +function startedAtFor( + session: Session, + previous: LiveActivityContentState | undefined, + now: number +): number { + // Deliberately no `activeAt`: it moves on every keep-alive and would + // change the dedupe key, causing a push per heartbeat. Prefer the + // server's turn boundary; a hub restart with no boundary falls back to + // the last user message before the previous run's start. + const activeTurnStartedAt = session.activeTurnStartedAt ?? 0 + if (activeTurnStartedAt > 0) return activeTurnStartedAt + if ((session.thinkingAt ?? 0) > 0) return session.thinkingAt + const lastUser = session.lastUserMessageAt ?? 0 + const previousStart = previous?.startedAt ?? 0 + if (lastUser > previousStart) return lastUser + if (previousStart > 0) return previousStart + return now +} + +/** Strip newlines/control whitespace and cap by code point (no broken graphemes). */ +export function sanitize(value: string, limit: number): string { + const flat = value.replace(/\s+/g, ' ').trim() + const points = Array.from(flat) + return points.length > limit ? points.slice(0, limit).join('') : flat +} diff --git a/hub/src/live-activity/liveActivityPushTransport.ts b/hub/src/live-activity/liveActivityPushTransport.ts new file mode 100644 index 00000000..94476b02 --- /dev/null +++ b/hub/src/live-activity/liveActivityPushTransport.ts @@ -0,0 +1,21 @@ +import type { LiveActivityApnsPayload } from './liveActivityPayload' + +/** + * Per-token send outcome, same semantics as the alert push transport: + * `invalid` means the activity token is permanently dead (410 / + * BadDeviceToken) and the row may be pruned; everything else is transient. + */ +export type LiveActivityPushOutcome = 'sent' | 'invalid' | 'failed' + +export type LiveActivityPushRequest = { + token: string + payload: LiveActivityApnsPayload + /** APNs `apns-priority`: 10 for status transitions/end, 5 for count ticks. */ + priority: number + /** APNs `apns-expiration` in epoch seconds. */ + expiration: number +} + +export type LiveActivityPushTransport = { + sendLiveActivity(request: LiveActivityPushRequest): Promise +} diff --git a/hub/src/push-ios/apnsClient.test.ts b/hub/src/push-ios/apnsClient.test.ts index 3f152b9a..05d299ce 100644 --- a/hub/src/push-ios/apnsClient.test.ts +++ b/hub/src/push-ios/apnsClient.test.ts @@ -224,6 +224,63 @@ describe('ApnsClient against a local node:http2 server', () => { const [first, second] = seen.slice(-2) expect(first.headers['authorization']).toBe(second.headers['authorization']) }) + + it('sends a Live Activity update with the liveactivity topic/type and raw aps body', async () => { + const client = makeClient() + const payload = { + aps: { + timestamp: 1_700_000_000, + event: 'update', + 'content-state': { v: 1, e: 'ZW52' }, + 'stale-date': 1_700_000_120 + } + } + const outcome = await client.sendLiveActivity({ + token: 'la-update-1', + payload, + priority: 5, + expiration: 1_700_000_300 + }) + expect(outcome).toBe('sent') + + const request = seen[seen.length - 1] + expect(request.headers[':path']).toBe('/3/device/la-update-1') + expect(request.headers['apns-topic']).toBe('run.hapi.ios.push-type.liveactivity') + expect(request.headers['apns-push-type']).toBe('liveactivity') + expect(request.headers['apns-priority']).toBe('5') + expect(request.headers['apns-expiration']).toBe('1700000300') + expect(request.headers['apns-collapse-id']).toBeUndefined() + expect(JSON.parse(request.body)).toEqual(payload) + }) + + it('classifies Live Activity 410 and BadDeviceToken as invalid', async () => { + responses.set('la-gone', { status: 410, body: '{"reason":"Unregistered"}' }) + responses.set('la-bad-token', { status: 400, body: '{"reason":"BadDeviceToken"}' }) + const client = makeClient() + expect(await client.sendLiveActivity({ + token: 'la-gone', + payload: { aps: { event: 'end' } }, + priority: 10, + expiration: 1_700_000_300 + })).toBe('invalid') + expect(await client.sendLiveActivity({ + token: 'la-bad-token', + payload: { aps: { event: 'end' } }, + priority: 10, + expiration: 1_700_000_300 + })).toBe('invalid') + }) + + it('logs Live Activity topic errors as failed without pruning the token', async () => { + responses.set('la-bad-topic', { status: 400, body: '{"reason":"TopicDisallowed"}' }) + const outcome = await makeClient().sendLiveActivity({ + token: 'la-bad-topic', + payload: { aps: { event: 'update' } }, + priority: 5, + expiration: 1_700_000_300 + }) + expect(outcome).toBe('failed') + }) }) describe('ApnsClient connection failure', () => { diff --git a/hub/src/push-ios/apnsClient.ts b/hub/src/push-ios/apnsClient.ts index b3d7d4c2..6f0414ed 100644 --- a/hub/src/push-ios/apnsClient.ts +++ b/hub/src/push-ios/apnsClient.ts @@ -2,6 +2,11 @@ import http2 from 'node:http2' import * as jose from 'jose' import type { EncryptedPushRequest, NativePushSendOutcome, EncryptedPushTransport } from '../push-native/transport' +import type { + LiveActivityPushOutcome, + LiveActivityPushRequest, + LiveActivityPushTransport +} from '../live-activity/liveActivityPushTransport' export const APNS_PRODUCTION_HOST = 'https://api.push.apple.com' export const APNS_SANDBOX_HOST = 'https://api.sandbox.push.apple.com' @@ -97,7 +102,7 @@ export type ApnsClientOptions = { * per minute at most, so connection reuse buys nothing and a persistent * APNs session would need ping/goaway lifecycle management. */ -export class ApnsClient implements EncryptedPushTransport { +export class ApnsClient implements EncryptedPushTransport, LiveActivityPushTransport { private readonly jwtProvider: ApnsJwtProvider private readonly bundleId: string private readonly host: string @@ -111,35 +116,87 @@ export class ApnsClient implements EncryptedPushTransport { } async send(request: EncryptedPushRequest): Promise { + const result = await this.perform( + (jwt) => { + const headers: Record = { + ':method': 'POST', + ':path': `/3/device/${request.token}`, + authorization: `bearer ${jwt}`, + 'apns-topic': this.bundleId, + 'apns-push-type': 'alert', + 'apns-priority': String(request.priority ?? 10), + 'apns-expiration': '0', + 'content-type': 'application/json' + } + if (request.collapseId) { + headers['apns-collapse-id'] = request.collapseId + } + return headers + }, + JSON.stringify(buildApnsRequestBody(request.envelope)) + ) + return result ? this.classifyResponse(result.status, result.body) : 'failed' + } + + /** + * Direct-APNs Live Activity push. Uses the app's liveactivity topic + * (`.push-type.liveactivity`) and sends the raw `aps` body built + * by the notifier (already encrypted in `content-state`). + */ + async sendLiveActivity(request: LiveActivityPushRequest): Promise { + const result = await this.perform( + (jwt) => ({ + ':method': 'POST', + ':path': `/3/device/${request.token}`, + authorization: `bearer ${jwt}`, + 'apns-topic': `${this.bundleId}.push-type.liveactivity`, + 'apns-push-type': 'liveactivity', + 'apns-priority': String(request.priority), + 'apns-expiration': String(request.expiration), + 'content-type': 'application/json' + }), + JSON.stringify(request.payload) + ) + return result ? this.classifyLiveActivityResponse(result.status, result.body) : 'failed' + } + + /** + * One HTTP/2 POST. Returns null on JWT/connection/timeout/stream failure + * (always transient); callers classify the HTTP status themselves. + */ + private async perform( + buildHeaders: (jwt: string) => Record, + body: string + ): Promise<{ status: number; body: string } | null> { let jwt: string try { jwt = await this.jwtProvider.getToken() } catch (e) { // Broken .p8 key material is our problem, never the device's. console.error('[ApnsClient] JWT generation failed:', e instanceof Error ? e.message : e) - return 'failed' + return null } - return await new Promise((resolve) => { + return await new Promise<{ status: number; body: string } | null>((resolve) => { let settled = false - let client: http2.ClientHttp2Session - const finish = (outcome: NativePushSendOutcome) => { + let client: http2.ClientHttp2Session | null = null + const finish = (result: { status: number; body: string } | null) => { if (settled) return settled = true clearTimeout(timer) try { - client.close() + client?.close() } catch { } - resolve(outcome) + resolve(result) } const timer = setTimeout(() => { console.error('[ApnsClient] Request timed out after', this.requestTimeoutMs, 'ms') try { - client.destroy() + client?.destroy() } catch { } - finish('failed') + finish(null) }, this.requestTimeoutMs) try { @@ -147,40 +204,26 @@ export class ApnsClient implements EncryptedPushTransport { } catch (e) { console.error('[ApnsClient] Connect threw:', e instanceof Error ? e.message : e) clearTimeout(timer) - resolve('failed') + resolve(null) return } client.on('error', (e) => { // Network error (DNS, TCP, TLS) - transient, never token death. console.error('[ApnsClient] Connection error:', e instanceof Error ? e.message : e) - finish('failed') + finish(null) }) - const headers: Record = { - ':method': 'POST', - ':path': `/3/device/${request.token}`, - authorization: `bearer ${jwt}`, - 'apns-topic': this.bundleId, - 'apns-push-type': 'alert', - 'apns-priority': String(request.priority ?? 10), - 'apns-expiration': '0', - 'content-type': 'application/json' - } - if (request.collapseId) { - headers['apns-collapse-id'] = request.collapseId - } - let req: http2.ClientHttp2Stream try { - req = client.request(headers) + req = client.request(buildHeaders(jwt)) } catch (e) { console.error('[ApnsClient] Request threw:', e instanceof Error ? e.message : e) - finish('failed') + finish(null) return } req.on('error', (e) => { console.error('[ApnsClient] Stream error:', e instanceof Error ? e.message : e) - finish('failed') + finish(null) }) let status = 0 @@ -192,9 +235,9 @@ export class ApnsClient implements EncryptedPushTransport { chunks.push(chunk) }) req.on('end', () => { - finish(this.classifyResponse(status, Buffer.concat(chunks).toString('utf8'))) + finish({ status, body: Buffer.concat(chunks).toString('utf8') }) }) - req.end(JSON.stringify(buildApnsRequestBody(request.envelope))) + req.end(body) }) } @@ -209,13 +252,7 @@ export class ApnsClient implements EncryptedPushTransport { if (status >= 200 && status < 300) { return 'sent' } - const reason = ((): string => { - try { - return (JSON.parse(body) as { reason?: string }).reason ?? '' - } catch { - return '' - } - })() + const reason = this.reason(body) if (status === 410) { return 'invalid' } @@ -225,4 +262,38 @@ export class ApnsClient implements EncryptedPushTransport { console.error('[ApnsClient] Send failed (transient):', status, reason || body.slice(0, 200)) return 'failed' } + + /** + * Live Activity topic/entitlement failures (BadTopic, TopicDisallowed, + * DeviceTokenNotForTopic) are configuration errors, not token death. + * They must not prune the row, and retrying every event is pointless; + * log them distinctly so the operator sees the mismatch. + */ + private classifyLiveActivityResponse(status: number, body: string): LiveActivityPushOutcome { + if (status >= 200 && status < 300) { + return 'sent' + } + const reason = this.reason(body) + if (status === 410 || (status === 400 && reason === 'BadDeviceToken')) { + return 'invalid' + } + if (status === 400 && ( + reason === 'BadTopic' + || reason === 'TopicDisallowed' + || reason === 'DeviceTokenNotForTopic' + )) { + console.error('[ApnsClient] Live Activity configuration error:', status, reason) + return 'failed' + } + console.error('[ApnsClient] Live Activity send failed (transient):', status, reason || body.slice(0, 200)) + return 'failed' + } + + private reason(body: string): string { + try { + return (JSON.parse(body) as { reason?: string }).reason ?? '' + } catch { + return '' + } + } } diff --git a/hub/src/push-native/envelope.ts b/hub/src/push-native/envelope.ts index 656b1e73..dd63de1a 100644 --- a/hub/src/push-native/envelope.ts +++ b/hub/src/push-native/envelope.ts @@ -48,11 +48,30 @@ function sortKeysDeep(value: unknown): unknown { } /** - * Encrypt `plaintext` under `key` and return the base64 envelope. + * Encrypt `plaintext` under `key` and return the base64 envelope with the + * push-notification AAD. Kept as the default entry point for the alert + * channel; Live Activities use {@link encryptEnvelopeWithAad} with their own + * domain-separated AAD. + * * `nonce` is only injectable for tests / vector generation - production * callers must let it default to 12 fresh random bytes per message. */ export function encryptEnvelope(key: Uint8Array, plaintext: string, nonce?: Uint8Array): string { + return encryptEnvelopeWithAad(key, plaintext, PUSH_ENVELOPE_AAD, nonce) +} + +/** + * Same wire format as {@link encryptEnvelope} but with a caller-supplied + * AAD. Used by Live Activity `content-state`, whose AAD is + * `hapi-live-activity-v1`, so ciphertexts cannot be replayed between the + * notification and Live Activity channels. + */ +export function encryptEnvelopeWithAad( + key: Uint8Array, + plaintext: string, + aad: string, + nonce?: Uint8Array +): string { if (key.length !== PUSH_KEY_LENGTH) { throw new Error(`push envelope key must be ${PUSH_KEY_LENGTH} bytes, got ${key.length}`) } @@ -61,17 +80,29 @@ export function encryptEnvelope(key: Uint8Array, plaintext: string, nonce?: Uint throw new Error(`push envelope nonce must be ${PUSH_NONCE_LENGTH} bytes, got ${iv.length}`) } const cipher = createCipheriv('aes-256-gcm', key, iv) - cipher.setAAD(Buffer.from(PUSH_ENVELOPE_AAD, 'ascii')) + cipher.setAAD(Buffer.from(aad, 'ascii')) const ciphertext = Buffer.concat([cipher.update(Buffer.from(plaintext, 'utf8')), cipher.final()]) const tag = cipher.getAuthTag() return Buffer.concat([iv, ciphertext, tag]).toString('base64') } /** - * Decrypt a base64 envelope. Throws on truncated envelopes and on any - * authentication failure (wrong key, flipped bit, altered AAD). + * Decrypt a base64 envelope with the push-notification AAD. */ export function decryptEnvelope(key: Uint8Array, envelopeB64: string): string { + return decryptEnvelopeWithAad(key, envelopeB64, PUSH_ENVELOPE_AAD) +} + +/** + * Decrypt a base64 envelope with a caller-supplied AAD. Throws on truncated + * envelopes and on any authentication failure (wrong key, flipped bit, + * altered AAD). + */ +export function decryptEnvelopeWithAad( + key: Uint8Array, + envelopeB64: string, + aad: string +): string { if (key.length !== PUSH_KEY_LENGTH) { throw new Error(`push envelope key must be ${PUSH_KEY_LENGTH} bytes, got ${key.length}`) } @@ -83,7 +114,7 @@ export function decryptEnvelope(key: Uint8Array, envelopeB64: string): string { const ciphertext = raw.subarray(PUSH_NONCE_LENGTH, raw.length - PUSH_TAG_LENGTH) const tag = raw.subarray(raw.length - PUSH_TAG_LENGTH) const decipher = createDecipheriv('aes-256-gcm', key, iv) - decipher.setAAD(Buffer.from(PUSH_ENVELOPE_AAD, 'ascii')) + decipher.setAAD(Buffer.from(aad, 'ascii')) decipher.setAuthTag(tag) return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8') } diff --git a/hub/src/startHub.ts b/hub/src/startHub.ts index 99301d95..e1b44186 100644 --- a/hub/src/startHub.ts +++ b/hub/src/startHub.ts @@ -2,6 +2,7 @@ import { createConfiguration, type ConfigSource } from './configuration' import { Store } from './store' import { SyncEngine, type SyncEvent } from './sync/syncEngine' import { NotificationHub } from './notifications/notificationHub' +import { LiveActivityNotifier } from './live-activity/liveActivityNotifier' import type { NotificationChannel } from './notifications/notificationTypes' import { HappyBot } from './telegram/bot' import { startWebServer } from './web/server' @@ -122,6 +123,7 @@ export async function startHub(options: StartHubOptions = {}): Promise { await usageReconciliation?.refresh() - } + }, + getLiveActivityControl: () => liveActivityNotifier }) // Start the bot if configured @@ -526,6 +533,7 @@ export async function startHub(options: StartHubOptions = {}): Promise { + it('upserts by namespace/device/session and reports genuine changes', () => { + const store = new Store(':memory:') + expect(store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'aa'.repeat(32), KEY)).toBe(true) + // Same token/key: no change, so no forced reconcile. + expect(store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'aa'.repeat(32), KEY)).toBe(false) + // Rotated activity token: changed. + expect(store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'bb'.repeat(32), KEY)).toBe(true) + + const rows = store.liveActivities.getForSession('default', 'sess-1') + expect(rows).toHaveLength(1) + expect(rows[0]).toMatchObject({ + namespace: 'default', + deviceId: 'dev-1', + sessionId: 'sess-1', + token: 'bb'.repeat(32), + pushKey: KEY + }) + store.close() + }) + + it('scopes tokens per device and can remove one device or one session', () => { + const store = new Store(':memory:') + store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'aa'.repeat(32), KEY) + store.liveActivities.upsert('default', 'dev-2', 'sess-1', 'bb'.repeat(32), KEY) + store.liveActivities.upsert('default', 'dev-1', 'sess-2', 'cc'.repeat(32), KEY) + + expect(store.liveActivities.listSessionRefs().sort((a, b) => a.sessionId.localeCompare(b.sessionId))) + .toEqual([ + { namespace: 'default', sessionId: 'sess-1' }, + { namespace: 'default', sessionId: 'sess-2' } + ]) + + store.liveActivities.removeForDevice('default', 'dev-1', 'sess-1') + expect(store.liveActivities.getForSession('default', 'sess-1')).toHaveLength(1) + expect(store.liveActivities.getForSession('default', 'sess-1')[0]?.deviceId).toBe('dev-2') + + store.liveActivities.removeForSession('sess-1') + expect(store.liveActivities.listForSessionAnyNamespace('sess-1')).toHaveLength(0) + expect(store.liveActivities.getForSession('default', 'sess-2')).toHaveLength(1) + store.close() + }) + + it('removes by token and prunes stale rows', () => { + const store = new Store(':memory:') + store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'aa'.repeat(32), KEY) + store.liveActivities.removeByToken('default', 'aa'.repeat(32)) + expect(store.liveActivities.listAll()).toHaveLength(0) + + store.liveActivities.upsert('default', 'dev-1', 'sess-1', 'aa'.repeat(32), KEY) + store.liveActivities.pruneOlderThan(Date.now() + 1) + expect(store.liveActivities.listAll()).toHaveLength(0) + store.close() + }) +}) diff --git a/hub/src/store/liveActivities.ts b/hub/src/store/liveActivities.ts new file mode 100644 index 00000000..869a87a2 --- /dev/null +++ b/hub/src/store/liveActivities.ts @@ -0,0 +1,149 @@ +import type { Database } from 'bun:sqlite' + +import type { StoredLiveActivityToken } from './types' + +type DbLiveActivityTokenRow = { + id: number + namespace: string + device_id: string + session_id: string + token: string + push_key: string + created_at: number + updated_at: number +} + +function toStoredLiveActivityToken(row: DbLiveActivityTokenRow): StoredLiveActivityToken { + return { + id: row.id, + namespace: row.namespace, + deviceId: row.device_id, + sessionId: row.session_id, + token: row.token, + pushKey: row.push_key, + createdAt: row.created_at, + updatedAt: row.updated_at + } +} + +/** + * Upserts one device's Live Activity token for a session and returns whether + * the token/key actually changed. Registration calls use the changed bit to + * decide whether to force a reconciliation push; a foreground re-registration + * with the same token must not cause a push. + */ +export function upsertLiveActivityToken( + db: Database, + namespace: string, + deviceId: string, + sessionId: string, + token: string, + pushKey: string +): boolean { + const existing = db.prepare(` + SELECT token, push_key FROM live_activity_tokens + WHERE namespace = ? AND device_id = ? AND session_id = ? + `).get(namespace, deviceId, sessionId) as { token: string; push_key: string } | undefined + const changed = !existing || existing.token !== token || existing.push_key !== pushKey + const now = Date.now() + db.prepare(` + INSERT INTO live_activity_tokens ( + namespace, device_id, session_id, token, push_key, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(namespace, device_id, session_id) + DO UPDATE SET + token = excluded.token, + push_key = excluded.push_key, + updated_at = excluded.updated_at + `).run(namespace, deviceId, sessionId, token, pushKey, now, now) + return changed +} + +export function removeLiveActivityTokenByToken( + db: Database, + namespace: string, + token: string +): void { + db.prepare(` + DELETE FROM live_activity_tokens WHERE namespace = ? AND token = ? + `).run(namespace, token) +} + +export function removeLiveActivityTokens( + db: Database, + namespace: string, + deviceId: string, + sessionId?: string +): void { + if (sessionId) { + db.prepare(` + DELETE FROM live_activity_tokens + WHERE namespace = ? AND device_id = ? AND session_id = ? + `).run(namespace, deviceId, sessionId) + return + } + db.prepare(` + DELETE FROM live_activity_tokens WHERE namespace = ? AND device_id = ? + `).run(namespace, deviceId) +} + +export function getLiveActivityTokensForSession( + db: Database, + namespace: string, + sessionId: string +): StoredLiveActivityToken[] { + const rows = db.prepare(` + SELECT * FROM live_activity_tokens + WHERE namespace = ? AND session_id = ? + ORDER BY updated_at DESC + `).all(namespace, sessionId) as DbLiveActivityTokenRow[] + return rows.map(toStoredLiveActivityToken) +} + +export function listLiveActivityTokens(db: Database): StoredLiveActivityToken[] { + const rows = db.prepare(` + SELECT * FROM live_activity_tokens ORDER BY updated_at DESC + `).all() as DbLiveActivityTokenRow[] + return rows.map(toStoredLiveActivityToken) +} + +/** + * Namespace-agnostic lookup for `session-removed`, whose event may not carry + * a namespace. Session ids are UUIDs, so cross-namespace matches cannot + * collide in practice. + */ +export function listLiveActivityTokensForAnySession( + db: Database, + sessionId: string +): StoredLiveActivityToken[] { + const rows = db.prepare(` + SELECT * FROM live_activity_tokens WHERE session_id = ? ORDER BY updated_at DESC + `).all(sessionId) as DbLiveActivityTokenRow[] + return rows.map(toStoredLiveActivityToken) +} + +/** + * Session ids with at least one registered activity token. Used by the boot + * reconcile; the namespace travels with the row, so the caller can resolve + * the session from the cache. + */ +export function listLiveActivitySessionRefs( + db: Database +): Array<{ namespace: string; sessionId: string }> { + const rows = db.prepare(` + SELECT DISTINCT namespace, session_id FROM live_activity_tokens + `).all() as Array<{ namespace: string; session_id: string }> + return rows.map((row) => ({ namespace: row.namespace, sessionId: row.session_id })) +} + +/** + * Namespace-agnostic cleanup for `session-removed`, whose event may not carry + * a namespace. Session ids are UUIDs, so deleting by id alone is safe. + */ +export function removeLiveActivityTokensForSession(db: Database, sessionId: string): void { + db.prepare('DELETE FROM live_activity_tokens WHERE session_id = ?').run(sessionId) +} + +export function pruneLiveActivityTokens(db: Database, olderThanMs: number): void { + db.prepare('DELETE FROM live_activity_tokens WHERE updated_at < ?').run(olderThanMs) +} diff --git a/hub/src/store/liveActivityStore.ts b/hub/src/store/liveActivityStore.ts new file mode 100644 index 00000000..240533f8 --- /dev/null +++ b/hub/src/store/liveActivityStore.ts @@ -0,0 +1,71 @@ +import type { Database } from 'bun:sqlite' + +import type { StoredLiveActivityToken } from './types' +import { + getLiveActivityTokensForSession, + listLiveActivitySessionRefs, + listLiveActivityTokens, + listLiveActivityTokensForAnySession, + pruneLiveActivityTokens, + removeLiveActivityTokenByToken, + removeLiveActivityTokens, + removeLiveActivityTokensForSession, + upsertLiveActivityToken +} from './liveActivities' + +/** + * Per-device Live Activity push tokens. This is deliberately separate from + * `fcm_devices`: an activity token is a different capability (it can only + * update the one activity the app created), and the normal device upsert + * would clobber the alert registration. + */ +export class LiveActivityStore { + constructor(private readonly db: Database) {} + + /** + * Upserts `(namespace, deviceId, sessionId)` and reports whether the + * token or push key changed. Callers use that bit to force a reconcile + * only for genuine registration changes. + */ + upsert( + namespace: string, + deviceId: string, + sessionId: string, + token: string, + pushKey: string + ): boolean { + return upsertLiveActivityToken(this.db, namespace, deviceId, sessionId, token, pushKey) + } + + removeByToken(namespace: string, token: string): void { + removeLiveActivityTokenByToken(this.db, namespace, token) + } + + removeForDevice(namespace: string, deviceId: string, sessionId?: string): void { + removeLiveActivityTokens(this.db, namespace, deviceId, sessionId) + } + + removeForSession(sessionId: string): void { + removeLiveActivityTokensForSession(this.db, sessionId) + } + + getForSession(namespace: string, sessionId: string): StoredLiveActivityToken[] { + return getLiveActivityTokensForSession(this.db, namespace, sessionId) + } + + listAll(): StoredLiveActivityToken[] { + return listLiveActivityTokens(this.db) + } + + listForSessionAnyNamespace(sessionId: string): StoredLiveActivityToken[] { + return listLiveActivityTokensForAnySession(this.db, sessionId) + } + + listSessionRefs(): Array<{ namespace: string; sessionId: string }> { + return listLiveActivitySessionRefs(this.db) + } + + pruneOlderThan(cutoffMs: number): void { + pruneLiveActivityTokens(this.db, cutoffMs) + } +} diff --git a/hub/src/store/types.ts b/hub/src/store/types.ts index 185aeed5..2c992a8f 100644 --- a/hub/src/store/types.ts +++ b/hub/src/store/types.ts @@ -79,6 +79,19 @@ export type StoredPushSubscription = { export type NativeDevicePlatform = 'phone' | 'wear' | 'ios' +export type StoredLiveActivityToken = { + id: number + namespace: string + deviceId: string + sessionId: string + /** APNs per-activity push token (hex). */ + token: string + /** base64 of the device's 32-byte E2E push key, stored with the token. */ + pushKey: string + createdAt: number + updatedAt: number +} + export type StoredFcmDevice = { id: number namespace: string diff --git a/hub/src/web/routes/devices.ts b/hub/src/web/routes/devices.ts index 11b9c15a..e4f4b51a 100644 --- a/hub/src/web/routes/devices.ts +++ b/hub/src/web/routes/devices.ts @@ -11,7 +11,7 @@ const PUSH_KEY_BYTES = 32 * otherwise garbage like `"!!!!" + 43 chars` could sneak past the length * gate and register an undecryptable key. */ -function decodePushKey(pushKey: string): Buffer | null { +export function decodePushKey(pushKey: string): Buffer | null { if (!/^[A-Za-z0-9+/]+={0,2}$/.test(pushKey)) { return null } diff --git a/hub/src/web/routes/liveActivities.test.ts b/hub/src/web/routes/liveActivities.test.ts new file mode 100644 index 00000000..e6f7f471 --- /dev/null +++ b/hub/src/web/routes/liveActivities.test.ts @@ -0,0 +1,228 @@ +import { describe, expect, it } from 'bun:test' +import { Hono } from 'hono' +import { SignJWT } from 'jose' + +import type { Session, SyncEngine } from '../../sync/syncEngine' +import { Store } from '../../store' +import type { LiveActivityControl } from '../../live-activity/liveActivityControl' +import { createAuthMiddleware, type WebAppEnv } from '../middleware/auth' +import { createLiveActivityRoutes } from './liveActivities' + +const JWT_SECRET = new TextEncoder().encode('test-secret') +const KEY = Buffer.alloc(32, 7).toString('base64') + +async function authHeaders(namespace: string = 'default') { + const token = await new SignJWT({ uid: 1, ns: namespace }) + .setProtectedHeader({ alg: 'HS256' }) + .setIssuedAt() + .setExpirationTime('1h') + .sign(JWT_SECRET) + return { authorization: `Bearer ${token}`, 'content-type': 'application/json' } +} + +function createSession(overrides: Partial = {}): Session { + return { + id: 'sess-1', + namespace: 'default', + seq: 1, + createdAt: 0, + updatedAt: 0, + active: true, + activeAt: 0, + metadata: null, + metadataVersion: 0, + agentState: null, + agentStateVersion: 0, + thinking: false, + thinkingAt: 0, + model: null, + modelReasoningEffort: null, + effort: null, + serviceTier: null, + ...overrides + } +} + +class FakeSyncEngine { + readonly sessions = new Map() + + resolveSessionAccess(sessionId: string, namespace: string): { + ok: true + sessionId: string + session: Session + } | { + ok: false + reason: 'not-found' | 'access-denied' + } { + const session = this.sessions.get(sessionId) + if (!session) return { ok: false, reason: 'not-found' } + if (session.namespace !== namespace) return { ok: false, reason: 'access-denied' } + return { ok: true, sessionId, session } + } +} + +function createApp(args: { + store: Store + engine: FakeSyncEngine + control?: LiveActivityControl | null +}) { + const app = new Hono() + app.use('*', createAuthMiddleware(JWT_SECRET)) + app.route('/api', createLiveActivityRoutes({ + store: args.store, + getSyncEngine: () => args.engine as unknown as SyncEngine, + getControl: () => args.control ?? null + })) + return app +} + +describe('live activity registration routes', () => { + it('registers a token, stores it, and reconciles only when the row changed', async () => { + const store = new Store(':memory:') + const engine = new FakeSyncEngine() + engine.sessions.set('sess-1', createSession()) + const reconciles: Array<{ sessionId: string; force?: boolean }> = [] + const control: LiveActivityControl = { + isRemoteSupported: () => true, + reconcile: (sessionId, force) => reconciles.push({ sessionId, force }) + } + const app = createApp({ store, engine, control }) + const headers = await authHeaders() + const body = { + token: 'aa'.repeat(32), + deviceId: 'dev-1', + sessionId: 'sess-1', + pushKey: KEY + } + + const first = await app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify(body) + }) + expect(first.status).toBe(200) + expect(await first.json()).toEqual({ ok: true, remote: true }) + expect(reconciles).toEqual([{ sessionId: 'sess-1', force: true }]) + expect(store.liveActivities.getForSession('default', 'sess-1')).toHaveLength(1) + + // Same token/key: no forced reconcile. + const second = await app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify(body) + }) + expect(second.status).toBe(200) + expect(reconciles).toHaveLength(1) + + // Rotated activity token: reconcile again. + const rotated = await app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify({ ...body, token: 'bb'.repeat(32) }) + }) + expect(rotated.status).toBe(200) + expect(reconciles).toHaveLength(2) + expect(store.liveActivities.getForSession('default', 'sess-1')[0]?.token).toBe('bb'.repeat(32)) + store.close() + }) + + it('rejects malformed tokens, keys, and unknown sessions', async () => { + const store = new Store(':memory:') + const engine = new FakeSyncEngine() + engine.sessions.set('sess-1', createSession()) + const app = createApp({ store, engine }) + const headers = await authHeaders() + const base = { + token: 'aa'.repeat(32), + deviceId: 'dev-1', + sessionId: 'sess-1', + pushKey: KEY + } + + for (const body of [ + { ...base, token: 'not-hex' }, + { ...base, pushKey: Buffer.alloc(31).toString('base64') } + ]) { + const response = await app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify(body) + }) + expect(response.status).toBe(400) + } + + const missing = await app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify({ ...base, sessionId: 'missing' }) + }) + expect(missing.status).toBe(404) + + const forbidden = await app.request('/api/live-activities/register', { + method: 'POST', + headers: await authHeaders('other'), + body: JSON.stringify(base) + }) + expect(forbidden.status).toBe(403) + expect(store.liveActivities.listAll()).toHaveLength(0) + store.close() + }) + + it('returns remote:false when Live Activities are not enabled on the hub', async () => { + const store = new Store(':memory:') + const engine = new FakeSyncEngine() + engine.sessions.set('sess-1', createSession()) + const app = createApp({ store, engine, control: null }) + const response = await app.request('/api/live-activities/register', { + method: 'POST', + headers: await authHeaders(), + body: JSON.stringify({ + token: 'aa'.repeat(32), + deviceId: 'dev-1', + sessionId: 'sess-1', + pushKey: KEY + }) + }) + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ ok: true, remote: false }) + store.close() + }) + + it('unregisters by token or by device/session', async () => { + const store = new Store(':memory:') + const engine = new FakeSyncEngine() + engine.sessions.set('sess-1', createSession()) + const app = createApp({ store, engine }) + const headers = await authHeaders() + const register = (token: string) => app.request('/api/live-activities/register', { + method: 'POST', + headers, + body: JSON.stringify({ + token, + deviceId: 'dev-1', + sessionId: 'sess-1', + pushKey: KEY + }) + }) + await register('aa'.repeat(32)) + await register('bb'.repeat(32)) // replaces the first row for this device/session + + const byToken = await app.request('/api/live-activities/register', { + method: 'DELETE', + headers, + body: JSON.stringify({ token: 'bb'.repeat(32) }) + }) + expect(byToken.status).toBe(200) + expect(store.liveActivities.listAll()).toHaveLength(0) + + await register('cc'.repeat(32)) + const byDevice = await app.request('/api/live-activities/register', { + method: 'DELETE', + headers, + body: JSON.stringify({ deviceId: 'dev-1', sessionId: 'sess-1' }) + }) + expect(byDevice.status).toBe(200) + expect(store.liveActivities.listAll()).toHaveLength(0) + store.close() + }) +}) diff --git a/hub/src/web/routes/liveActivities.ts b/hub/src/web/routes/liveActivities.ts new file mode 100644 index 00000000..d0e1e8e2 --- /dev/null +++ b/hub/src/web/routes/liveActivities.ts @@ -0,0 +1,100 @@ +import { Hono } from 'hono' +import { z } from 'zod' + +import type { Store } from '../../store' +import type { SyncEngine } from '../../sync/syncEngine' +import type { LiveActivityControl } from '../../live-activity/liveActivityControl' +import type { WebAppEnv } from '../middleware/auth' +import { decodePushKey } from './devices' +import { requireSession, requireSyncEngine } from './guards' + +const tokenSchema = z.string().regex(/^[0-9a-fA-F]{16,512}$/, 'token must be hex') +const deviceIdSchema = z.string().min(1).max(128) +const sessionIdSchema = z.string().min(1).max(256) + +const registerSchema = z.object({ + token: tokenSchema, + deviceId: deviceIdSchema, + sessionId: sessionIdSchema, + pushKey: z.string() +}) + +const unregisterSchema = z.object({ + token: tokenSchema.optional(), + deviceId: deviceIdSchema.optional(), + sessionId: sessionIdSchema.optional() +}).refine((value) => value.token !== undefined || value.deviceId !== undefined, { + message: 'token or deviceId is required' +}) + +/** + * Live Activity token registration. The iOS app creates the activity and + * sends its per-activity APNs token here; the hub encrypts future updates + * with the `pushKey` supplied alongside. The token rows are deliberately + * separate from `fcm_devices` (different capability, different lifecycle). + */ +export function createLiveActivityRoutes(options: { + store: Store + getSyncEngine: () => SyncEngine | null + getControl?: () => LiveActivityControl | null +}): Hono { + const app = new Hono() + + app.post('/live-activities/register', async (c) => { + if (c.get('role') === 'session-guest') { + return c.json({ error: 'Guest cannot register Live Activities' }, 403) + } + const json = await c.req.json().catch(() => null) + const parsed = registerSchema.safeParse(json) + if (!parsed.success) { + return c.json({ error: 'Invalid body', issues: parsed.error.flatten() }, 400) + } + const pushKey = decodePushKey(parsed.data.pushKey) + if (!pushKey) { + return c.json({ error: 'pushKey must be base64 of exactly 32 bytes' }, 400) + } + + const engine = requireSyncEngine(c, options.getSyncEngine) + if (engine instanceof Response) return engine + const access = requireSession(c, engine, parsed.data.sessionId) + if (access instanceof Response) return access + + const { token, deviceId, sessionId } = parsed.data + const changed = options.store.liveActivities.upsert( + c.get('namespace'), + deviceId, + sessionId, + token, + pushKey.toString('base64') + ) + const control = options.getControl?.() ?? null + if (changed) { + control?.reconcile(sessionId, true) + } + return c.json({ ok: true, remote: control?.isRemoteSupported() ?? false }) + }) + + app.delete('/live-activities/register', async (c) => { + if (c.get('role') === 'session-guest') { + return c.json({ error: 'Guest cannot register Live Activities' }, 403) + } + const json = await c.req.json().catch(() => null) + const parsed = unregisterSchema.safeParse(json) + if (!parsed.success) { + return c.json({ error: 'Invalid body', issues: parsed.error.flatten() }, 400) + } + const namespace = c.get('namespace') + if (parsed.data.token) { + options.store.liveActivities.removeByToken(namespace, parsed.data.token) + } else if (parsed.data.deviceId) { + options.store.liveActivities.removeForDevice( + namespace, + parsed.data.deviceId, + parsed.data.sessionId + ) + } + return c.json({ ok: true }) + }) + + return app +} diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 712ef99f..4e6cb846 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -33,6 +33,8 @@ import { createDshSessionRoutes } from './routes/dshSessions' import { createOpencodeSessionRoutes } from './routes/opencodeSessions' import { createPushRoutes } from './routes/push' import { createDevicesRoutes } from './routes/devices' +import { createLiveActivityRoutes } from './routes/liveActivities' +import type { LiveActivityControl } from '../live-activity/liveActivityControl' import { createVoiceRoutes } from './routes/voice' import { createHubSettingsRoutes } from './routes/hubSettings' import { createWorkGraphRoutes } from './routes/workGraph' @@ -243,6 +245,7 @@ function createWebApp(options: { officialWebUrl?: string dataDir: string refreshUsage?: () => Promise + getLiveActivityControl?: () => LiveActivityControl | null }): Hono { const app = new Hono() @@ -400,6 +403,11 @@ function createWebApp(options: { app.route('/api', createPushRoutes(options.store, options.vapidPublicKey)) app.route('/api', createClaudeModelsRoutes(options.dataDir)) app.route('/api', createDevicesRoutes(options.store)) + app.route('/api', createLiveActivityRoutes({ + store: options.store, + getSyncEngine: options.getSyncEngine, + getControl: options.getLiveActivityControl + })) app.route('/api', createVoiceRoutes({ dataDir: configuration.dataDir })) // Path is intentionally NOT `/api/events` — that route is the SSE stream. app.route('/api', createWorkGraphRoutes(options.store)) @@ -534,6 +542,7 @@ export async function startWebServer(options: { officialWebUrl?: string dataDir: string refreshUsage?: () => Promise + getLiveActivityControl?: () => LiveActivityControl | null }): Promise> { const isCompiled = isBunCompiled() const embeddedAssetMap = isCompiled ? await loadEmbeddedAssetMap() : null @@ -550,7 +559,8 @@ export async function startWebServer(options: { dataDir: options.dataDir, relayMode: options.relayMode, officialWebUrl: options.officialWebUrl, - refreshUsage: options.refreshUsage + refreshUsage: options.refreshUsage, + getLiveActivityControl: options.getLiveActivityControl }) const configuration = getConfiguration() diff --git a/ios/Hapi.xcodeproj/project.pbxproj b/ios/Hapi.xcodeproj/project.pbxproj index 11f20169..a030ed13 100644 --- a/ios/Hapi.xcodeproj/project.pbxproj +++ b/ios/Hapi.xcodeproj/project.pbxproj @@ -14,6 +14,8 @@ A300000000000000000000C4 /* HapiProtocol in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C2 /* HapiProtocol */; }; A300000000000000000000C5 /* HapiClient in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C3 /* HapiClient */; }; A300000000000000000000C8 /* HapiUI in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C7 /* HapiUI */; }; + A400000000000000000000C4 /* HapiProtocol in Frameworks */ = {isa = PBXBuildFile; productRef = A400000000000000000000C2 /* HapiProtocol */; }; + A400000000000000000000D4 /* HapiWidgets.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A400000000000000000000A4 /* HapiWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); platformFilters = (ios, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -31,6 +33,13 @@ remoteGlobalIDString = A100000000000000000000A5; remoteInfo = Hapi; }; + A400000000000000000000D2 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A100000000000000000000A6 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A400000000000000000000A5; + remoteInfo = HapiWidgets; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -41,6 +50,7 @@ dstSubfolderSpec = 13; files = ( A200000000000000000000D4 /* HapiNotificationService.appex in Embed Foundation Extensions */, + A400000000000000000000D4 /* HapiWidgets.appex in Embed Foundation Extensions */, ); name = "Embed Foundation Extensions"; runOnlyForDeploymentPostprocessing = 0; @@ -51,6 +61,7 @@ A100000000000000000000A4 /* Hapi.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Hapi.app; sourceTree = BUILT_PRODUCTS_DIR; }; A200000000000000000000A4 /* HapiNotificationService.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HapiNotificationService.appex; sourceTree = BUILT_PRODUCTS_DIR; }; A300000000000000000000A4 /* HapiTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; path = HapiTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + A400000000000000000000A4 /* HapiWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HapiWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ @@ -68,6 +79,13 @@ ); target = A200000000000000000000A5 /* HapiNotificationService */; }; + A400000000000000000000C6 /* Exceptions for "HapiWidgets" folder in "HapiWidgets" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = A400000000000000000000A5 /* HapiWidgets */; + }; /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -92,6 +110,14 @@ path = HapiTests; sourceTree = ""; }; + A400000000000000000000A2 /* HapiWidgets */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + A400000000000000000000C6 /* Exceptions for "HapiWidgets" folder in "HapiWidgets" target */, + ); + path = HapiWidgets; + sourceTree = ""; + }; /* End PBXFileSystemSynchronizedRootGroup section */ /* Begin PBXFrameworksBuildPhase section */ @@ -122,6 +148,14 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + A400000000000000000000A8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A400000000000000000000C4 /* HapiProtocol in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -131,6 +165,7 @@ A100000000000000000000A2 /* Hapi */, A200000000000000000000A2 /* HapiNotificationService */, A300000000000000000000A2 /* HapiTests */, + A400000000000000000000A2 /* HapiWidgets */, A100000000000000000000A3 /* Products */, ); sourceTree = ""; @@ -141,6 +176,7 @@ A100000000000000000000A4 /* Hapi.app */, A200000000000000000000A4 /* HapiNotificationService.appex */, A300000000000000000000A4 /* HapiTests.xctest */, + A400000000000000000000A4 /* HapiWidgets.appex */, ); name = Products; sourceTree = ""; @@ -161,6 +197,7 @@ ); dependencies = ( A200000000000000000000D1 /* PBXTargetDependency */, + A400000000000000000000D1 /* PBXTargetDependency */, ); fileSystemSynchronizedGroups = ( A100000000000000000000A2 /* Hapi */, @@ -223,6 +260,29 @@ productReference = A300000000000000000000A4 /* HapiTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; + A400000000000000000000A5 /* HapiWidgets */ = { + isa = PBXNativeTarget; + buildConfigurationList = A400000000000000000000B4 /* Build configuration list for PBXNativeTarget "HapiWidgets" */; + buildPhases = ( + A400000000000000000000A7 /* Sources */, + A400000000000000000000A8 /* Frameworks */, + A400000000000000000000A9 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A400000000000000000000A2 /* HapiWidgets */, + ); + name = HapiWidgets; + packageProductDependencies = ( + A400000000000000000000C2 /* HapiProtocol */, + ); + productName = HapiWidgets; + productReference = A400000000000000000000A4 /* HapiWidgets.appex */; + productType = "com.apple.product-type.app-extension"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -239,6 +299,9 @@ A200000000000000000000A5 = { CreatedOnToolsVersion = 16.0; }; + A400000000000000000000A5 = { + CreatedOnToolsVersion = 16.0; + }; }; }; buildConfigurationList = A100000000000000000000B1 /* Build configuration list for PBXProject "Hapi" */; @@ -263,6 +326,7 @@ A100000000000000000000A5 /* Hapi */, A200000000000000000000A5 /* HapiNotificationService */, A300000000000000000000A5 /* HapiTests */, + A400000000000000000000A5 /* HapiWidgets */, ); }; /* End PBXProject section */ @@ -289,6 +353,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + A400000000000000000000A9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -313,6 +384,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + A400000000000000000000A7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ @@ -326,6 +404,12 @@ target = A100000000000000000000A5 /* Hapi */; targetProxy = A300000000000000000000D2 /* PBXContainerItemProxy */; }; + A400000000000000000000D1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + platformFilter = ios; + target = A400000000000000000000A5 /* HapiWidgets */; + targetProxy = A400000000000000000000D2 /* PBXContainerItemProxy */; + }; /* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ @@ -514,6 +598,66 @@ }; name = Release; }; + A400000000000000000000B5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = HapiWidgets/HapiWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = XJB862F92W; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = HapiWidgets/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = HAPI; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.34.1; + PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiWidgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + A400000000000000000000B6 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_ENTITLEMENTS = HapiWidgets/HapiWidgets.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = XJB862F92W; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = HapiWidgets/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = HAPI; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 0.34.1; + PRODUCT_BUNDLE_IDENTIFIER = run.hapi.app.HapiWidgets; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; A300000000000000000000B5 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -589,6 +733,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + A400000000000000000000B4 /* Build configuration list for PBXNativeTarget "HapiWidgets" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A400000000000000000000B5 /* Debug */, + A400000000000000000000B6 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ @@ -611,6 +764,10 @@ isa = XCSwiftPackageProductDependency; productName = HapiUI; }; + A400000000000000000000C2 /* HapiProtocol */ = { + isa = XCSwiftPackageProductDependency; + productName = HapiProtocol; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = A100000000000000000000A6 /* Project object */; diff --git a/ios/Hapi/Features/LiveActivity/LiveActivityControlling.swift b/ios/Hapi/Features/LiveActivity/LiveActivityControlling.swift new file mode 100644 index 00000000..d145de5b --- /dev/null +++ b/ios/Hapi/Features/LiveActivity/LiveActivityControlling.swift @@ -0,0 +1,50 @@ +import HapiClient +import HapiProtocol + +/// The app-side seam for Live Activities. Declared unconditionally so +/// `AppModel` builds on Mac Catalyst too; the real coordinator is compiled +/// only for iOS (ActivityKit is unavailable on Catalyst). +@MainActor +protocol LiveActivityControlling: AnyObject { + var prefs: LiveActivityPrefs { get } + + /// The active hub changed (initial build, switch). `detach()` must run + /// before the old hub is shut down so its activities can end and their + /// tokens can be unregistered while the API still works. + func attach(to hub: HubSession) + func detach() + + func sessionsChanged(_ sessions: [SessionSummary]) + func setEnabled(_ enabled: Bool) + func appDidBecomeActive() + func appDidBackground() +} + +/// Catalyst / non-iOS placeholder. It still carries the shared prefs so the +/// Settings toggle behaves consistently. +@MainActor +final class NoopLiveActivityController: LiveActivityControlling { + let prefs: LiveActivityPrefs + + init(prefs: LiveActivityPrefs) { + self.prefs = prefs + } + + func attach(to hub: HubSession) {} + func detach() {} + func sessionsChanged(_ sessions: [SessionSummary]) {} + func setEnabled(_ enabled: Bool) { prefs.setEnabled(enabled) } + func appDidBecomeActive() {} + func appDidBackground() {} +} + +enum LiveActivityControllerFactory { + @MainActor + static func make(prefs: LiveActivityPrefs) -> any LiveActivityControlling { + #if os(iOS) && !targetEnvironment(macCatalyst) + return LiveActivityCoordinator(prefs: prefs) + #else + return NoopLiveActivityController(prefs: prefs) + #endif + } +} diff --git a/ios/Hapi/Features/LiveActivity/LiveActivityCoordinator.swift b/ios/Hapi/Features/LiveActivity/LiveActivityCoordinator.swift new file mode 100644 index 00000000..18767f12 --- /dev/null +++ b/ios/Hapi/Features/LiveActivity/LiveActivityCoordinator.swift @@ -0,0 +1,431 @@ +#if os(iOS) && !targetEnvironment(macCatalyst) +import ActivityKit +import Foundation +import HapiClient +import HapiProtocol +import OSLog + +/// Owns every HAPI Live Activity on this device. +/// +/// The app creates activities locally (push-to-start cannot be updated until +/// the app runs and provides the per-activity token), registers each +/// activity's APNs token with the active hub, and keeps local state fresh +/// while it runs. When suspended/killed, the hub's encrypted `liveactivity` +/// pushes take over; on the next launch `Activity.activities` recovers the +/// surviving activities and re-registers their tokens. +@MainActor +final class LiveActivityCoordinator: LiveActivityControlling { + let prefs: LiveActivityPrefs + + private weak var hub: HubSession? + private var activities: [String: Activity] = [:] + private var tokenTasks: [String: Task] = [:] + private var stateTasks: [String: Task] = [:] + private var registeredTokens: [String: String] = [:] + private var startedAt: [String: Int] = [:] + private var lastUserMessageAt: [String: Int] = [:] + private var lastStateKeys: [String: String] = [:] + /// False once the hub reports it cannot push Live Activity updates + /// (relay/off mode); the local activity must then end on background + /// instead of looking frozen on the Lock Screen. + private var remoteSupported = true + + /// System limit is undocumented; keep the lock screen legible and let + /// attention states win when more sessions are running. + private let maxActivities = 5 + private let log = Logger(subsystem: "run.hapi.companion", category: "live-activity") + + init(prefs: LiveActivityPrefs) { + self.prefs = prefs + } + + // MARK: - Hub lifecycle + + func attach(to hub: HubSession) { + self.hub = hub + remoteSupported = true + guard prefs.enabled, ActivityAuthorizationInfo().areActivitiesEnabled else { + return + } + recoverActivities() + sessionsChanged(hub.sessionStore.sessions) + } + + func detach() { + endAll(policy: .immediate) + hub = nil + remoteSupported = true + } + + func appDidBecomeActive() { + guard prefs.enabled, let hub else { return } + remoteSupported = true + for (sessionId, activity) in activities { + if let token = activity.pushToken { + registerToken(token, sessionId: sessionId, force: true) + } + } + sessionsChanged(hub.sessionStore.sessions) + } + + func appDidBackground() { + // APNs is the only reliable background updater. Without it, a frozen + // lock-screen card is worse than no card. + guard !remoteSupported else { return } + endAll(policy: .immediate) + } + + func setEnabled(_ enabled: Bool) { + prefs.setEnabled(enabled) + if enabled { + guard let hub else { return } + sessionsChanged(hub.sessionStore.sessions) + } else { + endAll(policy: .immediate) + } + } + + // MARK: - Reconciliation + + func sessionsChanged(_ sessions: [SessionSummary]) { + guard prefs.enabled, hub != nil else { return } + guard ActivityAuthorizationInfo().areActivitiesEnabled else { return } + guard PushKeychain.ensurePushKey() != nil else { return } + + let tracked = sessions.filter { summary in + LiveActivityPolicy.isTracked( + active: summary.active, + thinking: summary.thinking, + pendingRequestsCount: summary.pendingRequestsCount + ) + } + let selected = select(tracked) + let selectedIds = Set(selected.map(\.id)) + + for (sessionId, activity) in activities where !selectedIds.contains(sessionId) { + let summary = sessions.first { $0.id == sessionId } + if let summary, !LiveActivityPolicy.isTracked( + active: summary.active, + thinking: summary.thinking, + pendingRequestsCount: summary.pendingRequestsCount + ) { + endActivity( + activity, + sessionId: sessionId, + finalState: finalState(for: summary, status: .done), + policy: .after(Date().addingTimeInterval(60)), + unregister: true + ) + } else { + // Over the local cap while still running: remove quietly; the + // hub's token row is cleaned up by the unregister call. + endActivity(activity, sessionId: sessionId, finalState: nil, policy: .immediate, unregister: true) + } + } + + for summary in selected { + reconcile(summary) + } + } + + private func reconcile(_ summary: SessionSummary) { + guard let hub, let key = PushKeychain.ensurePushKey() else { return } + let now = Self.nowMillis() + guard let status = LiveActivityPolicy.status( + active: summary.active, + thinking: summary.thinking, + pendingRequestsCount: summary.pendingRequestsCount, + pendingRequestKinds: Set(summary.pendingRequestKinds) + ) else { + if let activity = activities[summary.id] { + endActivity( + activity, + sessionId: summary.id, + finalState: finalState(for: summary, status: .done), + policy: .after(Date().addingTimeInterval(60)), + unregister: true + ) + } + return + } + + let state = LiveActivityContentState( + status: status, + title: SessionListSearch.sessionTitle(summary), + project: projectName(summary), + startedAt: turnStart(for: summary, now: now), + updatedAt: now, + pendingCount: summary.pendingRequestsCount, + todoCompleted: summary.todoProgress?.completed ?? 0, + todoTotal: summary.todoProgress?.total ?? 0, + backgroundTaskCount: summary.backgroundTaskCount + ) + let stateKey = Self.stateKey(state) + guard let encrypted = try? LiveActivityCipher.seal(state, key: key.data) else { + log.error("Could not encrypt Live Activity state") + return + } + let content = ActivityContent( + state: encrypted, + staleDate: Date().addingTimeInterval(120) + ) + + if let activity = activities[summary.id] { + guard lastStateKeys[summary.id] != stateKey else { return } + lastStateKeys[summary.id] = stateKey + Task { + await activity.update(content) + } + return + } + + let attributes = SessionActivityAttributes(sessionId: summary.id, hubUrl: hub.hubUrl) + do { + let activity = try Activity.request( + attributes: attributes, + content: content, + pushType: .token + ) + lastStateKeys[summary.id] = stateKey + activities[summary.id] = activity + observe(activity) + } catch let error as ActivityAuthorizationError { + if error == .targetMaximumExceeded { + log.error("ActivityKit target limit exceeded; trimming the lowest-priority activity") + trimForCapacity() + } else { + log.error("Activity.request failed: \(String(describing: error), privacy: .public)") + } + } catch { + log.error("Activity.request failed: \(String(describing: error), privacy: .public)") + } + } + + private func select(_ tracked: [SessionSummary]) -> [SessionSummary] { + tracked.sorted { lhs, rhs in + let lhsPriority = attentionPriority(lhs) + let rhsPriority = attentionPriority(rhs) + if lhsPriority != rhsPriority { return lhsPriority > rhsPriority } + return (lhs.lastUserMessageAt ?? lhs.updatedAt) > (rhs.lastUserMessageAt ?? rhs.updatedAt) + } + .prefix(maxActivities) + .map { $0 } + } + + private func attentionPriority(_ summary: SessionSummary) -> Int { + guard summary.pendingRequestsCount > 0 else { return 2 } + let kinds = Set(summary.pendingRequestKinds) + if kinds == [.input] { return 3 } + if kinds == [.permission] { return 4 } + return 5 + } + + /// `targetMaximumExceeded`: drop the lowest-priority current activity so + /// the next reconcile can start the one that just failed. + private func trimForCapacity() { + guard let hub else { return } + let ranked = activities.keys.sorted { lhs, rhs in + let lhsSummary = hub.sessionStore.sessions.first { $0.id == lhs } + let rhsSummary = hub.sessionStore.sessions.first { $0.id == rhs } + let lhsPriority = lhsSummary.map { attentionPriority($0) } ?? 0 + let rhsPriority = rhsSummary.map { attentionPriority($0) } ?? 0 + return lhsPriority < rhsPriority + } + guard let victim = ranked.first, let activity = activities[victim] else { return } + endActivity(activity, sessionId: victim, finalState: nil, policy: .immediate, unregister: true) + } + + private func turnStart(for summary: SessionSummary, now: Int) -> Int { + let lastUser = summary.lastUserMessageAt + if let lastUser, lastUserMessageAt[summary.id] != lastUser { + lastUserMessageAt[summary.id] = lastUser + startedAt[summary.id] = lastUser + return lastUser + } + if let existing = startedAt[summary.id], existing > 0 { return existing } + let start = lastUser ?? now + startedAt[summary.id] = start + return start + } + + private func projectName(_ summary: SessionSummary) -> String { + guard let path = summary.metadata?.path else { return "" } + return path.split(separator: "/").last.map(String.init) ?? "" + } + + private func finalState( + for summary: SessionSummary, + status: LiveActivityContentState.Status + ) -> LiveActivityContentState { + LiveActivityContentState( + status: status, + title: SessionListSearch.sessionTitle(summary), + project: projectName(summary), + startedAt: turnStart(for: summary, now: Self.nowMillis()), + updatedAt: Self.nowMillis(), + pendingCount: summary.pendingRequestsCount, + todoCompleted: summary.todoProgress?.completed ?? 0, + todoTotal: summary.todoProgress?.total ?? 0, + backgroundTaskCount: summary.backgroundTaskCount + ) + } + + // MARK: - Activity + token lifecycle + + private func observe(_ activity: Activity) { + let sessionId = activity.attributes.sessionId + + if let token = activity.pushToken { + registerToken(token, sessionId: sessionId, force: false) + } + tokenTasks[sessionId]?.cancel() + tokenTasks[sessionId] = Task { [weak self] in + for await token in activity.pushTokenUpdates { + guard let self else { return } + // A newer activity for the same session owns the registration + // now; do not let a stale token stream overwrite its token. + guard self.activities[sessionId]?.id == activity.id else { return } + self.registerToken(token, sessionId: sessionId, force: false) + } + } + stateTasks[sessionId]?.cancel() + stateTasks[sessionId] = Task { [weak self] in + for await state in activity.activityStateUpdates { + guard let self else { return } + if state == .ended || state == .dismissed { + guard self.activities[sessionId]?.id == activity.id else { return } + self.unregisterToken(sessionId: sessionId) + self.forget(sessionId) + return + } + } + } + } + + private func registerToken(_ token: Data, sessionId: String, force: Bool) { + guard let hub, let key = PushKeychain.ensurePushKey() else { return } + let hex = token.map { String(format: "%02x", $0) }.joined() + if !force, registeredTokens[sessionId] == hex { return } + registeredTokens[sessionId] = hex + let api = hub.api + let deviceId = PushKeychain.ensureDeviceId() + let pushKey = key.base64 + Task { + do { + let response = try await api.registerLiveActivityToken( + token: hex, + deviceId: deviceId, + sessionId: sessionId, + pushKey: pushKey + ) + remoteSupported = response.remote + if !response.remote { + log.info("Hub does not support remote Live Activity updates; will end on background") + } + } catch { + log.error("Live Activity token registration failed: \(String(describing: error), privacy: .public)") + } + } + } + + private func unregisterToken(sessionId: String) { + guard let hub, let token = registeredTokens.removeValue(forKey: sessionId) else { return } + let api = hub.api + Task { + try? await api.unregisterLiveActivityToken(token: token) + } + } + + private func endActivity( + _ activity: Activity, + sessionId: String, + finalState: LiveActivityContentState?, + policy: ActivityUIDismissalPolicy, + unregister: Bool + ) { + let api = hub?.api + let token = registeredTokens[sessionId] + let key = PushKeychain.ensurePushKey() + forget(sessionId) + Task { + if let finalState, + let key, + let encrypted = try? LiveActivityCipher.seal(finalState, key: key.data) { + await activity.end( + ActivityContent(state: encrypted, staleDate: nil), + dismissalPolicy: policy + ) + } else { + await activity.end(nil, dismissalPolicy: policy) + } + // Unregister only the token this activity owned. Deleting by + // device/session could race a new turn's fresh registration. + guard unregister, let api, let token else { return } + try? await api.unregisterLiveActivityToken(token: token) + } + } + + private func endAll(policy: ActivityUIDismissalPolicy) { + let snapshot = activities + activities.removeAll() + for (sessionId, activity) in snapshot { + endActivity(activity, sessionId: sessionId, finalState: nil, policy: policy, unregister: true) + } + for task in tokenTasks.values { task.cancel() } + for task in stateTasks.values { task.cancel() } + tokenTasks.removeAll() + stateTasks.removeAll() + registeredTokens.removeAll() + startedAt.removeAll() + lastUserMessageAt.removeAll() + lastStateKeys.removeAll() + } + + private func forget(_ sessionId: String) { + activities.removeValue(forKey: sessionId) + tokenTasks.removeValue(forKey: sessionId)?.cancel() + stateTasks.removeValue(forKey: sessionId)?.cancel() + registeredTokens.removeValue(forKey: sessionId) + startedAt.removeValue(forKey: sessionId) + lastUserMessageAt.removeValue(forKey: sessionId) + lastStateKeys.removeValue(forKey: sessionId) + } + + private func recoverActivities() { + guard let hub else { return } + let key = PushKeychain.ensurePushKey() + for activity in Activity.activities { + let sessionId = activity.attributes.sessionId + guard activity.attributes.hubUrl == hub.hubUrl, + activity.activityState == .active || activity.activityState == .stale else { + Task { await activity.end(nil, dismissalPolicy: .immediate) } + continue + } + activities[sessionId] = activity + if let key, + let state = try? LiveActivityCipher.open(activity.content.state, key: key.data) { + startedAt[sessionId] = state.startedAt + lastStateKeys[sessionId] = Self.stateKey(state) + } + observe(activity) + } + } + + private static func nowMillis() -> Int { + Int(Date().timeIntervalSince1970 * 1000) + } + + private static func stateKey(_ state: LiveActivityContentState) -> String { + [ + state.status.rawValue, + state.title, + state.project, + String(state.startedAt), + String(state.pendingCount), + String(state.todoCompleted), + String(state.todoTotal), + String(state.backgroundTaskCount) + ].joined(separator: "|") + } +} +#endif diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index b6437791..48c90f8f 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -249,13 +249,23 @@ struct SettingsView: View { PushCoordinator.shared.reregisterAll() } } + Toggle( + "Live Activities", + isOn: Binding( + get: { appModel.liveActivityPrefs.enabled }, + set: { appModel.setLiveActivitiesEnabled($0) } + ) + ) } header: { Text("Notifications") } footer: { - if let problem = push.lastRegistrationProblem { - Text(problem) - } else { - Text("Pushes are end-to-end encrypted; only this device can read them.") + VStack(alignment: .leading, spacing: 4) { + if let problem = push.lastRegistrationProblem { + Text(problem) + } else { + Text("Pushes are end-to-end encrypted; only this device can read them.") + } + Text("Live Activities show running sessions on the Lock Screen; their content is end-to-end encrypted too.") } } } diff --git a/ios/Hapi/HapiApp.swift b/ios/Hapi/HapiApp.swift index 823fbbc9..3cadaf7c 100644 --- a/ios/Hapi/HapiApp.swift +++ b/ios/Hapi/HapiApp.swift @@ -32,14 +32,21 @@ struct HapiApp: App { /// through `AppModel`: unpaired → pairing confirm; already paired to that /// hub → switch with a notice; a different hub → add-hub confirm. /// - /// Never log the URL itself: the query carries the access token. + /// Live Activities open `hapicompanion://sessions/[?hub=]`; + /// that form is routed through the same notification-target path. + /// + /// Never log the URL itself: the bind query carries the access token. private func handleIncomingURL(_ url: URL) { - guard let link = BindLink.parse(url.absoluteString) else { - log.warning("Ignoring malformed URL (scheme: \(url.scheme ?? "none", privacy: .public))") + if let link = BindLink.parse(url.absoluteString) { + if !model.handleBindLink(link) { + log.warning("Bind link carried an unusable hub URL") + } return } - if !model.handleBindLink(link) { - log.warning("Bind link carried an unusable hub URL") + if let link = SessionLink.parse(url.absoluteString) { + model.handleSessionLink(link) + return } + log.warning("Ignoring malformed URL (scheme: \(url.scheme ?? "none", privacy: .public))") } } diff --git a/ios/Hapi/Info.plist b/ios/Hapi/Info.plist index 3846cffb..09198646 100644 --- a/ios/Hapi/Info.plist +++ b/ios/Hapi/Info.plist @@ -11,6 +11,8 @@ ITSAppUsesNonExemptEncryption + NSSupportsLiveActivities + NSCameraUsageDescription HAPI uses the camera to scan your hub's pairing QR code and to capture photos you attach to messages. NSMicrophoneUsageDescription diff --git a/ios/Hapi/Models/AppModel.swift b/ios/Hapi/Models/AppModel.swift index f808d98b..b7249f77 100644 --- a/ios/Hapi/Models/AppModel.swift +++ b/ios/Hapi/Models/AppModel.swift @@ -52,6 +52,8 @@ final class AppModel { // `let` storage is inert under @Observable (no annotation needed). let registry: HubRegistry + let liveActivityPrefs: LiveActivityPrefs + let liveActivity: any LiveActivityControlling private let credentialStore: any CredentialStoring private let performer: any HTTPPerforming private let pairingService: HubPairingService @@ -72,6 +74,9 @@ final class AppModel { credentialStore: credentialStore, performer: performer ) + let liveActivityPrefs = LiveActivityPrefs() + self.liveActivityPrefs = liveActivityPrefs + self.liveActivity = LiveActivityControllerFactory.make(prefs: liveActivityPrefs) restore() // Push wiring (P3): the coordinator is a process singleton (UIKit // delegates outlive any model); it pulls navigation + suppression @@ -142,6 +147,8 @@ final class AppModel { func signOut(hub: String) { let wasActive = state == .paired(activeHub: hub) if wasActive { + // End + unregister while the old hub's API still works. + liveActivity.detach() session?.shutdown() session = nil } @@ -199,6 +206,16 @@ final class AppModel { return true } + /// Live Activity tap-through (`hapicompanion://sessions/[?hub=]`). + /// Reuses the notification-tap route: switch to the owning hub only when + /// it is paired, then let the home screen consume `pendingOpenSessionId`. + @discardableResult + func handleSessionLink(_ link: SessionLink) -> Bool { + let hub = link.hubUrl.flatMap { HubURLNormalization.normalize($0) } + openNotificationTarget(sessionId: link.sessionId, hubUrl: hub) + return true + } + // MARK: - App lifecycle /// Forwarded from the scene: foreground starts/resumes the active @@ -208,11 +225,13 @@ final class AppModel { case .active: isForeground = true session?.enterForeground() + liveActivity.appDidBecomeActive() // Re-registers every hub when the APNs token arrives — the // cheap-upsert healing pass (Android registrar `start()`). PushCoordinator.shared.appDidBecomeActive(isPaired: state != .unpaired) case .background: isForeground = false + liveActivity.appDidBackground() session?.enterBackground() case .inactive: break // transitional; no connection changes @@ -221,11 +240,22 @@ final class AppModel { } } + /// Settings toggle. The coordinator owns ending/starting activities so + /// the pref and the live activities never disagree. + func setLiveActivitiesEnabled(_ enabled: Bool) { + liveActivity.setEnabled(enabled) + } + // MARK: - Internals /// Builds (and starts, when foregrounded) the session for `hub`, /// replacing any previous one. private func activate(hub: String) { + if let current = session, current.hubUrl != hub { + // End the old hub's activities and unregister their tokens while + // its API is still live; the new hub gets a fresh registration. + liveActivity.detach() + } let previousStore = session?.lastSeenStore session?.shutdown() session = nil @@ -259,9 +289,16 @@ final class AppModel { newSession.onTerminalAuthFailure = { [weak self] in self?.handleTerminalAuthFailure(for: hub) } + newSession.sessionStore.onSessionsChanged = { [weak self, weak newSession] sessions in + // A refresh that lands after a hub switch must not repopulate the + // new hub's coordinator with the old hub's sessions. + guard let self, let newSession, self.session === newSession else { return } + self.liveActivity.sessionsChanged(sessions) + } session = newSession state = .paired(activeHub: hub) hubs = registry.hubs + liveActivity.attach(to: newSession) if isForeground { newSession.enterForeground() } @@ -272,6 +309,7 @@ final class AppModel { /// revoked, so the dead credentials are removed and the UI drops to /// pairing (or the next hub) with a banner. private func handleTerminalAuthFailure(for hub: String) { + liveActivity.detach() session = nil // the session shut itself down before calling back authFailureNotice = hub // No JWT left to authenticate a push unregister; just drop the hub diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 1041ae29..001a2594 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -5707,6 +5707,40 @@ } } }, + "Live Activities" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Live-активности" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "实时活动" + } + } + } + }, + "Live Activities show running sessions on the Lock Screen; their content is end-to-end encrypted too." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Live-активности показывают запущенные сеансы на экране блокировки; их содержимое также защищено сквозным шифрованием." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "实时活动会在锁定屏幕上显示正在运行的会话;其内容同样采用端到端加密。" + } + } + } + }, "Live updates interrupted — reconnecting…" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/HapiTests/LiveActivityRoutingTests.swift b/ios/HapiTests/LiveActivityRoutingTests.swift new file mode 100644 index 00000000..49afcac7 --- /dev/null +++ b/ios/HapiTests/LiveActivityRoutingTests.swift @@ -0,0 +1,41 @@ +import HapiClient +import HapiProtocol +import XCTest +@testable import Hapi + +/// Live Activity tap-through uses the same notification-target path as a push +/// tap; the hub hint is only honored when it is already paired. +@MainActor +final class LiveActivityRoutingTests: XCTestCase { + private func makeModel() -> (AppModel, UserDefaults, String) { + let suiteName = "LiveActivityRoutingTests-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suiteName)! + let model = AppModel( + registry: HubRegistry(defaults: defaults), + credentialStore: InMemoryCredentialStore() + ) + return (model, defaults, suiteName) + } + + func testSessionLinkSetsPendingOpenSessionId() { + let (model, defaults, suiteName) = makeModel() + defer { defaults.removePersistentDomain(forName: suiteName) } + + model.handleSessionLink(SessionLink( + sessionId: "sess-1", + hubUrl: "https://hub.example.com" + )) + + XCTAssertEqual(model.pendingOpenSessionId, "sess-1") + XCTAssertEqual(model.state, .unpaired) + } + + func testUnpairedHubHintFallsBackToTheActiveHub() { + let (model, defaults, suiteName) = makeModel() + defer { defaults.removePersistentDomain(forName: suiteName) } + + model.handleSessionLink(SessionLink(sessionId: "sess-2", hubUrl: nil)) + + XCTAssertEqual(model.pendingOpenSessionId, "sess-2") + } +} diff --git a/ios/HapiWidgets/HapiWidgets.entitlements b/ios/HapiWidgets/HapiWidgets.entitlements new file mode 100644 index 00000000..9298dec1 --- /dev/null +++ b/ios/HapiWidgets/HapiWidgets.entitlements @@ -0,0 +1,10 @@ + + + + + keychain-access-groups + + $(AppIdentifierPrefix)run.hapi.companion.push + + + diff --git a/ios/HapiWidgets/HapiWidgetsBundle.swift b/ios/HapiWidgets/HapiWidgetsBundle.swift new file mode 100644 index 00000000..420518b3 --- /dev/null +++ b/ios/HapiWidgets/HapiWidgetsBundle.swift @@ -0,0 +1,9 @@ +import SwiftUI +import WidgetKit + +@main +struct HapiWidgetsBundle: WidgetBundle { + var body: some Widget { + SessionLiveActivityWidget() + } +} diff --git a/ios/HapiWidgets/Info.plist b/ios/HapiWidgets/Info.plist new file mode 100644 index 00000000..0f118fb7 --- /dev/null +++ b/ios/HapiWidgets/Info.plist @@ -0,0 +1,11 @@ + + + + + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/ios/HapiWidgets/Localizable.xcstrings b/ios/HapiWidgets/Localizable.xcstrings new file mode 100644 index 00000000..a3214748 --- /dev/null +++ b/ios/HapiWidgets/Localizable.xcstrings @@ -0,0 +1,159 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "Done" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Готово" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "完成" + } + } + } + }, + "Error" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ошибка" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "错误" + } + } + } + }, + "Needs approval" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Требуется одобрение" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "需要批准" + } + } + } + }, + "Needs attention" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Требуется внимание" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "需要关注" + } + } + } + }, + "Needs input" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Требуется ответ" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "需要回复" + } + } + } + }, + "Open HAPI" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Открыть HAPI" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "打开 HAPI" + } + } + } + }, + "Open the app to view this session." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Откройте приложение, чтобы посмотреть сеанс." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "打开应用查看此会话。" + } + } + } + }, + "Paused" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Приостановлено" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已暂停" + } + } + } + }, + "Working" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Работает" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "运行中" + } + } + } + } + }, + "version" : "1.0" +} diff --git a/ios/HapiWidgets/SessionLiveActivityWidget.swift b/ios/HapiWidgets/SessionLiveActivityWidget.swift new file mode 100644 index 00000000..d309ea10 --- /dev/null +++ b/ios/HapiWidgets/SessionLiveActivityWidget.swift @@ -0,0 +1,242 @@ +import ActivityKit +import HapiProtocol +import SwiftUI +import WidgetKit + +/// Lock-screen + Dynamic Island surface for one HAPI session. +/// +/// The APNs `content-state` is an encrypted envelope; the widget extension +/// decrypts it with the shared per-install push key and renders this view. +/// No plaintext names or counts ever travel through APNs. +struct SessionLiveActivityWidget: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: SessionActivityAttributes.self) { context in + SessionActivityLockScreen( + state: Self.decrypt(context.state), + isStale: context.isStale + ) + .widgetURL(SessionLink.url( + sessionId: context.attributes.sessionId, + hubUrl: context.attributes.hubUrl + )) + } dynamicIsland: { context in + let state = Self.decrypt(context.state) + let color = Self.statusColor(state?.status) + return DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + VStack(alignment: .leading, spacing: 2) { + Text(state?.title ?? "HAPI") + .font(.headline) + .lineLimit(1) + if let project = state?.project, !project.isEmpty { + Text(project) + .font(.caption2) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + } + DynamicIslandExpandedRegion(.trailing) { + if let state { + ElapsedText(startedAt: state.startedAt) + .font(.headline.monospacedDigit()) + } + } + DynamicIslandExpandedRegion(.center) { + if let status = state?.status { + StatusBadge(status: status, isStale: context.isStale) + } else { + Text("Open HAPI") + .font(.caption) + .foregroundStyle(.secondary) + } + } + DynamicIslandExpandedRegion(.bottom) { + if let state { + ActivityCounts(state: state) + .font(.caption2) + } + } + } compactLeading: { + Circle() + .fill(color) + .frame(width: 8, height: 8) + } compactTrailing: { + if let state { + ElapsedText(startedAt: state.startedAt) + .font(.caption2.monospacedDigit()) + } else { + Image(systemName: "waveform") + .font(.caption2) + } + } minimal: { + Circle() + .fill(color) + .frame(width: 8, height: 8) + } + } + } + + private static func decrypt(_ state: EncryptedLiveActivityState) -> LiveActivityContentState? { + guard let key = WidgetKeychain.pushKey() else { return nil } + return try? LiveActivityCipher.open(state, key: key) + } + + private static func statusColor(_ status: LiveActivityContentState.Status?) -> Color { + switch status { + case .working: return .blue + case .needsApproval: return .orange + case .needsInput: return .purple + case .needsAttention: return .red + case .done: return .green + case .error: return .red + case nil: return .gray + } + } +} + +private struct SessionActivityLockScreen: View { + let state: LiveActivityContentState? + let isStale: Bool + + var body: some View { + Group { + if let state { + VStack(alignment: .leading, spacing: 8) { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Circle() + .fill(color(for: state.status)) + .frame(width: 9, height: 9) + Text(state.title) + .font(.headline) + .lineLimit(1) + Spacer(minLength: 8) + ElapsedText(startedAt: state.startedAt) + .font(.headline.monospacedDigit()) + } + + HStack(spacing: 8) { + if !state.project.isEmpty { + Label(state.project, systemImage: "folder") + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Spacer(minLength: 4) + StatusBadge(status: state.status, isStale: isStale) + } + + ActivityCounts(state: state) + .font(.caption2) + } + .padding(.horizontal, 4) + } else { + VStack(alignment: .leading, spacing: 6) { + Text("HAPI") + .font(.headline) + Text("Open the app to view this session.") + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .accessibilityElement(children: .combine) + } + + private func color(for status: LiveActivityContentState.Status) -> Color { + switch status { + case .working: return .blue + case .needsApproval: return .orange + case .needsInput: return .purple + case .needsAttention: return .red + case .done: return .green + case .error: return .red + } + } +} + +private struct ElapsedText: View { + let startedAt: Int + + var body: some View { + let start = Date(timeIntervalSince1970: Double(startedAt) / 1000) + Text(timerInterval: min(start, Date())...Date.distantFuture, countsDown: false) + } +} + +private struct StatusBadge: View { + let status: LiveActivityContentState.Status + let isStale: Bool + + var body: some View { + Label(label, systemImage: symbol) + .font(.caption2.weight(.semibold)) + .foregroundStyle(isStale ? Color.secondary : color) + .lineLimit(1) + } + + private var label: String { + if isStale { return String(localized: "Paused") } + switch status { + case .working: return String(localized: "Working") + case .needsApproval: return String(localized: "Needs approval") + case .needsInput: return String(localized: "Needs input") + case .needsAttention: return String(localized: "Needs attention") + case .done: return String(localized: "Done") + case .error: return String(localized: "Error") + } + } + + private var symbol: String { + if isStale { return "pause.circle" } + switch status { + case .working: return "gearshape.2.fill" + case .needsApproval: return "hand.raised.fill" + case .needsInput: return "bubble.left.fill" + case .needsAttention: return "exclamationmark.bubble.fill" + case .done: return "checkmark.circle.fill" + case .error: return "xmark.octagon.fill" + } + } + + private var color: Color { + switch status { + case .working: return .blue + case .needsApproval: return .orange + case .needsInput: return .purple + case .needsAttention: return .red + case .done: return .green + case .error: return .red + } + } +} + +private struct ActivityCounts: View { + let state: LiveActivityContentState + + var body: some View { + HStack(spacing: 10) { + if state.pendingCount > 0 { + Label("\(state.pendingCount)", systemImage: "hand.raised.fill") + .foregroundStyle(.orange) + } + if state.todoTotal > 0 { + HStack(spacing: 4) { + ProgressView( + value: Double(state.todoCompleted), + total: Double(max(state.todoTotal, 1)) + ) + .frame(width: 48) + Text("\(state.todoCompleted)/\(state.todoTotal)") + .monospacedDigit() + } + } + if state.backgroundTaskCount > 0 { + Label("\(state.backgroundTaskCount)", systemImage: "gearshape.2.fill") + } + Spacer(minLength: 0) + } + .foregroundStyle(.secondary) + } +} diff --git a/ios/HapiWidgets/WidgetKeychain.swift b/ios/HapiWidgets/WidgetKeychain.swift new file mode 100644 index 00000000..0c02a833 --- /dev/null +++ b/ios/HapiWidgets/WidgetKeychain.swift @@ -0,0 +1,30 @@ +import Foundation +import Security + +/// Read-only Keychain access to the per-install push key shared with the app +/// and the Notification Service Extension. +/// +/// The widget target carries the same `run.hapi.companion.push` Keychain +/// access group. No `kSecAttrAccessGroup` is passed: Foundation reads the +/// first accessible group, matching the app/NSE lookup. Items are stored +/// `kSecAttrAccessibleAfterFirstUnlock`, so this works while the phone is +/// locked after its first unlock since boot. +enum WidgetKeychain { + static let service = "run.hapi.companion.push" + static let pushKeyAccount = "pushKey" + + static func pushKey() -> Data? { + let query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: pushKeyAccount, + kSecReturnData as String: true, + kSecMatchLimit as String: kSecMatchLimitOne + ] + var item: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess else { + return nil + } + return item as? Data + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LiveActivityEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LiveActivityEndpoints.swift new file mode 100644 index 00000000..1d2e1f30 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/LiveActivityEndpoints.swift @@ -0,0 +1,71 @@ +import Foundation + +/// Response of `POST /api/live-activities/register`. +/// +/// `remote` is false when the hub is not in direct-APNs mode: the app can +/// still show a local activity while it runs, but no remote updates will +/// arrive, so it should end on background / use a short stale date. +public struct LiveActivityRegistrationResponse: Decodable, Equatable, Sendable { + public let ok: Bool + public let remote: Bool + + public init(ok: Bool, remote: Bool) { + self.ok = ok + self.remote = remote + } +} + +extension APIClient { + /// `POST /api/live-activities/register` — upserts the per-activity APNs + /// token for a session. The hub encrypts future content-state pushes + /// with `pushKey` (the same per-install E2E key used by alert pushes). + public func registerLiveActivityToken( + token: String, + deviceId: String, + sessionId: String, + pushKey: String + ) async throws -> LiveActivityRegistrationResponse { + struct RegisterRequest: Encodable { + let token: String + let deviceId: String + let sessionId: String + let pushKey: String + } + return try await request( + .post, + "/api/live-activities/register", + body: RegisterRequest( + token: token, + deviceId: deviceId, + sessionId: sessionId, + pushKey: pushKey + ) + ) + } + + /// `DELETE /api/live-activities/register` by activity token. + public func unregisterLiveActivityToken(token: String) async throws { + struct UnregisterRequest: Encodable { + let token: String + } + try await requestVoid( + .delete, + "/api/live-activities/register", + body: UnregisterRequest(token: token) + ) + } + + /// `DELETE /api/live-activities/register` by device/session (used when + /// the activity ended before its token arrived). + public func unregisterLiveActivityTokens(deviceId: String, sessionId: String) async throws { + struct UnregisterRequest: Encodable { + let deviceId: String + let sessionId: String + } + try await requestVoid( + .delete, + "/api/live-activities/register", + body: UnregisterRequest(deviceId: deviceId, sessionId: sessionId) + ) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Settings/LiveActivityPrefs.swift b/ios/Packages/HapiKit/Sources/HapiClient/Settings/LiveActivityPrefs.swift new file mode 100644 index 00000000..00e83688 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Settings/LiveActivityPrefs.swift @@ -0,0 +1,26 @@ +import Foundation + +/// Install-global Live Activity preference (Settings → Notifications). +/// +/// Defaults to enabled; the coordinator also checks the system's +/// `ActivityAuthorizationInfo`, so a user who disabled Live Activities in +/// iOS settings is handled separately. Corrupt/missing storage reads as the +/// default, matching the other prefs stores. +@MainActor @Observable +public final class LiveActivityPrefs { + public private(set) var enabled: Bool + + private let defaults: UserDefaults + + public static let enabledKey = "settings.liveActivities" + + public init(defaults: UserDefaults = .standard) { + self.defaults = defaults + self.enabled = defaults.object(forKey: Self.enabledKey) as? Bool ?? true + } + + public func setEnabled(_ enabled: Bool) { + self.enabled = enabled + defaults.set(enabled, forKey: Self.enabledKey) + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift index 0f9837a7..bedafb44 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Stores/SessionListStore.swift @@ -95,6 +95,13 @@ public final class SessionListStore: SessionListStoring { /// for the Android `SessionStore.scratchlistInvalidations` flow). @ObservationIgnored public var onScratchlistInvalidation: (@MainActor (String) -> Void)? + /// Fired after every real list mutation (SSE, REST refresh, optimistic + /// pin/archive/reopen). The app's Live Activity coordinator uses this + /// single seam to reconcile activities; keep-alive-only patches never + /// reach it. Cold-start snapshot hydration is reconciled by the + /// coordinator when it attaches to the hub. + @ObservationIgnored public var onSessionsChanged: (@MainActor ([SessionSummary]) -> Void)? + /// Authoritative removal only: SSE from either pipe, or a successful /// archive/delete. Optimistic list removal/rollback, filters and failed refreshes /// must not dismiss a client's currently selected session. @@ -428,5 +435,6 @@ public final class SessionListStore: SessionListStoring { sessions = next listRevision += 1 snapshot?.scheduleWrite(next) + onSessionsChanged?(next) } } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/LiveActivityCipher.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/LiveActivityCipher.swift new file mode 100644 index 00000000..a76a93fa --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/LiveActivityCipher.swift @@ -0,0 +1,126 @@ +#if canImport(CryptoKit) +import CryptoKit +#endif +import Foundation + +/// Why a Live Activity content-state envelope could not be opened. +public enum LiveActivityCipherError: Error, Equatable, Sendable { + case invalidKeyLength + case malformedEnvelope + case unsupportedVersion + case authenticationFailed + case invalidJSON + case cryptoUnavailable +} + +/// AES-256-GCM envelope for Live Activity `content-state`. +/// +/// The wire shape is deliberately identical to the push envelope +/// (`base64(nonce || ciphertext || tag)`), but the AAD is domain-separated +/// (`hapi-live-activity-v1`) so ciphertexts cannot be replayed between the +/// notification and Live Activity channels. +/// +/// The plaintext is canonical JSON (sorted keys, no whitespace) of +/// ``LiveActivityContentState``. The hub has a byte-compatible TypeScript +/// producer; `shared/fixtures/live-activity/content-state-v1.json` pins the +/// cross-language vector. +public enum LiveActivityCipher { + public static let aad = "hapi-live-activity-v1" + public static let keyLength = 32 + public static let nonceLength = 12 + public static let tagLength = 16 + + /// Encrypts `state` into the APNs `content-state` wrapper. + /// + /// `nonce` is injectable only for tests / golden-vector generation; + /// production callers must let it default to 12 fresh random bytes. + public static func seal( + _ state: LiveActivityContentState, + key: Data, + nonce: Data? = nil + ) throws -> EncryptedLiveActivityState { + guard key.count == keyLength else { + throw LiveActivityCipherError.invalidKeyLength + } + let plaintext = try canonicalJSON(state) + let nonceData = nonce ?? randomNonce() + guard nonceData.count == nonceLength else { + throw LiveActivityCipherError.malformedEnvelope + } + #if canImport(CryptoKit) + do { + let box = try AES.GCM.seal( + plaintext, + using: SymmetricKey(data: key), + nonce: AES.GCM.Nonce(data: nonceData), + authenticating: Data(aad.utf8) + ) + let envelope = nonceData + box.ciphertext + box.tag + return EncryptedLiveActivityState(e: envelope.base64EncodedString()) + } catch { + throw LiveActivityCipherError.authenticationFailed + } + #else + throw LiveActivityCipherError.cryptoUnavailable + #endif + } + + /// Decrypts the wrapper carried in an APNs `content-state`. + public static func open( + _ envelope: EncryptedLiveActivityState, + key: Data + ) throws -> LiveActivityContentState { + guard envelope.v == EncryptedLiveActivityState.currentVersion else { + throw LiveActivityCipherError.unsupportedVersion + } + guard key.count == keyLength else { + throw LiveActivityCipherError.invalidKeyLength + } + guard let raw = Data(base64Encoded: envelope.e), + raw.count >= nonceLength + tagLength else { + throw LiveActivityCipherError.malformedEnvelope + } + #if canImport(CryptoKit) + let nonceBytes = raw.subdata(in: 0.. Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return try encoder.encode(state) + } + + private static func randomNonce() -> Data { + var generator = SystemRandomNumberGenerator() + var bytes = Data(capacity: nonceLength) + for _ in 0.. summary -> promptTitle -> path -> id`). + public var title: String + /// Project basename for the lock-screen row. + public var project: String + /// Epoch ms when the current turn started. + public var startedAt: Int + /// Epoch ms when this state was produced. + public var updatedAt: Int + public var pendingCount: Int + public var todoCompleted: Int + public var todoTotal: Int + public var backgroundTaskCount: Int + + public init( + status: Status, + title: String, + project: String, + startedAt: Int, + updatedAt: Int, + pendingCount: Int = 0, + todoCompleted: Int = 0, + todoTotal: Int = 0, + backgroundTaskCount: Int = 0 + ) { + self.status = status + self.title = title + self.project = project + self.startedAt = startedAt + self.updatedAt = updatedAt + self.pendingCount = pendingCount + self.todoCompleted = todoCompleted + self.todoTotal = todoTotal + self.backgroundTaskCount = backgroundTaskCount + } + + /// Tolerant decode for counter fields: a future hub may omit a count + /// without making the whole activity unreadable. Status stays strict. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + status = try container.decode(Status.self, forKey: .status) + title = try container.decode(String.self, forKey: .title) + project = try container.decode(String.self, forKey: .project) + startedAt = try container.decode(Int.self, forKey: .startedAt) + updatedAt = try container.decode(Int.self, forKey: .updatedAt) + pendingCount = try container.decodeIfPresent(Int.self, forKey: .pendingCount) ?? 0 + todoCompleted = try container.decodeIfPresent(Int.self, forKey: .todoCompleted) ?? 0 + todoTotal = try container.decodeIfPresent(Int.self, forKey: .todoTotal) ?? 0 + backgroundTaskCount = try container.decodeIfPresent(Int.self, forKey: .backgroundTaskCount) ?? 0 + } +} + +/// The APNs-carried wrapper: an AES-256-GCM envelope over canonical JSON of +/// ``LiveActivityContentState``. The system only needs this to be Codable; +/// the widget extension opens it with the shared per-install push key. +public struct EncryptedLiveActivityState: Codable, Hashable, Sendable { + public static let currentVersion = 1 + + public var v: Int + /// base64(nonce[12] || ciphertext || tag[16]). + public var e: String + + public init(v: Int = EncryptedLiveActivityState.currentVersion, e: String) { + self.v = v + self.e = e + } +} + +/// Pure, shared state mapping used by the app coordinator and tests. +/// +/// The hub has a TypeScript counterpart for the same precedence; keep the +/// two in sync and cover both with the shared golden fixture. +public enum LiveActivityPolicy { + /// A session gets a Live Activity while it is working or waiting for a + /// human. Inactive/settled sessions do not. + public static func isTracked( + active: Bool, + thinking: Bool, + pendingRequestsCount: Int + ) -> Bool { + active && (thinking || pendingRequestsCount > 0) + } + + /// Pending requests win over `working`, matching `SessionRowStatus`. + /// Returns nil for a settled session (the caller ends its activity). + public static func status( + active: Bool, + thinking: Bool, + pendingRequestsCount: Int, + pendingRequestKinds: Set + ) -> LiveActivityContentState.Status? { + guard active else { return nil } + if pendingRequestsCount > 0 { + if pendingRequestKinds == [.input] { return .needsInput } + if pendingRequestKinds == [.permission] { return .needsApproval } + return .needsAttention + } + return thinking ? .working : nil + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/SessionActivityAttributes.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/SessionActivityAttributes.swift new file mode 100644 index 00000000..c2bd7082 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/LiveActivity/SessionActivityAttributes.swift @@ -0,0 +1,28 @@ +import Foundation + +#if os(iOS) && !targetEnvironment(macCatalyst) +import ActivityKit +#endif + +/// Static attributes for one session's Live Activity. +/// +/// Declared unconditionally so macOS/Linux package tests can construct it; +/// the `ActivityAttributes` conformance is only compiled for iOS (not +/// Catalyst), where ActivityKit is actually available. `hubUrl` stays local: +/// it is not part of any APNs payload, and lets a recovered activity end +/// itself after a hub switch and build the right deep link. +public struct SessionActivityAttributes: Codable, Hashable, Sendable { + public var sessionId: String + public var hubUrl: String + + public init(sessionId: String, hubUrl: String) { + self.sessionId = sessionId + self.hubUrl = hubUrl + } +} + +#if os(iOS) && !targetEnvironment(macCatalyst) +extension SessionActivityAttributes: ActivityAttributes { + public typealias ContentState = EncryptedLiveActivityState +} +#endif diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift index efc793e7..cec23e68 100644 --- a/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Models/SessionSummary.swift @@ -1,7 +1,7 @@ import Foundation /// Classification of a pending request for list badges. -public enum PendingRequestKind: String, Codable, Sendable { +public enum PendingRequestKind: String, Codable, Hashable, Sendable { case permission case input } diff --git a/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/SessionLink.swift b/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/SessionLink.swift new file mode 100644 index 00000000..e4c2b64f --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiProtocol/Pairing/SessionLink.swift @@ -0,0 +1,99 @@ +import Foundation + +/// Parsed session deep link opened by a Live Activity (or a notification +/// action that wants to reuse the same route). +/// +/// hapicompanion://sessions/[?hub=] +/// +/// `hub` is a hint, not an authority: the app only switches to a hub that is +/// already paired and has credentials (the same guard as notification taps). +/// A blank or non-http(s) hint is ignored rather than rejecting the whole +/// link, so the session can still open on the active hub. +public struct SessionLink: Equatable, Sendable { + public let sessionId: String + /// The hub URL exactly as carried by the link (decoded, not normalized — + /// hub normalization is the client layer's job). + public let hubUrl: String? + + public init(sessionId: String, hubUrl: String? = nil) { + self.sessionId = sessionId + self.hubUrl = hubUrl + } + + public static let scheme = "hapicompanion" + public static let host = "sessions" + + /// Parses the link; nil on malformed input (wrong scheme/host, missing + /// or oversized id, invalid percent escapes). + public static func parse(_ raw: String) -> SessionLink? { + let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty, + let components = URLComponents(string: trimmed), + components.scheme?.lowercased() == Self.scheme, + components.host?.lowercased() == Self.host, + hasValidPercentEncoding(components.percentEncodedPath), + let decodedPath = components.percentEncodedPath.removingPercentEncoding else { + return nil + } + let parts = decodedPath.split(separator: "/", omittingEmptySubsequences: true) + guard parts.count == 1 else { return nil } + let sessionId = String(parts[0]) + guard !sessionId.isEmpty, + sessionId.count <= 256, + !sessionId.contains("%"), + sessionId.trimmingCharacters(in: .whitespacesAndNewlines) == sessionId else { + return nil + } + + let hub = components.queryItems? + .first(where: { $0.name == "hub" })? + .value? + .trimmingCharacters(in: .whitespacesAndNewlines) + let validHub = hub.flatMap { isHTTPURL($0) ? $0 : nil } + return SessionLink(sessionId: sessionId, hubUrl: validHub) + } + + /// The value the widget puts in `.widgetURL`. + public static func url(sessionId: String, hubUrl: String?) -> URL? { + var components = URLComponents() + components.scheme = Self.scheme + components.host = Self.host + components.path = "/\(sessionId)" + if let hubUrl { + components.queryItems = [URLQueryItem(name: "hub", value: hubUrl)] + } + return components.url + } + + private static func isHTTPURL(_ value: String) -> Bool { + guard let components = URLComponents(string: value), + let scheme = components.scheme?.lowercased(), + scheme == "http" || scheme == "https", + let host = components.host, !host.isEmpty else { + return false + } + return true + } + + /// `URLComponents` tolerates a malformed escape in the path (it may + /// leave `%zz` intact), so validate before asking Foundation to decode. + private static func hasValidPercentEncoding(_ value: String) -> Bool { + var index = value.startIndex + while index < value.endIndex { + guard value[index] == "%" else { + index = value.index(after: index) + continue + } + let first = value.index(after: index) + guard first < value.endIndex else { return false } + let second = value.index(after: first) + guard second < value.endIndex, + value[first].isHexDigit, + value[second].isHexDigit else { + return false + } + index = value.index(after: second) + } + return true + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/LiveActivityEndpointTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/LiveActivityEndpointTests.swift new file mode 100644 index 00000000..c4501eab --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/LiveActivityEndpointTests.swift @@ -0,0 +1,48 @@ +import Foundation +import HapiClient +import Testing + +@Suite("Live Activity endpoints") +struct LiveActivityEndpointTests { + private func bodyString(_ request: URLRequest?) -> String? { + request?.httpBody.flatMap { String(data: $0, encoding: .utf8) } + } + + private let token = String(repeating: "aa", count: 32) + + @Test func registersWithDeviceSessionAndPushKey() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: #"{"ok":true,"remote":true}"#) + + let response = try await harness.client.registerLiveActivityToken( + token: token, + deviceId: "dev-1", + sessionId: "sess-1", + pushKey: "key" + ) + + #expect(response == LiveActivityRegistrationResponse(ok: true, remote: true)) + let request = await harness.performer.requests.first + #expect(request?.url?.absoluteString == "\(testHubURLString)/api/live-activities/register") + #expect(request?.httpMethod == "POST") + #expect( + bodyString(request) + == "{\"deviceId\":\"dev-1\",\"pushKey\":\"key\",\"sessionId\":\"sess-1\",\"token\":\"\(token)\"}" + ) + } + + @Test func unregistersByTokenOrDeviceSession() async throws { + let harness = try makeHarness(jwt: freshJWT()) + await harness.performer.enqueue(json: "{}") + await harness.performer.enqueue(json: "{}") + + try await harness.client.unregisterLiveActivityToken(token: token) + try await harness.client.unregisterLiveActivityTokens(deviceId: "dev-1", sessionId: "sess-1") + + let requests = await harness.performer.requests + #expect(requests.count == 2) + #expect(requests[0].httpMethod == "DELETE") + #expect(bodyString(requests[0]) == "{\"token\":\"\(token)\"}") + #expect(bodyString(requests[1]) == #"{"deviceId":"dev-1","sessionId":"sess-1"}"#) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/LiveActivityPrefsTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/LiveActivityPrefsTests.swift new file mode 100644 index 00000000..b8f7c261 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Settings/LiveActivityPrefsTests.swift @@ -0,0 +1,30 @@ +import Foundation +import HapiClient +import Testing + +@MainActor +@Suite("Live Activity prefs") +struct LiveActivityPrefsTests { + private func makeDefaults() throws -> (UserDefaults, String) { + let suiteName = "LiveActivityPrefsTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + return (defaults, suiteName) + } + + @Test func defaultsToEnabledAndRoundTrips() throws { + let (defaults, suiteName) = try makeDefaults() + defer { defaults.removePersistentDomain(forName: suiteName) } + + #expect(LiveActivityPrefs(defaults: defaults).enabled) + + LiveActivityPrefs(defaults: defaults).setEnabled(false) + #expect(!LiveActivityPrefs(defaults: defaults).enabled) + + LiveActivityPrefs(defaults: defaults).setEnabled(true) + #expect(LiveActivityPrefs(defaults: defaults).enabled) + } + + @Test func storageKeyIsStable() { + #expect(LiveActivityPrefs.enabledKey == "settings.liveActivities") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift index 59a8a69a..7846420e 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/Stores/SessionListStoreTests.swift @@ -37,6 +37,21 @@ struct SessionListStoreTests { #expect(store.sessions.map(\.id) == ["pinned", "active", "old-inactive"]) } + @Test func onSessionsChangedFiresForRealChangesOnly() async throws { + let (performer, store) = try makeStore() + var changes: [[String]] = [] + store.onSessionsChanged = { sessions in changes.append(sessions.map(\.id)) } + + await performer.enqueue(json: try sessionsResponseJSON(storeSummary("s1"))) + try await store.refresh() + #expect(changes == [["s1"]]) + + // Keep-alive `activeAt` churn is filtered before `setSessions`, so + // the Live Activity seam must not see it. + store.applySessionEvent(try sessionUpdatedEvent("s1", dataJSON: "{\"activeAt\":123}")) + #expect(changes.count == 1) + } + @Test func staleRefreshCannotUndoNewerUserInput() async throws { let (performer, store) = try makeStore() let snapshot = try sessionsResponseJSON( diff --git a/ios/Packages/HapiKit/Tests/HapiProtocolTests/LiveActivityTests.swift b/ios/Packages/HapiKit/Tests/HapiProtocolTests/LiveActivityTests.swift new file mode 100644 index 00000000..cbde6874 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiProtocolTests/LiveActivityTests.swift @@ -0,0 +1,198 @@ +import Foundation +import HapiProtocol +import Testing + +@Suite("Live Activity policy") +struct LiveActivityPolicyTests { + @Test func tracksWorkingAndWaitingSessions() { + #expect(LiveActivityPolicy.isTracked(active: true, thinking: true, pendingRequestsCount: 0)) + #expect(LiveActivityPolicy.isTracked(active: true, thinking: false, pendingRequestsCount: 1)) + #expect(!LiveActivityPolicy.isTracked(active: false, thinking: true, pendingRequestsCount: 1)) + #expect(!LiveActivityPolicy.isTracked(active: true, thinking: false, pendingRequestsCount: 0)) + } + + @Test func pendingRequestsWinOverWorking() { + #expect(LiveActivityPolicy.status( + active: true, + thinking: true, + pendingRequestsCount: 1, + pendingRequestKinds: [.permission] + ) == .needsApproval) + #expect(LiveActivityPolicy.status( + active: true, + thinking: true, + pendingRequestsCount: 2, + pendingRequestKinds: [.input] + ) == .needsInput) + #expect(LiveActivityPolicy.status( + active: true, + thinking: true, + pendingRequestsCount: 2, + pendingRequestKinds: [.input, .permission] + ) == .needsAttention) + } + + @Test func workingWhenThinkingWithoutRequests() { + #expect(LiveActivityPolicy.status( + active: true, + thinking: true, + pendingRequestsCount: 0, + pendingRequestKinds: [] + ) == .working) + } + + @Test func settledOrInactiveSessionsHaveNoLiveState() { + #expect(LiveActivityPolicy.status( + active: true, + thinking: false, + pendingRequestsCount: 0, + pendingRequestKinds: [] + ) == nil) + #expect(LiveActivityPolicy.status( + active: false, + thinking: true, + pendingRequestsCount: 0, + pendingRequestKinds: [] + ) == nil) + } + + @Test func counterFieldsTolerateOmissionButStatusDoesNot() throws { + let json = #""" + {"status":"working","title":"t","project":"p","startedAt":1,"updatedAt":2} + """# + let state = try JSONDecoder().decode(LiveActivityContentState.self, from: Data(json.utf8)) + #expect(state.pendingCount == 0) + #expect(state.todoCompleted == 0) + #expect(state.todoTotal == 0) + #expect(state.backgroundTaskCount == 0) + + let bad = #""" + {"status":"flying","title":"t","project":"p","startedAt":1,"updatedAt":2} + """# + #expect(throws: DecodingError.self) { + try JSONDecoder().decode(LiveActivityContentState.self, from: Data(bad.utf8)) + } + } +} + +#if canImport(CryptoKit) +@Suite("Live Activity cipher") +struct LiveActivityCipherTests { + private struct Fixture: Decodable { + let keyHex: String + let nonceHex: String + let aad: String + let plaintext: String + let envelopeB64: String + + enum CodingKeys: String, CodingKey { + case keyHex = "key_hex" + case nonceHex = "nonce_hex" + case aad + case plaintext + case envelopeB64 = "envelope_b64" + } + } + + private static let fixtureState = LiveActivityContentState( + status: .needsApproval, + title: "Claude - hapi", + project: "hapi", + startedAt: 1_700_000_000_000, + updatedAt: 1_700_000_060_000, + pendingCount: 1, + todoCompleted: 2, + todoTotal: 5, + backgroundTaskCount: 0 + ) + + private static func fixture() throws -> Fixture { + let url = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .appendingPathComponent("../../../shared/fixtures/live-activity/content-state-v1.json") + .standardizedFileURL + return try JSONDecoder().decode(Fixture.self, from: Data(contentsOf: url)) + } + + private static func data(hex: String) -> Data { + var bytes = [UInt8]() + var index = hex.startIndex + while index < hex.endIndex { + let next = hex.index(index, offsetBy: 2) + bytes.append(UInt8(hex[index...json ├── pagination/.json ├── catalogs/modes.json # reference tables (see Catalogs below) +├── push/envelope-v1.json # hand-authored push-cipher vector +├── live-activity/content-state-v1.json # hand-authored Live Activity cipher vector └── README.md ``` +`push/` and `live-activity/` are hand-authored cryptographic contract vectors, +not pipeline fixtures: they pin the AES-GCM wire format across the hub and +native clients. The "regenerate, never hand-edit" rule applies to the +`chat/`, `sse/`, and `pagination/` suites above. + ## How to consume (all suites) - **iOS** (`ios/`, SPM test target): resolve the repo checkout from the test diff --git a/shared/fixtures/live-activity/content-state-v1.json b/shared/fixtures/live-activity/content-state-v1.json new file mode 100644 index 00000000..642a629b --- /dev/null +++ b/shared/fixtures/live-activity/content-state-v1.json @@ -0,0 +1,7 @@ +{ + "key_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", + "nonce_hex": "000102030405060708090a0b", + "aad": "hapi-live-activity-v1", + "plaintext": "{\"backgroundTaskCount\":0,\"pendingCount\":1,\"project\":\"hapi\",\"startedAt\":1700000000000,\"status\":\"needsApproval\",\"title\":\"Claude - hapi\",\"todoCompleted\":2,\"todoTotal\":5,\"updatedAt\":1700000060000}", + "envelope_b64": "AAECAwQFBgcICQoLPCC0eqaOpWniNPnv5YgLBsC58lqEWWVMFEWV4HMNadxmU8GJwbUwokWIXZ366EJdjS1Ct3i+wqpWtQY7a5eUnIRZojun8xxQK2SaXt+/PtgIuvlSWkEgHJyJ679aypvjrp09leUxuGjxal/ealkDC9MTDs7B/wfZIZ4iqefGQy7TM3CvlvvpJ2eFJ+JStzyuU4CGURcroWauK4cTlYaGmvL7vC/c0+4L1we8jrrkx8+/9PsVu5tDjFXv9vdB9YeOXzHn0JFTjDlT/C9vXsPDyQ==" +}