mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-01 06:31:27 +00:00
feat(ios): add snapshot-backed home and lock screen widgets
- add the WidgetSnapshot contract, App Group store, status/title builder - write debounced snapshots from SessionListStore; NSE refreshes them from decrypted pushes and reloads widget timelines - add small/medium/large, accessory, and StandBy widget families with attention-first rows and session deep links - add App Group entitlements for the app, NSE, and widget extension - document the snapshot data flow and privacy properties - cover selection, title fallback, store round-trip, and push updates via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -46,6 +46,8 @@ Your hub, coding agents, plugins, and command-line tools may send prompts, sourc
|
||||
|
||||
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.
|
||||
|
||||
Home-screen and Lock Screen status widgets read a small, display-only snapshot from the app's App Group container (`group.run.hapi.app`). It contains session/project names, status, counts and timestamps — never message text, files, or hub credentials. The snapshot is written by the app and refreshed by the Notification Service Extension from already-decrypted pushes; it stays on the device and is not sent to Apple or any relay. Widgets are visible on the Home Screen when the device is unlocked; use the system privacy/redaction options if project names should be hidden on the Lock Screen.
|
||||
|
||||
### 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**:
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
A100000000000000000000C4 /* HapiProtocol in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C2 /* HapiProtocol */; };
|
||||
A200000000000000000000C4 /* HapiProtocol in Frameworks */ = {isa = PBXBuildFile; productRef = A200000000000000000000C2 /* HapiProtocol */; };
|
||||
A100000000000000000000C5 /* HapiClient in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C3 /* HapiClient */; };
|
||||
A100000000000000000000C8 /* HapiUI in Frameworks */ = {isa = PBXBuildFile; productRef = A100000000000000000000C7 /* HapiUI */; };
|
||||
A200000000000000000000D4 /* HapiNotificationService.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A200000000000000000000A4 /* HapiNotificationService.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
@@ -135,6 +136,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A200000000000000000000C4 /* HapiProtocol in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -229,6 +231,7 @@
|
||||
);
|
||||
name = HapiNotificationService;
|
||||
packageProductDependencies = (
|
||||
A200000000000000000000C2 /* HapiProtocol */,
|
||||
);
|
||||
productName = HapiNotificationService;
|
||||
productReference = A200000000000000000000A4 /* HapiNotificationService.appex */;
|
||||
@@ -764,6 +767,10 @@
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = HapiUI;
|
||||
};
|
||||
A200000000000000000000C2 /* HapiProtocol */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = HapiProtocol;
|
||||
};
|
||||
A400000000000000000000C2 /* HapiProtocol */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = HapiProtocol;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import HapiClient
|
||||
import HapiProtocol
|
||||
|
||||
/// Cross-platform seam for the home-screen widget snapshot writer. The real
|
||||
/// writer is iOS-only (WidgetKit); Catalyst gets a no-op.
|
||||
@MainActor
|
||||
protocol WidgetSnapshotControlling: AnyObject {
|
||||
func update(_ sessions: [SessionSummary], hubUrl: String)
|
||||
func flush()
|
||||
func clear()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class NoopWidgetSnapshotController: WidgetSnapshotControlling {
|
||||
func update(_ sessions: [SessionSummary], hubUrl: String) {}
|
||||
func flush() {}
|
||||
func clear() {}
|
||||
}
|
||||
|
||||
enum WidgetSnapshotControllerFactory {
|
||||
@MainActor
|
||||
static func make() -> any WidgetSnapshotControlling {
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
return WidgetSnapshotUpdater()
|
||||
#else
|
||||
return NoopWidgetSnapshotController()
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
import Foundation
|
||||
import HapiClient
|
||||
import HapiProtocol
|
||||
import WidgetKit
|
||||
|
||||
/// Debounced writer for the App Group widget snapshot. The widget timeline
|
||||
/// reads this file; the app never talks to WidgetKit for rendering.
|
||||
@MainActor
|
||||
final class WidgetSnapshotUpdater: WidgetSnapshotControlling {
|
||||
private struct Pending {
|
||||
let sessions: [SessionSummary]
|
||||
let hubUrl: String
|
||||
}
|
||||
|
||||
private var pending: Pending?
|
||||
private var debounceTask: Task<Void, Never>?
|
||||
private let debounce: Duration = .milliseconds(400)
|
||||
|
||||
func update(_ sessions: [SessionSummary], hubUrl: String) {
|
||||
pending = Pending(sessions: sessions, hubUrl: hubUrl)
|
||||
debounceTask?.cancel()
|
||||
debounceTask = Task { [debounce] in
|
||||
do {
|
||||
try await Task.sleep(for: debounce)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
guard !Task.isCancelled else { return }
|
||||
self.flush()
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes any pending snapshot now (app background) and reloads the
|
||||
/// widget timelines after the atomic write completes.
|
||||
func flush() {
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
guard let pending else { return }
|
||||
self.pending = nil
|
||||
let snapshot = WidgetSnapshotBuilder.build(
|
||||
sessions: pending.sessions,
|
||||
hubUrl: pending.hubUrl
|
||||
)
|
||||
Task.detached(priority: .utility) {
|
||||
try? WidgetSnapshotStore.save(snapshot)
|
||||
await MainActor.run {
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: WidgetSnapshotStore.widgetKind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clear() {
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
pending = nil
|
||||
Task.detached(priority: .utility) {
|
||||
try? WidgetSnapshotStore.save(.empty)
|
||||
await MainActor.run {
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: WidgetSnapshotStore.widgetKind)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -4,6 +4,10 @@
|
||||
<dict>
|
||||
<key>aps-environment</key>
|
||||
<string>development</string>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.run.hapi.app</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)run.hapi.companion.push</string>
|
||||
|
||||
@@ -54,6 +54,7 @@ final class AppModel {
|
||||
let registry: HubRegistry
|
||||
let liveActivityPrefs: LiveActivityPrefs
|
||||
let liveActivity: any LiveActivityControlling
|
||||
let widgetSnapshots: any WidgetSnapshotControlling
|
||||
private let credentialStore: any CredentialStoring
|
||||
private let performer: any HTTPPerforming
|
||||
private let pairingService: HubPairingService
|
||||
@@ -77,6 +78,7 @@ final class AppModel {
|
||||
let liveActivityPrefs = LiveActivityPrefs()
|
||||
self.liveActivityPrefs = liveActivityPrefs
|
||||
self.liveActivity = LiveActivityControllerFactory.make(prefs: liveActivityPrefs)
|
||||
self.widgetSnapshots = WidgetSnapshotControllerFactory.make()
|
||||
restore()
|
||||
// Push wiring (P3): the coordinator is a process singleton (UIKit
|
||||
// delegates outlive any model); it pulls navigation + suppression
|
||||
@@ -108,6 +110,7 @@ final class AppModel {
|
||||
activate(hub: hub)
|
||||
return
|
||||
}
|
||||
widgetSnapshots.clear()
|
||||
state = .unpaired
|
||||
}
|
||||
|
||||
@@ -149,6 +152,7 @@ final class AppModel {
|
||||
if wasActive {
|
||||
// End + unregister while the old hub's API still works.
|
||||
liveActivity.detach()
|
||||
widgetSnapshots.clear()
|
||||
session?.shutdown()
|
||||
session = nil
|
||||
}
|
||||
@@ -226,12 +230,18 @@ final class AppModel {
|
||||
isForeground = true
|
||||
session?.enterForeground()
|
||||
liveActivity.appDidBecomeActive()
|
||||
if let session {
|
||||
widgetSnapshots.update(session.sessionStore.sessions, hubUrl: session.hubUrl)
|
||||
} else {
|
||||
widgetSnapshots.clear()
|
||||
}
|
||||
// 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()
|
||||
widgetSnapshots.flush()
|
||||
session?.enterBackground()
|
||||
case .inactive:
|
||||
break // transitional; no connection changes
|
||||
@@ -283,6 +293,7 @@ final class AppModel {
|
||||
performer: performer
|
||||
) else {
|
||||
// Unreachable for registry-normalized origins; fail closed.
|
||||
widgetSnapshots.clear()
|
||||
state = .unpaired
|
||||
return
|
||||
}
|
||||
@@ -294,11 +305,13 @@ final class AppModel {
|
||||
// new hub's coordinator with the old hub's sessions.
|
||||
guard let self, let newSession, self.session === newSession else { return }
|
||||
self.liveActivity.sessionsChanged(sessions)
|
||||
self.widgetSnapshots.update(sessions, hubUrl: newSession.hubUrl)
|
||||
}
|
||||
session = newSession
|
||||
state = .paired(activeHub: hub)
|
||||
hubs = registry.hubs
|
||||
liveActivity.attach(to: newSession)
|
||||
widgetSnapshots.update(newSession.sessionStore.sessions, hubUrl: newSession.hubUrl)
|
||||
if isForeground {
|
||||
newSession.enterForeground()
|
||||
}
|
||||
@@ -310,6 +323,7 @@ final class AppModel {
|
||||
/// pairing (or the next hub) with a banner.
|
||||
private func handleTerminalAuthFailure(for hub: String) {
|
||||
liveActivity.detach()
|
||||
widgetSnapshots.clear()
|
||||
session = nil // the session shut itself down before calling back
|
||||
authFailureNotice = hub
|
||||
// No JWT left to authenticate a push unregister; just drop the hub
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.run.hapi.app</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)run.hapi.companion.push</string>
|
||||
|
||||
@@ -2,6 +2,10 @@ import CryptoKit
|
||||
import Foundation
|
||||
import Security
|
||||
import UserNotifications
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
import HapiProtocol
|
||||
import WidgetKit
|
||||
#endif
|
||||
|
||||
/// Notification Service Extension (P3): APNs delivers
|
||||
/// `{aps: {mutable-content: 1, alert: <generic>}, hapi: {v: 1, e: <envelope>}}`
|
||||
@@ -37,6 +41,7 @@ final class NotificationService: UNNotificationServiceExtension {
|
||||
|
||||
if let fields = Self.decryptedFields(from: request.content.userInfo) {
|
||||
Self.apply(fields, to: content)
|
||||
Self.updateWidgetSnapshot(fields)
|
||||
}
|
||||
contentHandler(content)
|
||||
}
|
||||
@@ -76,8 +81,7 @@ final class NotificationService: UNNotificationServiceExtension {
|
||||
|
||||
/// Contract slice of `PushPayload` (see the header note): display title,
|
||||
/// display body (ready-summary composition), category for actions.
|
||||
static func apply(_ fields: [String: String], to content: UNMutableNotificationContent) {
|
||||
let type = fields["type"] ?? ""
|
||||
static func apply(_ fields: [String: String], to content: UNMutableNotificationContent) { let type = fields["type"] ?? ""
|
||||
let contractVersion = fields["contractVersion"]
|
||||
let knownVersion = contractVersion == nil || isBlank(contractVersion!) || contractVersion == "1"
|
||||
|
||||
@@ -103,6 +107,22 @@ final class NotificationService: UNNotificationServiceExtension {
|
||||
content.userInfo = userInfo
|
||||
}
|
||||
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
/// Best-effort widget snapshot refresh from a decrypted alert. The
|
||||
/// alert path already has the session/type; the app will overwrite the
|
||||
/// snapshot with exact counts on its next run.
|
||||
private static func updateWidgetSnapshot(_ fields: [String: String]) {
|
||||
guard let type = fields["type"], let sessionId = fields["sessionId"] else { return }
|
||||
if WidgetSnapshotStore.applyPush(
|
||||
type: type,
|
||||
sessionId: sessionId,
|
||||
sessionName: fields["sessionName"]
|
||||
) {
|
||||
WidgetCenter.shared.reloadTimelines(ofKind: WidgetSnapshotStore.widgetKind)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private static func displayBody(_ fields: [String: String], type: String) -> String {
|
||||
if type == "ready",
|
||||
let rawSummary = fields["notifySummary"],
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
import HapiProtocol
|
||||
import SwiftUI
|
||||
import UIKit
|
||||
import WidgetKit
|
||||
|
||||
/// Home-screen and lock-screen status widgets. Same data contract as the
|
||||
/// Live Activity, but snapshot-driven: the app writes the App Group file and
|
||||
/// reloads timelines; the widget never holds credentials or talks to the hub.
|
||||
struct HapiHomeWidget: Widget {
|
||||
var body: some WidgetConfiguration {
|
||||
StaticConfiguration(
|
||||
kind: WidgetSnapshotStore.widgetKind,
|
||||
provider: HapiWidgetProvider()
|
||||
) { entry in
|
||||
HapiWidgetView(entry: entry)
|
||||
}
|
||||
.configurationDisplayName("HAPI")
|
||||
.description("Running sessions and requests that need you.")
|
||||
.supportedFamilies([
|
||||
.systemSmall,
|
||||
.systemMedium,
|
||||
.systemLarge,
|
||||
.accessoryCircular,
|
||||
.accessoryRectangular,
|
||||
.accessoryInline
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
struct HapiWidgetEntry: TimelineEntry {
|
||||
let date: Date
|
||||
let snapshot: WidgetSnapshot
|
||||
}
|
||||
|
||||
struct HapiWidgetProvider: TimelineProvider {
|
||||
func placeholder(in context: Context) -> HapiWidgetEntry {
|
||||
HapiWidgetEntry(date: Date(), snapshot: .empty)
|
||||
}
|
||||
|
||||
func getSnapshot(in context: Context, completion: @escaping (HapiWidgetEntry) -> Void) {
|
||||
completion(HapiWidgetEntry(date: Date(), snapshot: WidgetSnapshotStore.load() ?? .empty))
|
||||
}
|
||||
|
||||
func getTimeline(in context: Context, completion: @escaping (Timeline<HapiWidgetEntry>) -> Void) {
|
||||
let now = Date()
|
||||
let entry = HapiWidgetEntry(date: now, snapshot: WidgetSnapshotStore.load() ?? .empty)
|
||||
// Pushes reload the timeline immediately; this is only the fallback.
|
||||
completion(Timeline(entries: [entry], policy: .after(now.addingTimeInterval(15 * 60))))
|
||||
}
|
||||
}
|
||||
|
||||
private struct HapiWidgetView: View {
|
||||
let entry: HapiWidgetEntry
|
||||
|
||||
@Environment(\.widgetFamily) private var family
|
||||
|
||||
var body: some View {
|
||||
content
|
||||
.containerBackground(for: .widget) {
|
||||
if isAccessory {
|
||||
AccessoryWidgetBackground()
|
||||
} else {
|
||||
HapiWidgetBackground()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var content: some View {
|
||||
switch family {
|
||||
case .systemSmall:
|
||||
SmallWidget(snapshot: entry.snapshot)
|
||||
case .systemMedium:
|
||||
MediumWidget(snapshot: entry.snapshot)
|
||||
case .systemLarge:
|
||||
LargeWidget(snapshot: entry.snapshot)
|
||||
case .accessoryCircular:
|
||||
CircularAccessory(snapshot: entry.snapshot)
|
||||
case .accessoryRectangular:
|
||||
RectangularAccessory(snapshot: entry.snapshot)
|
||||
case .accessoryInline:
|
||||
InlineAccessory(snapshot: entry.snapshot)
|
||||
default:
|
||||
MediumWidget(snapshot: entry.snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
private var isAccessory: Bool {
|
||||
switch family {
|
||||
case .accessoryCircular, .accessoryRectangular, .accessoryInline: return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct HapiWidgetBackground: View {
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Color(uiColor: .systemBackground)
|
||||
LinearGradient(
|
||||
colors: [
|
||||
Color.blue.opacity(0.10),
|
||||
Color.purple.opacity(0.05),
|
||||
.clear
|
||||
],
|
||||
startPoint: .topLeading,
|
||||
endPoint: .bottomTrailing
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Home screen
|
||||
|
||||
private struct SmallWidget: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 7) {
|
||||
WidgetHeader(snapshot: snapshot)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 4) {
|
||||
Text("\(snapshot.runningCount)")
|
||||
.font(.system(size: 38, weight: .light, design: .rounded))
|
||||
.monospacedDigit()
|
||||
Text("Working")
|
||||
.font(.caption2.weight(.semibold))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 5) {
|
||||
if snapshot.needsApprovalCount > 0 {
|
||||
CountLine(color: .orange, image: "hand.raised.fill", count: snapshot.needsApprovalCount, label: "Needs approval")
|
||||
}
|
||||
if snapshot.needsInputCount > 0 {
|
||||
CountLine(color: .purple, image: "bubble.left.fill", count: snapshot.needsInputCount, label: "Needs input")
|
||||
}
|
||||
if snapshot.needsApprovalCount == 0 && snapshot.needsInputCount == 0 {
|
||||
if let top = snapshot.sessions.first {
|
||||
CountLine(color: top.status.color, image: top.status.symbol, count: nil, label: top.title)
|
||||
} else {
|
||||
Text("No running sessions")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.widgetURL(topURL)
|
||||
}
|
||||
|
||||
private var topURL: URL? {
|
||||
guard let top = snapshot.sessions.first else { return nil }
|
||||
return SessionLink.url(sessionId: top.id, hubUrl: snapshot.hubUrl.isEmpty ? nil : snapshot.hubUrl)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MediumWidget: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
WidgetHeader(snapshot: snapshot)
|
||||
.padding(.bottom, 7)
|
||||
if snapshot.sessions.isEmpty {
|
||||
EmptyWidgetState()
|
||||
} else {
|
||||
ForEach(snapshot.sessions.prefix(3)) { session in
|
||||
SessionRow(session: session, hubUrl: snapshot.hubUrl, compact: true)
|
||||
}
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
FooterLine(snapshot: snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct LargeWidget: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
WidgetHeader(snapshot: snapshot)
|
||||
.padding(.bottom, 7)
|
||||
if snapshot.sessions.isEmpty {
|
||||
EmptyWidgetState()
|
||||
} else {
|
||||
ForEach(snapshot.sessions.prefix(7)) { session in
|
||||
SessionRow(session: session, hubUrl: snapshot.hubUrl, compact: false)
|
||||
}
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
FooterLine(snapshot: snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Accessories
|
||||
|
||||
private struct CircularAccessory: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Circle()
|
||||
.stroke(.tertiary, lineWidth: 5)
|
||||
Circle()
|
||||
.trim(from: 0, to: ringProgress)
|
||||
.stroke(.primary, style: StrokeStyle(lineWidth: 5, lineCap: .round))
|
||||
.rotationEffect(.degrees(-90))
|
||||
VStack(spacing: 0) {
|
||||
Text("\(snapshot.runningCount)")
|
||||
.font(.title2.weight(.semibold))
|
||||
.monospacedDigit()
|
||||
Text("working")
|
||||
.font(.system(size: 8, weight: .medium))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var ringProgress: CGFloat {
|
||||
guard snapshot.runningCount > 0 else { return 0 }
|
||||
return min(1, CGFloat(snapshot.runningCount) / 5)
|
||||
}
|
||||
}
|
||||
|
||||
private struct RectangularAccessory: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: "waveform")
|
||||
.font(.caption2)
|
||||
Text("HAPI")
|
||||
.font(.caption2.weight(.bold))
|
||||
Spacer(minLength: 0)
|
||||
if snapshot.needsApprovalCount > 0 {
|
||||
Image(systemName: "hand.raised.fill")
|
||||
.font(.caption2)
|
||||
Text("\(snapshot.needsApprovalCount)")
|
||||
.font(.caption2.weight(.bold))
|
||||
}
|
||||
}
|
||||
if let top = snapshot.sessions.first {
|
||||
Text(top.title)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
Text(top.status.accessoryLabel)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
} else {
|
||||
Text("No running sessions")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct InlineAccessory: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
Label {
|
||||
Text("HAPI · \(snapshot.runningCount) working · \(snapshot.needsApprovalCount) approvals")
|
||||
} icon: {
|
||||
Image(systemName: "waveform")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Shared pieces
|
||||
|
||||
private struct WidgetHeader: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
HapiMark()
|
||||
.frame(width: 15, height: 15)
|
||||
Text("HAPI")
|
||||
.font(.caption2.weight(.bold))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer(minLength: 0)
|
||||
if snapshot.needsApprovalCount > 0 || snapshot.needsInputCount > 0 {
|
||||
Circle()
|
||||
.fill(.orange)
|
||||
.frame(width: 6, height: 6)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct HapiMark: View {
|
||||
var body: some View {
|
||||
RoundedRectangle(cornerRadius: 4.5, style: .continuous)
|
||||
.fill(
|
||||
LinearGradient(
|
||||
colors: [Color.blue, Color.purple],
|
||||
startPoint: .topLeading,
|
||||
endPoint: .bottomTrailing
|
||||
)
|
||||
)
|
||||
.overlay {
|
||||
Image(systemName: "waveform")
|
||||
.font(.system(size: 8, weight: .bold))
|
||||
.foregroundStyle(.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct SessionRow: View {
|
||||
let session: WidgetSnapshot.Session
|
||||
let hubUrl: String
|
||||
let compact: Bool
|
||||
|
||||
var body: some View {
|
||||
if let url = SessionLink.url(sessionId: session.id, hubUrl: hubUrl.isEmpty ? nil : hubUrl) {
|
||||
Link(destination: url) { row }
|
||||
} else {
|
||||
row
|
||||
}
|
||||
}
|
||||
|
||||
private var row: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(session.status.color)
|
||||
.frame(width: 7, height: 7)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(session.title)
|
||||
.font(.caption.weight(.semibold))
|
||||
.lineLimit(1)
|
||||
if compact {
|
||||
Text(session.project.isEmpty ? session.status.shortLabel : session.project)
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
Spacer(minLength: 4)
|
||||
trailing
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var trailing: some View {
|
||||
switch session.status {
|
||||
case .working:
|
||||
if let startedAt = session.startedAt {
|
||||
ElapsedText(startedAt: startedAt)
|
||||
.font(.caption2.monospacedDigit())
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
StatusBadge(status: session.status)
|
||||
}
|
||||
case .done:
|
||||
Text(Date(timeIntervalSince1970: Double(session.updatedAt) / 1000), style: .relative)
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
default:
|
||||
StatusBadge(status: session.status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct StatusBadge: View {
|
||||
let status: LiveActivityContentState.Status
|
||||
|
||||
var body: some View {
|
||||
Label(status.shortLabel, systemImage: status.symbol)
|
||||
.font(.system(size: 8, weight: .semibold))
|
||||
.labelStyle(.titleAndIcon)
|
||||
.foregroundStyle(status.color)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private struct CountLine: View {
|
||||
let color: Color
|
||||
let image: String
|
||||
let count: Int?
|
||||
let label: String
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 5) {
|
||||
Image(systemName: image)
|
||||
.font(.system(size: 9, weight: .semibold))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 11)
|
||||
if let count {
|
||||
Text("\(count)")
|
||||
.font(.system(size: 10, weight: .bold))
|
||||
.monospacedDigit()
|
||||
}
|
||||
Text(label)
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct FooterLine: View {
|
||||
let snapshot: WidgetSnapshot
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
let background = snapshot.sessions.reduce(0) { $0 + $1.backgroundTaskCount }
|
||||
if background > 0 {
|
||||
Label("\(background)", systemImage: "gearshape.2.fill")
|
||||
}
|
||||
if let top = snapshot.sessions.first(where: { $0.todoTotal > 0 }) {
|
||||
ProgressView(
|
||||
value: Double(top.todoCompleted),
|
||||
total: Double(max(top.todoTotal, 1))
|
||||
)
|
||||
.frame(width: 42)
|
||||
Text("\(top.todoCompleted)/\(top.todoTotal)")
|
||||
.monospacedDigit()
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(.top, 5)
|
||||
}
|
||||
}
|
||||
|
||||
private struct EmptyWidgetState: View {
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("No running sessions")
|
||||
.font(.caption.weight(.semibold))
|
||||
Text("Open HAPI to start one.")
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
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 extension LiveActivityContentState.Status {
|
||||
var color: Color {
|
||||
switch self {
|
||||
case .working: return .blue
|
||||
case .needsApproval: return .orange
|
||||
case .needsInput: return .purple
|
||||
case .needsAttention: return .red
|
||||
case .done: return .green
|
||||
case .error: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var symbol: String {
|
||||
switch self {
|
||||
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"
|
||||
}
|
||||
}
|
||||
|
||||
var shortLabel: String {
|
||||
switch self {
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
var accessoryLabel: String {
|
||||
switch self {
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.application-groups</key>
|
||||
<array>
|
||||
<string>group.run.hapi.app</string>
|
||||
</array>
|
||||
<key>keychain-access-groups</key>
|
||||
<array>
|
||||
<string>$(AppIdentifierPrefix)run.hapi.companion.push</string>
|
||||
|
||||
@@ -4,6 +4,7 @@ import WidgetKit
|
||||
@main
|
||||
struct HapiWidgetsBundle: WidgetBundle {
|
||||
var body: some Widget {
|
||||
HapiHomeWidget()
|
||||
SessionLiveActivityWidget()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,23 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"No running sessions" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Нет запущенных сеансов"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "没有运行中的会话"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Open HAPI" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -103,6 +120,23 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Open HAPI to start one." : {
|
||||
"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" : {
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
import Foundation
|
||||
|
||||
/// Small, display-only snapshot shared with the home-screen / lock-screen
|
||||
/// widgets through the App Group container.
|
||||
///
|
||||
/// This is deliberately **not** the full `SessionSummary` list: widgets only
|
||||
/// need a handful of fields, the snapshot stays well under a few KB, and it
|
||||
/// contains no credentials or message content.
|
||||
public struct WidgetSnapshot: Codable, Equatable, Sendable {
|
||||
public struct Session: Codable, Equatable, Sendable, Identifiable {
|
||||
public var id: String
|
||||
public var title: String
|
||||
public var project: String
|
||||
/// Reuses the Live Activity status vocabulary: `working` renders as
|
||||
/// “running”, `needsInput` as “needs reply”.
|
||||
public var status: LiveActivityContentState.Status
|
||||
/// Epoch ms of the user message that started the turn, when known.
|
||||
public var startedAt: Int?
|
||||
/// Epoch ms of the last session change.
|
||||
public var updatedAt: Int
|
||||
public var pendingCount: Int
|
||||
public var todoCompleted: Int
|
||||
public var todoTotal: Int
|
||||
public var backgroundTaskCount: Int
|
||||
|
||||
public init(
|
||||
id: String,
|
||||
title: String,
|
||||
project: String,
|
||||
status: LiveActivityContentState.Status,
|
||||
startedAt: Int?,
|
||||
updatedAt: Int,
|
||||
pendingCount: Int = 0,
|
||||
todoCompleted: Int = 0,
|
||||
todoTotal: Int = 0,
|
||||
backgroundTaskCount: Int = 0
|
||||
) {
|
||||
self.id = id
|
||||
self.title = title
|
||||
self.project = project
|
||||
self.status = status
|
||||
self.startedAt = startedAt
|
||||
self.updatedAt = updatedAt
|
||||
self.pendingCount = pendingCount
|
||||
self.todoCompleted = todoCompleted
|
||||
self.todoTotal = todoTotal
|
||||
self.backgroundTaskCount = backgroundTaskCount
|
||||
}
|
||||
}
|
||||
|
||||
public var generatedAt: Int
|
||||
/// Active hub origin. The widget is active-hub scoped; switching hubs
|
||||
/// overwrites the snapshot.
|
||||
public var hubUrl: String
|
||||
/// Rows shown by medium/large widgets (attention-first, capped).
|
||||
public var sessions: [Session]
|
||||
/// Totals across all tracked sessions, independent of the row cap. The
|
||||
/// small widget needs accurate counts even when more than eight sessions
|
||||
/// are running.
|
||||
public var runningCount: Int
|
||||
public var needsApprovalCount: Int
|
||||
public var needsInputCount: Int
|
||||
public var needsAttentionCount: Int
|
||||
|
||||
public init(
|
||||
generatedAt: Int,
|
||||
hubUrl: String,
|
||||
sessions: [Session],
|
||||
runningCount: Int? = nil,
|
||||
needsApprovalCount: Int? = nil,
|
||||
needsInputCount: Int? = nil,
|
||||
needsAttentionCount: Int? = nil
|
||||
) {
|
||||
self.generatedAt = generatedAt
|
||||
self.hubUrl = hubUrl
|
||||
self.sessions = sessions
|
||||
self.runningCount = runningCount ?? sessions.filter { $0.status == .working }.count
|
||||
self.needsApprovalCount = needsApprovalCount ?? sessions.filter { $0.status == .needsApproval }.count
|
||||
self.needsInputCount = needsInputCount ?? sessions.filter { $0.status == .needsInput }.count
|
||||
self.needsAttentionCount = needsAttentionCount ?? sessions.filter { $0.status == .needsAttention }.count
|
||||
}
|
||||
|
||||
public static let empty = WidgetSnapshot(generatedAt: 0, hubUrl: "", sessions: [])
|
||||
}
|
||||
|
||||
/// Builds the widget snapshot from the app's session list.
|
||||
///
|
||||
/// Selection is attention-first: pending requests, then running sessions,
|
||||
/// then recently completed sessions (so the large widget can show a “done”
|
||||
/// row). The small/medium widget uses the first rows; the large widget uses
|
||||
/// up to eight.
|
||||
public enum WidgetSnapshotBuilder {
|
||||
public static let defaultLimit = 8
|
||||
public static let defaultRecentWindowMs = 15 * 60 * 1000
|
||||
|
||||
public static func build(
|
||||
sessions: [SessionSummary],
|
||||
hubUrl: String,
|
||||
now: Int = Int(Date().timeIntervalSince1970 * 1000),
|
||||
recentWindowMs: Int = defaultRecentWindowMs,
|
||||
limit: Int = defaultLimit
|
||||
) -> WidgetSnapshot {
|
||||
let cutoff = now - recentWindowMs
|
||||
let rows = sessions.compactMap { summary -> WidgetSnapshot.Session? in
|
||||
let tracked = LiveActivityPolicy.isTracked(
|
||||
active: summary.active,
|
||||
thinking: summary.thinking,
|
||||
pendingRequestsCount: summary.pendingRequestsCount
|
||||
)
|
||||
let status: LiveActivityContentState.Status
|
||||
if tracked {
|
||||
guard let liveStatus = LiveActivityPolicy.status(
|
||||
active: summary.active,
|
||||
thinking: summary.thinking,
|
||||
pendingRequestsCount: summary.pendingRequestsCount,
|
||||
pendingRequestKinds: Set(summary.pendingRequestKinds)
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
status = liveStatus
|
||||
} else {
|
||||
guard summary.updatedAt >= cutoff else { return nil }
|
||||
status = .done
|
||||
}
|
||||
return WidgetSnapshot.Session(
|
||||
id: summary.id,
|
||||
title: title(for: summary),
|
||||
project: projectName(for: summary),
|
||||
status: status,
|
||||
startedAt: summary.lastUserMessageAt,
|
||||
updatedAt: summary.updatedAt,
|
||||
pendingCount: summary.pendingRequestsCount,
|
||||
todoCompleted: summary.todoProgress?.completed ?? 0,
|
||||
todoTotal: summary.todoProgress?.total ?? 0,
|
||||
backgroundTaskCount: summary.backgroundTaskCount
|
||||
)
|
||||
}
|
||||
.sorted { lhs, rhs in
|
||||
let lp = priority(lhs.status)
|
||||
let rp = priority(rhs.status)
|
||||
if lp != rp { return lp > rp }
|
||||
return lhs.updatedAt > rhs.updatedAt
|
||||
}
|
||||
|
||||
let limited = Array(rows.prefix(max(0, limit)))
|
||||
return WidgetSnapshot(
|
||||
generatedAt: now,
|
||||
hubUrl: hubUrl,
|
||||
sessions: limited,
|
||||
runningCount: rows.filter { $0.status == .working }.count,
|
||||
needsApprovalCount: rows.filter { $0.status == .needsApproval }.count,
|
||||
needsInputCount: rows.filter { $0.status == .needsInput }.count,
|
||||
needsAttentionCount: rows.filter { $0.status == .needsAttention }.count
|
||||
)
|
||||
}
|
||||
|
||||
public static func title(for summary: SessionSummary) -> String {
|
||||
if let name = summary.metadata?.name, !name.isEmpty { return name }
|
||||
if let text = summary.metadata?.summary?.text, !text.isEmpty { return text }
|
||||
if let prompt = summary.metadata?.promptTitle, !prompt.isEmpty { return prompt }
|
||||
if let path = summary.metadata?.path,
|
||||
let tail = path.split(separator: "/").last(where: { !$0.isEmpty }) {
|
||||
return String(tail)
|
||||
}
|
||||
return String(summary.id.prefix(8))
|
||||
}
|
||||
|
||||
public static func projectName(for summary: SessionSummary) -> String {
|
||||
guard let path = summary.metadata?.path else { return "" }
|
||||
return path.split(separator: "/").last.map(String.init) ?? ""
|
||||
}
|
||||
|
||||
private static func priority(_ status: LiveActivityContentState.Status) -> Int {
|
||||
switch status {
|
||||
case .needsAttention: return 6
|
||||
case .needsApproval: return 5
|
||||
case .needsInput: return 4
|
||||
case .error: return 6
|
||||
case .working: return 2
|
||||
case .done: return 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared App Group file store. The widget target and the app/NSE use the
|
||||
/// same path; tests inject a temporary directory.
|
||||
public enum WidgetSnapshotStore {
|
||||
public static let appGroupIdentifier = "group.run.hapi.app"
|
||||
public static let fileName = "widget-snapshot.json"
|
||||
public static let widgetKind = "HapiHomeWidget"
|
||||
|
||||
/// Production location, or nil when the App Group entitlement is absent.
|
||||
public static func containerURL() -> URL? {
|
||||
#if canImport(Darwin)
|
||||
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier)
|
||||
#else
|
||||
return nil
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func fileURL(in directory: URL) -> URL {
|
||||
directory.appendingPathComponent(fileName, isDirectory: false)
|
||||
}
|
||||
|
||||
public static func load() -> WidgetSnapshot? {
|
||||
guard let directory = containerURL() else { return nil }
|
||||
return load(from: directory)
|
||||
}
|
||||
|
||||
public static func load(from directory: URL) -> WidgetSnapshot? {
|
||||
guard let data = try? Data(contentsOf: fileURL(in: directory)) else { return nil }
|
||||
return try? JSONDecoder().decode(WidgetSnapshot.self, from: data)
|
||||
}
|
||||
|
||||
public static func save(_ snapshot: WidgetSnapshot) throws {
|
||||
guard let directory = containerURL() else { return }
|
||||
try save(snapshot, to: directory)
|
||||
}
|
||||
|
||||
public static func save(_ snapshot: WidgetSnapshot, to directory: URL) throws {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let url = fileURL(in: directory)
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]
|
||||
try encoder.encode(snapshot).write(to: url, options: .atomic)
|
||||
#if os(iOS) && !targetEnvironment(macCatalyst)
|
||||
// The lock-screen widget must read the snapshot after first unlock.
|
||||
try? FileManager.default.setAttributes(
|
||||
[.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication],
|
||||
ofItemAtPath: url.path
|
||||
)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// NSE-side best-effort update from a decrypted push. The alert push
|
||||
/// carries no counts/todos, so this updates the status and pending badge
|
||||
/// while preserving the richer fields the app wrote.
|
||||
@discardableResult
|
||||
public static func applyPush(
|
||||
type: String,
|
||||
sessionId: String,
|
||||
sessionName: String?,
|
||||
now: Int = Int(Date().timeIntervalSince1970 * 1000),
|
||||
in directory: URL? = nil
|
||||
) -> Bool {
|
||||
let existing = directory.map { load(from: $0) } ?? load()
|
||||
guard var snapshot = existing else { return false }
|
||||
let status: LiveActivityContentState.Status?
|
||||
switch type {
|
||||
case "permission-request": status = .needsApproval
|
||||
case "input-request": status = .needsInput
|
||||
case "ready", "task-notification": status = .done
|
||||
default: status = nil
|
||||
}
|
||||
guard let status else { return false }
|
||||
|
||||
if let index = snapshot.sessions.firstIndex(where: { $0.id == sessionId }) {
|
||||
let old = snapshot.sessions[index].status
|
||||
snapshot.adjustCounts(for: old, by: -1)
|
||||
snapshot.sessions[index].status = status
|
||||
snapshot.sessions[index].updatedAt = now
|
||||
if status == .needsApproval || status == .needsInput {
|
||||
snapshot.sessions[index].pendingCount = max(1, snapshot.sessions[index].pendingCount)
|
||||
} else {
|
||||
snapshot.sessions[index].pendingCount = 0
|
||||
}
|
||||
} else {
|
||||
// The app may not have written this session yet (cold start or
|
||||
// another surface started it); add a minimal row.
|
||||
let title = sessionName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
snapshot.sessions.insert(WidgetSnapshot.Session(
|
||||
id: sessionId,
|
||||
title: title.isEmpty ? String(sessionId.prefix(8)) : title,
|
||||
project: "",
|
||||
status: status,
|
||||
startedAt: nil,
|
||||
updatedAt: now,
|
||||
pendingCount: status == .needsApproval || status == .needsInput ? 1 : 0
|
||||
), at: 0)
|
||||
}
|
||||
snapshot.adjustCounts(for: status, by: 1)
|
||||
snapshot.generatedAt = now
|
||||
snapshot.sessions = Array(snapshot.sessions.prefix(WidgetSnapshotBuilder.defaultLimit))
|
||||
do {
|
||||
if let directory {
|
||||
try save(snapshot, to: directory)
|
||||
} else {
|
||||
try save(snapshot)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension WidgetSnapshot {
|
||||
mutating func adjustCounts(for status: LiveActivityContentState.Status, by delta: Int) {
|
||||
switch status {
|
||||
case .working: runningCount = max(0, runningCount + delta)
|
||||
case .needsApproval: needsApprovalCount = max(0, needsApprovalCount + delta)
|
||||
case .needsInput: needsInputCount = max(0, needsInputCount + delta)
|
||||
case .needsAttention: needsAttentionCount = max(0, needsAttentionCount + delta)
|
||||
case .done, .error: break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import Foundation
|
||||
import HapiProtocol
|
||||
import Testing
|
||||
|
||||
@Suite("Widget snapshot")
|
||||
struct WidgetSnapshotTests {
|
||||
private func summary(
|
||||
id: String,
|
||||
active: Bool = true,
|
||||
thinking: Bool = false,
|
||||
pending: Int = 0,
|
||||
kinds: [PendingRequestKind] = [],
|
||||
updatedAt: Int,
|
||||
lastUserMessageAt: Int? = nil,
|
||||
name: String? = nil,
|
||||
path: String = "/Users/me/projects/hapi",
|
||||
todo: TodoProgress? = nil,
|
||||
backgroundTasks: Int = 0
|
||||
) -> SessionSummary {
|
||||
SessionSummary(
|
||||
id: id,
|
||||
active: active,
|
||||
thinking: thinking,
|
||||
activeAt: updatedAt,
|
||||
updatedAt: updatedAt,
|
||||
lastUserMessageAt: lastUserMessageAt,
|
||||
metadata: SessionSummaryMetadata(name: name, path: path),
|
||||
metadataVersion: 1,
|
||||
agentStateVersion: 1,
|
||||
todosUpdatedAt: 0,
|
||||
todoProgress: todo,
|
||||
pendingRequestsCount: pending,
|
||||
pendingRequestKinds: kinds,
|
||||
backgroundTaskCount: backgroundTasks
|
||||
)
|
||||
}
|
||||
|
||||
@Test func selectsAttentionFirstAndKeepsExactTotals() {
|
||||
let now = 1_700_000_000_000
|
||||
let snapshot = WidgetSnapshotBuilder.build(
|
||||
sessions: [
|
||||
summary(id: "working", thinking: true, updatedAt: now - 30_000, lastUserMessageAt: now - 90_000, name: "Fix widget"),
|
||||
summary(id: "approval", pending: 2, kinds: [.permission], updatedAt: now - 20_000, name: "Review Android"),
|
||||
summary(id: "input", pending: 1, kinds: [.input], updatedAt: now - 10_000, name: "Answer question"),
|
||||
summary(id: "done", thinking: false, updatedAt: now - 5_000, name: "Old done"),
|
||||
summary(id: "stale", thinking: false, updatedAt: now - 60 * 60 * 1000, name: "Too old")
|
||||
],
|
||||
hubUrl: "https://hub.example.com",
|
||||
now: now,
|
||||
recentWindowMs: 15 * 60 * 1000,
|
||||
limit: 3
|
||||
)
|
||||
|
||||
#expect(snapshot.sessions.map(\.id) == ["approval", "input", "working"])
|
||||
#expect(snapshot.runningCount == 1)
|
||||
#expect(snapshot.needsApprovalCount == 1)
|
||||
#expect(snapshot.needsInputCount == 1)
|
||||
#expect(snapshot.sessions.first?.startedAt == nil)
|
||||
#expect(snapshot.sessions.first?.project == "hapi")
|
||||
#expect(snapshot.sessions.first?.title == "Review Android")
|
||||
#expect(snapshot.generatedAt == now)
|
||||
#expect(snapshot.hubUrl == "https://hub.example.com")
|
||||
}
|
||||
|
||||
@Test func includesRecentlyCompletedSessionsWithinTheWindow() {
|
||||
let now = 1_700_000_000_000
|
||||
let snapshot = WidgetSnapshotBuilder.build(
|
||||
sessions: [
|
||||
summary(id: "recent", thinking: false, updatedAt: now - 1_000, name: "Recent"),
|
||||
summary(id: "old", thinking: false, updatedAt: now - 16 * 60 * 1000, name: "Old")
|
||||
],
|
||||
hubUrl: "https://hub.example.com",
|
||||
now: now
|
||||
)
|
||||
|
||||
#expect(snapshot.sessions.map(\.id) == ["recent"])
|
||||
#expect(snapshot.sessions.first?.status == .done)
|
||||
#expect(snapshot.runningCount == 0)
|
||||
}
|
||||
|
||||
@Test func titleFallsBackThroughTheSameOrderAsTheApp() {
|
||||
var item = summary(id: "fallback-id", updatedAt: 1, path: "/repo/My Project")
|
||||
#expect(WidgetSnapshotBuilder.title(for: item) == "My Project")
|
||||
|
||||
item.metadata?.promptTitle = "Prompt title"
|
||||
#expect(WidgetSnapshotBuilder.title(for: item) == "Prompt title")
|
||||
|
||||
item.metadata?.summary = SessionSummaryMetadata.Summary(text: "Summary title")
|
||||
#expect(WidgetSnapshotBuilder.title(for: item) == "Summary title")
|
||||
|
||||
item.metadata?.name = "Manual name"
|
||||
#expect(WidgetSnapshotBuilder.title(for: item) == "Manual name")
|
||||
}
|
||||
|
||||
@Test func snapshotRoundTripsThroughTheAppGroupFile() throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("WidgetSnapshotTests-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let snapshot = WidgetSnapshotBuilder.build(
|
||||
sessions: [summary(id: "s1", thinking: true, updatedAt: 5_000, lastUserMessageAt: 4_000, name: "Session")],
|
||||
hubUrl: "https://hub.example.com",
|
||||
now: 5_000
|
||||
)
|
||||
try WidgetSnapshotStore.save(snapshot, to: directory)
|
||||
#expect(WidgetSnapshotStore.load(from: directory) == snapshot)
|
||||
}
|
||||
|
||||
@Test func pushUpdatesStatusAndTotals() throws {
|
||||
let directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("WidgetSnapshotPush-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let initial = WidgetSnapshotBuilder.build(
|
||||
sessions: [summary(id: "s1", thinking: true, updatedAt: 1_000, name: "Session")],
|
||||
hubUrl: "https://hub.example.com",
|
||||
now: 1_000
|
||||
)
|
||||
try WidgetSnapshotStore.save(initial, to: directory)
|
||||
|
||||
#expect(WidgetSnapshotStore.applyPush(
|
||||
type: "permission-request", sessionId: "s1", sessionName: "Session", now: 2_000, in: directory
|
||||
))
|
||||
var updated = try #require(WidgetSnapshotStore.load(from: directory))
|
||||
#expect(updated.sessions.first?.status == .needsApproval)
|
||||
#expect(updated.sessions.first?.pendingCount == 1)
|
||||
#expect(updated.runningCount == 0)
|
||||
#expect(updated.needsApprovalCount == 1)
|
||||
|
||||
#expect(WidgetSnapshotStore.applyPush(
|
||||
type: "ready", sessionId: "s1", sessionName: "Session", now: 3_000, in: directory
|
||||
))
|
||||
updated = try #require(WidgetSnapshotStore.load(from: directory))
|
||||
#expect(updated.sessions.first?.status == .done)
|
||||
#expect(updated.sessions.first?.pendingCount == 0)
|
||||
#expect(updated.needsApprovalCount == 0)
|
||||
|
||||
#expect(WidgetSnapshotStore.applyPush(
|
||||
type: "input-request", sessionId: "s2", sessionName: "New session", now: 4_000, in: directory
|
||||
))
|
||||
updated = try #require(WidgetSnapshotStore.load(from: directory))
|
||||
#expect(updated.sessions.first?.id == "s2")
|
||||
#expect(updated.sessions.first?.status == .needsInput)
|
||||
#expect(updated.needsInputCount == 1)
|
||||
|
||||
#expect(!WidgetSnapshotStore.applyPush(
|
||||
type: "unknown", sessionId: "s2", sessionName: nil, now: 5_000, in: directory
|
||||
))
|
||||
}
|
||||
}
|
||||
+41
-7
@@ -218,9 +218,10 @@ provider credentials as described below.
|
||||
after-first-unlock so lock-screen pushes decrypt), swaps in the real
|
||||
title/body, stamps the action category, and stores the decrypted fields in
|
||||
`userInfo` for the tap/action handlers. Undecryptable payloads deliver
|
||||
the generic alert unchanged. The appex links nothing beyond the SDK — it
|
||||
carries an SDK-only copy of the HapiKit `PushEnvelope` decrypt, kept honest
|
||||
by the shared test vector.
|
||||
the generic alert unchanged. The appex carries an SDK-only copy of the
|
||||
HapiKit `PushEnvelope` decrypt, kept honest by the shared test vector. It
|
||||
also links `HapiProtocol` for the App Group widget snapshot (see below);
|
||||
the decryption copy remains self-contained.
|
||||
- **Actions.** `permission-request` → Allow / Deny; `ready` and
|
||||
`task-notification` → inline Reply. `input-request` previews the first
|
||||
question, remaining question count and session name, with tap-to-open only
|
||||
@@ -307,18 +308,51 @@ lock-screen/Dynamic Island UI, Keychain read), and the hub's
|
||||
`src/live-activity/` notifier. The cross-language cipher vector is
|
||||
`shared/fixtures/live-activity/content-state-v1.json`.
|
||||
|
||||
### Home-screen and Lock Screen widgets
|
||||
|
||||
The same `HapiWidgets` extension also hosts static WidgetKit widgets for the
|
||||
Home Screen, Lock Screen accessories and StandBy. They are snapshot-driven,
|
||||
not real-time, and never hold hub credentials.
|
||||
|
||||
- **Data:** the app writes a small `widget-snapshot.json` to the App Group
|
||||
container `group.run.hapi.app` (`HapiProtocol/Widget/WidgetSnapshot.swift`).
|
||||
It contains only display fields: session id/title/project, status, elapsed
|
||||
start, pending/todo/background counts, hub origin, and exact status totals.
|
||||
- **Refresh:** `SessionListStore` changes debounce into a snapshot write;
|
||||
the Notification Service Extension also applies each decrypted push to the
|
||||
snapshot and calls `WidgetCenter.reloadTimelines` — so `ready` /
|
||||
`permission-request` / `input-request` update the widget while the app is
|
||||
suspended. The TimelineProvider falls back to a 15-minute policy.
|
||||
- **Surfaces:** systemSmall (totals + top attention), systemMedium (3 rows),
|
||||
systemLarge (up to 7 rows + progress), accessoryCircular /
|
||||
accessoryRectangular / accessoryInline, and StandBy (reuses the large
|
||||
layout). Every session row deep-links to `hapicompanion://sessions/<id>`.
|
||||
- **Scope:** active hub only; attention-first ordering; recently completed
|
||||
sessions stay visible for 15 minutes so the large widget can show a “done”
|
||||
row. No Control Center controls.
|
||||
- **Privacy:** the snapshot contains project/session names (no message text,
|
||||
no JWT). It lives in the App Group and is protected
|
||||
`completeUntilFirstUserAuthentication`. Add `.privacySensitive` or a
|
||||
privacy toggle if names must not show on the Lock Screen.
|
||||
- **Signing:** enable **App Groups** for the app, `HapiNotificationService`
|
||||
and `HapiWidgets` with `group.run.hapi.app`; keep the shared Keychain group
|
||||
for the push/Live Activity keys. The widget target stays iOS-only.
|
||||
- **Layer map:** `HapiProtocol/Widget/` (snapshot model/store/builder),
|
||||
`Hapi/Features/Widgets/` (debounced writer), `HapiWidgets/HapiHomeWidget.swift`
|
||||
(families + timeline), and the NSE's `updateWidgetSnapshot` hook.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | Responsibility |
|
||||
|---|---|
|
||||
| `Hapi.xcodeproj/` | App, notification extension, widget extension and app-hosted tests. App sources use Xcode synchronized folders. |
|
||||
| `Hapi/Models/` | `AppModel` pairing/navigation, active `HubSession`, per-chat `ChatSession`, and `PushCoordinator`. |
|
||||
| `Hapi/Features/` | SwiftUI screens and app models for pairing, sessions, chat, new sessions, files, Scratchlist and settings; UIKit transcript hosting; Live Activity coordinator. |
|
||||
| `Packages/HapiKit/Sources/HapiProtocol/` | Foundation wire models, catalogs, pairing/deep-link parsers, versioned patches, chat reduction, message-window logic, Git parsers, and the Live Activity content-state/cipher contract. |
|
||||
| `Hapi/Features/` | SwiftUI screens and app models for pairing, sessions, chat, new sessions, files, Scratchlist and settings; UIKit transcript hosting; Live Activity coordinator; widget snapshot writer. |
|
||||
| `Packages/HapiKit/Sources/HapiProtocol/` | Foundation wire models, catalogs, pairing/deep-link parsers, versioned patches, chat reduction, message-window logic, Git parsers, Live Activity content-state/cipher, and the widget snapshot model/store. |
|
||||
| `Packages/HapiKit/Sources/HapiClient/` | Auth/REST/SSE, stores and disk snapshots, message windows, chat interaction, attachments, dictation, push, Live Activity endpoints/prefs, and testable feature logic. |
|
||||
| `Packages/HapiKit/Sources/HapiUI/` | Reusable Markdown, syntax highlighting, diff rendering, theme and typography. |
|
||||
| `HapiNotificationService/` | SDK-only extension that decrypts APNs content using the shared Keychain key. |
|
||||
| `HapiWidgets/` | WidgetKit extension: Live Activity lock-screen/Dynamic Island UI plus the shared-key decrypt. iOS-only (no Catalyst). |
|
||||
| `HapiNotificationService/` | Appex that decrypts APNs content with the shared Keychain key and refreshes the App Group widget snapshot on push. |
|
||||
| `HapiWidgets/` | WidgetKit extension: Live Activity lock-screen/Dynamic Island UI, home/lock-screen/StandBy status widgets, and the shared-key decrypt. iOS-only (no Catalyst). |
|
||||
| `Packages/HapiKit/Tests/`, `HapiTests/` | Package and app-hosted verification. |
|
||||
|
||||
The app owns navigation, lifecycle and screen presentation; HapiKit supplies
|
||||
|
||||
Reference in New Issue
Block a user