Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(ios): add a share extension, quick actions, the app plugin and APNs device registration

nirholas7ca1455ae834
diff --git a/api/_lib/migrations/20260930160000_apns_devices.sql b/api/_lib/migrations/20260930160000_apns_devices.sql
new file mode 100644
index 000000000..82f670590
--- /dev/null
+++ b/api/_lib/migrations/20260930160000_apns_devices.sql
@@ -0,0 +1,45 @@
+-- Migration: APNs device tokens for the three.ws iOS app.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260930160000_apns_devices.sql
+-- Idempotent.
+--
+-- The iOS app's WKWebView runs no service worker, so Web Push (push_subscriptions)
+-- cannot reach it. The app registers with Apple Push Notification service
+-- instead and hands its device token to POST /api/push/device, which stores it
+-- here. api/_lib/notify.js fans every push-enabled notification out to both
+-- tables, so the preference center governs the iPhone exactly as it governs a
+-- browser.
+--
+-- token the hex device token APNs issued. Unique globally: a phone
+-- that signs into another account moves to that account, the
+-- same latest-owner-wins rule push_subscriptions uses.
+-- environment which APNs host accepts the token. A development build is
+-- issued sandbox tokens and an App Store or TestFlight build
+-- production ones; the client cannot tell which it is, so the
+-- sender tries the recorded host, falls back to the other on
+-- BadDeviceToken, and records whichever one answered.
+--
+-- api/push/device.js writes rows; api/_lib/apns.js reads them and prunes the
+-- ones APNs reports as gone.
+
+begin;
+
+create table if not exists apns_devices (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ token text not null,
+ environment text not null default 'production'
+ check (environment in ('production', 'sandbox')),
+ app_version text,
+ created_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now()
+);
+
+create unique index if not exists apns_devices_token
+ on apns_devices (token);
+create index if not exists apns_devices_user
+ on apns_devices (user_id, last_seen_at desc);
+
+comment on table apns_devices is
+ 'APNs device tokens for the iOS app, one row per device, latest owner wins.';
+
+commit;
diff --git a/ios/native/App/App.xcodeproj/project.pbxproj b/ios/native/App/App.xcodeproj/project.pbxproj
index 5bd77059c..a187facae 100644
--- a/ios/native/App/App.xcodeproj/project.pbxproj
+++ b/ios/native/App/App.xcodeproj/project.pbxproj
@@ -36,6 +36,12 @@
C4A11E0230B1004A00000000 /* GlanceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0230B1000A00000000 /* GlanceProvider.swift */; };
C4A11E0230B1004B00000000 /* AgentGlanceWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0230B1000B00000000 /* AgentGlanceWidget.swift */; };
C4A11E0230B1005000000000 /* GlanceWidget.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C4A11E0230B1000E00000000 /* GlanceWidget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
+ C4A11E0330C1001100000000 /* QuickActions.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000100000000 /* QuickActions.swift */; };
+ C4A11E0330C1001200000000 /* ThreeWsAppPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000200000000 /* ThreeWsAppPlugin.swift */; };
+ C4A11E0330C1001300000000 /* SharedInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000300000000 /* SharedInbox.swift */; };
+ C4A11E0330C1001400000000 /* SharedInbox.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000300000000 /* SharedInbox.swift */; };
+ C4A11E0330C1001500000000 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000400000000 /* ShareViewController.swift */; };
+ C4A11E0330C1001600000000 /* ShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = C4A11E0330C1000700000000 /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -46,6 +52,13 @@
remoteGlobalIDString = C4A11E0230B1006000000000;
remoteInfo = GlanceWidgetExtension;
};
+ C4A11E0330C1006600000000 /* PBXContainerItemProxy */ = {
+ isa = PBXContainerItemProxy;
+ containerPortal = 504EC2FC1FED79650016851F /* Project object */;
+ proxyType = 1;
+ remoteGlobalIDString = C4A11E0330C1006000000000;
+ remoteInfo = ShareExtension;
+ };
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -56,6 +69,7 @@
dstSubfolderSpec = 13;
files = (
C4A11E0230B1005000000000 /* GlanceWidget.appex in Embed Foundation Extensions */,
+ C4A11E0330C1001600000000 /* ShareExtension.appex in Embed Foundation Extensions */,
);
name = "Embed Foundation Extensions";
runOnlyForDeploymentPostprocessing = 0;
@@ -91,6 +105,13 @@
C4A11E0230B1000C00000000 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C4A11E0230B1000D00000000 /* GlanceWidget.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = GlanceWidget.entitlements; sourceTree = "<group>"; };
C4A11E0230B1000E00000000 /* GlanceWidget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = GlanceWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; };
+ C4A11E0330C1000100000000 /* QuickActions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuickActions.swift; sourceTree = "<group>"; };
+ C4A11E0330C1000200000000 /* ThreeWsAppPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThreeWsAppPlugin.swift; sourceTree = "<group>"; };
+ C4A11E0330C1000300000000 /* SharedInbox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedInbox.swift; sourceTree = "<group>"; };
+ C4A11E0330C1000400000000 /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = "<group>"; };
+ C4A11E0330C1000500000000 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+ C4A11E0330C1000600000000 /* ShareExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ShareExtension.entitlements; sourceTree = "<group>"; };
+ C4A11E0330C1000700000000 /* ShareExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -109,6 +130,13 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ C4A11E0330C1006200000000 /* Frameworks */ = {
+ isa = PBXFrameworksBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -117,6 +145,7 @@
children = (
958DCC722DB07C7200EA8C5F /* debug.xcconfig */,
504EC3061FED79650016851F /* App */,
+ C4A11E0330C1002000000000 /* ShareExtension */,
C4A11E0230B1002000000000 /* Glance */,
504EC3051FED79650016851F /* Products */,
);
@@ -127,6 +156,7 @@
children = (
504EC3041FED79650016851F /* App.app */,
C4A11E0230B1000E00000000 /* GlanceWidget.appex */,
+ C4A11E0330C1000700000000 /* ShareExtension.appex */,
);
name = Products;
sourceTree = "<group>";
@@ -140,6 +170,8 @@
50379B222058CBB4000EE86E /* capacitor.config.json */,
504EC3071FED79650016851F /* AppDelegate.swift */,
7A31B0C14E5F41A290C30011 /* MainViewController.swift */,
+ C4A11E0330C1000100000000 /* QuickActions.swift */,
+ C4A11E0330C1000200000000 /* ThreeWsAppPlugin.swift */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
504EC3101FED79650016851F /* LaunchScreen.storyboard */,
@@ -188,6 +220,17 @@
path = ../../../apple/GlanceWidget;
sourceTree = SOURCE_ROOT;
};
+ C4A11E0330C1002000000000 /* ShareExtension */ = {
+ isa = PBXGroup;
+ children = (
+ C4A11E0330C1000400000000 /* ShareViewController.swift */,
+ C4A11E0330C1000300000000 /* SharedInbox.swift */,
+ C4A11E0330C1000500000000 /* Info.plist */,
+ C4A11E0330C1000600000000 /* ShareExtension.entitlements */,
+ );
+ path = ShareExtension;
+ sourceTree = "<group>";
+ };
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -204,6 +247,7 @@
);
dependencies = (
C4A11E0230B1006500000000 /* PBXTargetDependency */,
+ C4A11E0330C1006500000000 /* PBXTargetDependency */,
);
name = App;
packageProductDependencies = (
@@ -229,6 +273,22 @@
productReference = C4A11E0230B1000E00000000 /* GlanceWidget.appex */;
productType = "com.apple.product-type.app-extension";
};
+ C4A11E0330C1006000000000 /* ShareExtension */ = {
+ isa = PBXNativeTarget;
+ buildConfigurationList = C4A11E0330C1006700000000 /* Build configuration list for PBXNativeTarget "ShareExtension" */;
+ buildPhases = (
+ C4A11E0330C1006100000000 /* Sources */,
+ C4A11E0330C1006200000000 /* Frameworks */,
+ );
+ buildRules = (
+ );
+ dependencies = (
+ );
+ name = ShareExtension;
+ productName = ShareExtension;
+ productReference = C4A11E0330C1000700000000 /* ShareExtension.appex */;
+ productType = "com.apple.product-type.app-extension";
+ };
/* End PBXNativeTarget section */
/* Begin PBXProject section */
@@ -247,6 +307,10 @@
CreatedOnToolsVersion = 15.0;
ProvisioningStyle = Automatic;
};
+ C4A11E0330C1006000000000 = {
+ CreatedOnToolsVersion = 15.0;
+ ProvisioningStyle = Automatic;
+ };
};
};
buildConfigurationList = 504EC2FF1FED79650016851F /* Build configuration list for PBXProject "App" */;
@@ -267,6 +331,7 @@
targets = (
504EC3031FED79650016851F /* App */,
C4A11E0230B1006000000000 /* GlanceWidgetExtension */,
+ C4A11E0330C1006000000000 /* ShareExtension */,
);
};
/* End PBXProject section */
@@ -302,6 +367,9 @@
C4A11E0230B1003300000000 /* GlanceTokenStore.swift in Sources */,
C4A11E0230B1003400000000 /* GlanceCache.swift in Sources */,
C4A11E0230B1003500000000 /* GlanceLink.swift in Sources */,
+ C4A11E0330C1001100000000 /* QuickActions.swift in Sources */,
+ C4A11E0330C1001200000000 /* ThreeWsAppPlugin.swift in Sources */,
+ C4A11E0330C1001300000000 /* SharedInbox.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -323,6 +391,15 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
+ C4A11E0330C1006100000000 /* Sources */ = {
+ isa = PBXSourcesBuildPhase;
+ buildActionMask = 2147483647;
+ files = (
+ C4A11E0330C1001500000000 /* ShareViewController.swift in Sources */,
+ C4A11E0330C1001400000000 /* SharedInbox.swift in Sources */,
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ };
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
@@ -331,6 +408,11 @@
target = C4A11E0230B1006000000000 /* GlanceWidgetExtension */;
targetProxy = C4A11E0230B1006600000000 /* PBXContainerItemProxy */;
};
+ C4A11E0330C1006500000000 /* PBXTargetDependency */ = {
+ isa = PBXTargetDependency;
+ target = C4A11E0330C1006000000000 /* ShareExtension */;
+ targetProxy = C4A11E0330C1006600000000 /* PBXContainerItemProxy */;
+ };
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -596,6 +678,72 @@
};
name = Release;
};
+ C4A11E0330C1006800000000 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ APPLICATION_EXTENSION_API_ONLY = YES;
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 1;
+ GENERATE_INFOPLIST_FILE = NO;
+ /* The App Group the extension parks shares in and the app reads
+ them from. Same value as the app and the glance widget. */
+ GLANCE_APP_GROUP = group.ws.three.app;
+ INFOPLIST_FILE = ShareExtension/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 16.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ MARKETING_VERSION = 1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = ws.three.app.share;
+ PRODUCT_NAME = ShareExtension;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Debug;
+ };
+ C4A11E0330C1006900000000 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ALWAYS_SEARCH_USER_PATHS = NO;
+ APPLICATION_EXTENSION_API_ONLY = YES;
+ CLANG_ENABLE_MODULES = YES;
+ CLANG_ENABLE_OBJC_ARC = YES;
+ CODE_SIGN_ENTITLEMENTS = ShareExtension/ShareExtension.entitlements;
+ CODE_SIGN_STYLE = Automatic;
+ CURRENT_PROJECT_VERSION = 1;
+ GENERATE_INFOPLIST_FILE = NO;
+ /* The App Group the extension parks shares in and the app reads
+ them from. Same value as the app and the glance widget. */
+ GLANCE_APP_GROUP = group.ws.three.app;
+ INFOPLIST_FILE = ShareExtension/Info.plist;
+ IPHONEOS_DEPLOYMENT_TARGET = 16.0;
+ LD_RUNPATH_SEARCH_PATHS = (
+ "$(inherited)",
+ "@executable_path/Frameworks",
+ "@executable_path/../../Frameworks",
+ );
+ MARKETING_VERSION = 1.0;
+ PRODUCT_BUNDLE_IDENTIFIER = ws.three.app.share;
+ PRODUCT_NAME = ShareExtension;
+ SDKROOT = iphoneos;
+ SKIP_INSTALL = YES;
+ SWIFT_COMPILATION_MODE = wholemodule;
+ SWIFT_OPTIMIZATION_LEVEL = "-O";
+ SWIFT_VERSION = 5.0;
+ TARGETED_DEVICE_FAMILY = "1,2";
+ };
+ name = Release;
+ };
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -626,6 +774,15 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
+ C4A11E0330C1006700000000 /* Build configuration list for PBXNativeTarget "ShareExtension" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ C4A11E0330C1006800000000 /* Debug */,
+ C4A11E0330C1006900000000 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
diff --git a/ios/native/App/App/AppDelegate.swift b/ios/native/App/App/AppDelegate.swift
index f5293d6f4..2e270fadb 100644
--- a/ios/native/App/App/AppDelegate.swift
+++ b/ios/native/App/App/AppDelegate.swift
@@ -7,30 +7,24 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
- // Override point for customization after application launch.
+ // Shares older than a day were abandoned (the user never came back to
+ // the app). Their files are in the shared App Group, which is backed
+ // up and counted against the user's storage, so they do not linger.
+ SharedInbox.sweep()
return true
}
- func applicationWillResignActive(_ application: UIApplication) {
- // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
- // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
+ // APNs hands the device token to the app delegate and to nothing else.
+ // The PushNotifications plugin listens for these two Capacitor
+ // notifications; without the forwarding, `register()` in the WebView never
+ // resolves and the device is never enrolled for push. The web half that
+ // sends the token to /api/push/device is src/push-notifications.js.
+ func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
+ NotificationCenter.default.post(name: .capacitorDidRegisterForRemoteNotifications, object: deviceToken)
}
- func applicationDidEnterBackground(_ application: UIApplication) {
- // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
- // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
- }
-
- func applicationWillEnterForeground(_ application: UIApplication) {
- // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
- }
-
- func applicationDidBecomeActive(_ application: UIApplication) {
- // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
- }
-
- func applicationWillTerminate(_ application: UIApplication) {
- // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
+ func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
+ NotificationCenter.default.post(name: .capacitorDidFailToRegisterForRemoteNotifications, object: error)
}
func application(_ application: UIApplication,
diff --git a/ios/native/App/App/Info.plist b/ios/native/App/App/Info.plist
index 9dc2dbc7d..48959dac3 100644
--- a/ios/native/App/App/Info.plist
+++ b/ios/native/App/App/Info.plist
@@ -30,8 +30,8 @@
are declared in App.entitlements + public/.well-known/apple-app-site-association;
this custom scheme is the fallback that wallet and OAuth redirects can always
reach, including from a Safari view controller that cannot resolve an
- associated domain. Handled in AppDelegate -> Capacitor's App plugin ->
- src/native-bridge.js.
+ associated domain. Handled in SceneDelegate -> Capacitor's App plugin ->
+ ios/src/native-bridge.js.
-->
<key>CFBundleURLTypes</key>
<array>
@@ -81,6 +81,83 @@
<key>NSMotionUsageDescription</key>
<string>three.ws reads device motion to keep an agent anchored in place as you move the camera.</string>
+ <!--
+ Home screen quick actions: press and hold the icon. The same doors as the
+ Android app's launcher shortcuts (solana-mobile/twa/twa-manifest.json),
+ plus the inbox, which is where a push lands. Each type maps to a page in
+ QuickActions.swift; declaring them here rather than in code means they
+ exist from install, before the app has ever been opened.
+ -->
+ <key>UIApplicationShortcutItems</key>
+ <array>
+ <dict>
+ <key>UIApplicationShortcutItemType</key>
+ <string>ws.three.app.create</string>
+ <key>UIApplicationShortcutItemTitle</key>
+ <string>Create avatar</string>
+ <key>UIApplicationShortcutItemIconSymbolName</key>
+ <string>sparkles</string>
+ </dict>
+ <dict>
+ <key>UIApplicationShortcutItemType</key>
+ <string>ws.three.app.discover</string>
+ <key>UIApplicationShortcutItemTitle</key>
+ <string>Discover</string>
+ <key>UIApplicationShortcutItemSubtitle</key>
+ <string>Marketplace</string>
+ <key>UIApplicationShortcutItemIconSymbolName</key>
+ <string>square.grid.2x2</string>
+ </dict>
+ <dict>
+ <key>UIApplicationShortcutItemType</key>
+ <string>ws.three.app.agents</string>
+ <key>UIApplicationShortcutItemTitle</key>
+ <string>My agents</string>
+ <key>UIApplicationShortcutItemIconSymbolName</key>
+ <string>person.2</string>
+ </dict>
+ <dict>
+ <key>UIApplicationShortcutItemType</key>
+ <string>ws.three.app.notifications</string>
+ <key>UIApplicationShortcutItemTitle</key>
+ <string>Notifications</string>
+ <key>UIApplicationShortcutItemIconSymbolName</key>
+ <string>bell</string>
+ </dict>
+ </array>
+
+ <!--
+ Binary glTF. iOS ships no identifier for .glb, so a model in Files would
+ otherwise carry an anonymous dynamic type the share extension's
+ activation rule cannot name. Imported, not exported: three.ws does not
+ own the format, and an app that declares it too simply agrees with us.
+ -->
+ <key>UTImportedTypeDeclarations</key>
+ <array>
+ <dict>
+ <key>UTTypeIdentifier</key>
+ <string>org.khronos.glb</string>
+ <key>UTTypeDescription</key>
+ <string>glTF binary model</string>
+ <key>UTTypeConformsTo</key>
+ <array>
+ <string>public.data</string>
+ <string>public.content</string>
+ </array>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array>
+ <string>glb</string>
+ </array>
+ <key>public.mime-type</key>
+ <array>
+ <string>model/gltf-binary</string>
+ </array>
+ </dict>
+ </dict>
+ </array>
+
<!-- Push notifications arriving while the app is backgrounded. -->
<key>UIBackgroundModes</key>
<array>
diff --git a/ios/native/App/App/MainViewController.swift b/ios/native/App/App/MainViewController.swift
index 7f08045dd..2be93d308 100644
--- a/ios/native/App/App/MainViewController.swift
+++ b/ios/native/App/App/MainViewController.swift
@@ -51,4 +51,28 @@ class MainViewController: CAPBridgeViewController {
// a CarPlay scene can ever connect. It is inert until one does.
if let webView { DriveLink.shared.attach(to: webView) }
}
+
+ /// Registers the app's own plugin beside the packaged ones. It is not a
+ /// Swift package, so the SPM plugin graph never discovers it; this is the
+ /// hook Capacitor gives an app for exactly that case.
+ override func capacitorDidLoad() {
+ bridge?.registerPluginInstance(ThreeWsAppPlugin())
+ }
+
+ /// Navigates the WebView to a path on the product origin.
+ ///
+ /// Native entry points (quick actions, a collected share) arrive as a path
+ /// rather than a URL, and only ever resolve against three.ws, so nothing
+ /// that reaches this method can point the app's only WebView off-site.
+ func open(path: String) {
+ guard path.hasPrefix("/"), !path.hasPrefix("//"),
+ let url = URL(string: path, relativeTo: MainViewController.origin)?.absoluteURL,
+ url.host == MainViewController.origin.host
+ else { return }
+ if webView?.url == url { return }
+ webView?.load(URLRequest(url: url))
+ }
+
+ /// The origin the WebView serves, which is `server.url` in capacitor.config.ts.
+ static let origin = URL(string: "https://three.ws")!
}
diff --git a/ios/native/App/App/QuickActions.swift b/ios/native/App/App/QuickActions.swift
new file mode 100644
index 000000000..430fa90ff
--- /dev/null
+++ b/ios/native/App/App/QuickActions.swift
@@ -0,0 +1,30 @@
+import UIKit
+
+/// The home screen quick actions: press and hold the three.ws icon.
+///
+/// They are declared statically in Info.plist (`UIApplicationShortcutItems`) so
+/// they exist from the moment the app is installed, before it has ever been
+/// opened, and they mirror the Android app's launcher shortcuts in
+/// solana-mobile/twa/twa-manifest.json one for one, so the two apps offer the
+/// same three doors. The `type` of each item is the only thing read here; the
+/// title and icon live in the plist where iOS localises them.
+enum QuickActions {
+ /// `UIApplicationShortcutItemType` values and the page each one opens. The
+ /// `utm_source` keeps quick-action traffic distinguishable in analytics
+ /// from an ordinary launch, the same way the Android shortcuts are tagged.
+ static let routes: [String: String] = [
+ "ws.three.app.create": "/create?utm_source=ios_shortcut",
+ "ws.three.app.discover": "/marketplace?utm_source=ios_shortcut",
+ "ws.three.app.agents": "/my-agents?utm_source=ios_shortcut",
+ "ws.three.app.notifications": "/notifications?utm_source=ios_shortcut",
+ ]
+
+ /// Opens the page for `item`. Returns false for a type this build does not
+ /// know, which is what an item left behind by an older build would be.
+ @discardableResult
+ static func perform(_ item: UIApplicationShortcutItem, in controller: MainViewController) -> Bool {
+ guard let path = routes[item.type] else { return false }
+ controller.open(path: path)
+ return true
+ }
+}
diff --git a/ios/native/App/App/SceneDelegate.swift b/ios/native/App/App/SceneDelegate.swift
index 3a524286c..f2ec28ea9 100644
--- a/ios/native/App/App/SceneDelegate.swift
+++ b/ios/native/App/App/SceneDelegate.swift
@@ -7,8 +7,14 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
+ // MainViewController, not Capacitor's stock CAPBridgeViewController.
+ // Building the window here replaces whatever Main.storyboard names, so
+ // this line is the only thing that decides which controller hosts the
+ // WebView. With the stock class the app silently loses edge-swipe back,
+ // the dark chrome, the CarPlay channel and the ThreeWsApp plugin.
+ let main = MainViewController()
window = UIWindow(windowScene: windowScene)
- window?.rootViewController = CAPBridgeViewController()
+ window?.rootViewController = main
window?.makeKeyAndVisible()
// A cold launch straight from the widget link on three.ws/glance. The
@@ -18,6 +24,13 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
GlanceLink.claim(context.url)
}
+ // A cold launch from a home screen quick action. The WebView has just
+ // started loading the start URL; loading the action's page instead
+ // replaces that navigation rather than stacking a second one on it.
+ if let item = connectionOptions.shortcutItem {
+ QuickActions.perform(item, in: main)
+ }
+
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
}
@@ -34,4 +47,29 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
SceneDelegateProxy.shared.scene(scene, continue: userActivity)
}
+
+ /// A quick action chosen while the app was already running.
+ func windowScene(_ windowScene: UIWindowScene,
+ performActionFor shortcutItem: UIApplicationShortcutItem,
+ completionHandler: @escaping (Bool) -> Void) {
+ guard let main = window?.rootViewController as? MainViewController else {
+ completionHandler(false)
+ return
+ }
+ completionHandler(QuickActions.perform(shortcutItem, in: main))
+ }
+
+ /// Picks up a photo or model shared from another app.
+ ///
+ /// The share extension cannot open the app itself (Apple withholds
+ /// `UIApplication.open` from extensions), so it parks the files in the App
+ /// Group and the app collects them the next time it comes forward, which is
+ /// what the sheet tells the user to do. `claimPending` consumes the marker,
+ /// so a share is routed exactly once however often the app is activated.
+ func sceneDidBecomeActive(_ scene: UIScene) {
+ guard let main = window?.rootViewController as? MainViewController,
+ let share = SharedInbox.claimPending()
+ else { return }
+ main.open(path: share.landingPath)
+ }
}
diff --git a/ios/native/App/App/ThreeWsAppPlugin.swift b/ios/native/App/App/ThreeWsAppPlugin.swift
new file mode 100644
index 000000000..92887221d
--- /dev/null
+++ b/ios/native/App/App/ThreeWsAppPlugin.swift
@@ -0,0 +1,58 @@
+import Foundation
+import Capacitor
+import UserNotifications
+
+/// The app's own Capacitor plugin, for the two things no packaged plugin does.
+///
+/// - `takeShare({ id })` hands the page the files the share extension parked in
+/// the App Group (see SharedInbox.swift). src/shared/share-target.js calls it
+/// in place of reading the service worker cache, which the iOS WebView lacks.
+/// - `setBadge({ count })` keeps the home screen icon's badge equal to the
+/// inbox's unread count. APNs sets it when a push arrives; this is what
+/// brings it back down when the notifications are read in the app.
+///
+/// Registered in MainViewController.capacitorDidLoad, and reached from the web
+/// as `Capacitor.Plugins.ThreeWsApp`.
+@objc(ThreeWsAppPlugin)
+public class ThreeWsAppPlugin: CAPPlugin, CAPBridgedPlugin {
+ public let identifier = "ThreeWsAppPlugin"
+ public let jsName = "ThreeWsApp"
+ public let pluginMethods: [CAPPluginMethod] = [
+ CAPPluginMethod(name: "takeShare", returnType: CAPPluginReturnPromise),
+ CAPPluginMethod(name: "setBadge", returnType: CAPPluginReturnPromise),
+ ]
+
+ @objc func takeShare(_ call: CAPPluginCall) {
+ guard let id = call.getString("id"), SharedInbox.isValidId(id) else {
+ call.reject("A share id is required", "invalid_id")
+ return
+ }
+ // File reads and base64 of a model can take a moment; keep them off the
+ // main thread the bridge dispatches on.
+ DispatchQueue.global(qos: .userInitiated).async {
+ guard let taken = SharedInbox.take(id: id) else {
+ call.reject("That share has expired or was already opened", "not_found")
+ return
+ }
+ let files: [JSObject] = zip(taken.share.files, taken.files).map { meta, bytes in
+ ["name": meta.name, "type": meta.type, "data": bytes.base64EncodedString()]
+ }
+ call.resolve([
+ "kind": taken.share.kind.rawValue,
+ "createdAt": Int(taken.share.createdAt.timeIntervalSince1970 * 1000),
+ "files": files,
+ ])
+ }
+ }
+
+ @objc func setBadge(_ call: CAPPluginCall) {
+ let count = max(0, call.getInt("count") ?? 0)
+ UNUserNotificationCenter.current().setBadgeCount(count) { error in
+ if let error {
+ call.reject(error.localizedDescription)
+ } else {
+ call.resolve()
+ }
+ }
+ }
+}
diff --git a/ios/native/App/ShareExtension/Info.plist b/ios/native/App/ShareExtension/Info.plist
new file mode 100644
index 000000000..2dd8eaca3
--- /dev/null
+++ b/ios/native/App/ShareExtension/Info.plist
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleDisplayName</key>
+ <string>three.ws</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>NSExtension</key>
+ <dict>
+ <key>NSExtensionPointIdentifier</key>
+ <string>com.apple.share-services</string>
+ <key>NSExtensionPrincipalClass</key>
+ <string>$(PRODUCT_MODULE_NAME).ShareViewController</string>
+ <key>NSExtensionAttributes</key>
+ <dict>
+ <!--
+ The same things the Android app's share target accepts
+ (solana-mobile/twa/twa-manifest.json): up to three photos, which
+ become the front, left and right angles of a selfie-to-avatar
+ run, or one binary glTF. Written as a predicate rather than the
+ dictionary form because the dictionary form has no key for a
+ file type, and a .glb is exactly that. org.khronos.glb is
+ declared by the app's Info.plist (UTImportedTypeDeclarations),
+ which is what gives a .glb in Files that identifier.
+ -->
+ <key>NSExtensionActivationRule</key>
+ <string>SUBQUERY (
+ extensionItems, $extensionItem,
+ SUBQUERY (
+ $extensionItem.attachments, $attachment,
+ ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.image"
+ ).@count BETWEEN {1, 3}
+ OR SUBQUERY (
+ $extensionItem.attachments, $attachment,
+ ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "org.khronos.glb"
+ ).@count == 1
+ ).@count >= 1</string>
+ </dict>
+ </dict>
+ <!--
+ SharedInbox.swift reads the App Group from this key, the same one the
+ app and the Agent glance widget read, so the three targets can never
+ disagree on where a share is parked.
+ -->
+ <key>GlanceAppGroup</key>
+ <string>$(GLANCE_APP_GROUP)</string>
+</dict>
+</plist>
diff --git a/ios/native/App/ShareExtension/ShareExtension.entitlements b/ios/native/App/ShareExtension/ShareExtension.entitlements
new file mode 100644
index 000000000..f8303b2d7
--- /dev/null
+++ b/ios/native/App/ShareExtension/ShareExtension.entitlements
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!--
+ The share extension writes shared photos and models into the App Group
+ container, and the app reads them back out (SharedInbox.swift). Without
+ the shared group the two processes cannot see each other's files and
+ every share arrives at an empty inbox.
+ -->
+ <key>com.apple.security.application-groups</key>
+ <array>
+ <string>$(GLANCE_APP_GROUP)</string>
+ </array>
+</dict>
+</plist>
diff --git a/ios/native/App/ShareExtension/ShareViewController.swift b/ios/native/App/ShareExtension/ShareViewController.swift
new file mode 100644
index 000000000..5468eb3b3
--- /dev/null
+++ b/ios/native/App/ShareExtension/ShareViewController.swift
@@ -0,0 +1,275 @@
+import UIKit
+import UniformTypeIdentifiers
+import UserNotifications
+
+/// The three.ws entry in the system share sheet.
+///
+/// Share one to three photos and they become the front, left and right angles
+/// of a selfie-to-avatar run; share a `.glb` and it lands in the upload flow.
+/// This is the iOS counterpart of the Android app's web share target, and it
+/// accepts the same things (solana-mobile/twa/twa-manifest.json `shareTarget`).
+///
+/// The extension does the part only it can do, copying the files out of the
+/// sending app while it still has access to them, and nothing else. Photos are
+/// normalised to JPEG here because the page's pipeline reads JPEG, PNG and
+/// WebP, and an iPhone photo arrives as HEIC.
+final class ShareViewController: UIViewController {
+ /// Longest edge of a shared photo. Matches what /create/selfie downsizes to
+ /// before upload, so nothing is lost and the hand-off stays small.
+ private static let maxPhotoEdge: CGFloat = 2048
+ /// The page receives the model as one base64 string across the Capacitor
+ /// bridge, which roughly doubles it in memory. Past this an older phone's
+ /// WebView process is at risk of being killed mid hand-off.
+ private static let maxModelBytes = 64 * 1024 * 1024
+ private static let glbType = "org.khronos.glb"
+
+ private let card = UIView()
+ private let preview = UIImageView()
+ private let titleLabel = UILabel()
+ private let statusLabel = UILabel()
+ private let spinner = UIActivityIndicatorView(style: .medium)
+ private let doneButton = UIButton(type: .system)
+ /// Scratch space for copies on their way into the inbox. A stored share has
+ /// already moved its files out; whatever a failed one left is deleted.
+ private lazy var staging = FileManager.default.temporaryDirectory
+ .appendingPathComponent(UUID().uuidString, isDirectory: true)
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+ buildInterface()
+ collect()
+ }
+
+ // MARK: - Collecting
+
+ private enum Outcome {
+ case stored(SharedShare)
+ case failed(String)
+ }
+
+ private func collect() {
+ let providers = (extensionContext?.inputItems as? [NSExtensionItem] ?? [])
+ .flatMap { $0.attachments ?? [] }
+ let models = providers.filter(isModel)
+ let photos = providers.filter { !isModel($0) && $0.hasItemConformingToTypeIdentifier(UTType.image.identifier) }
+
+ try? FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)
+
+ if let model = models.first {
+ loadModel(model, into: staging) { [weak self] outcome in self?.finish(outcome) }
+ } else if !photos.isEmpty {
+ loadPhotos(Array(photos.prefix(3)), into: staging) { [weak self] outcome in self?.finish(outcome) }
+ } else {
+ finish(.failed("three.ws takes photos and .glb models. This item is neither."))
+ }
+ }
+
+ private func isModel(_ provider: NSItemProvider) -> Bool {
+ if provider.hasItemConformingToTypeIdentifier(Self.glbType) { return true }
+ return provider.suggestedName?.lowercased().hasSuffix(".glb") == true
+ }
+
+ private func loadPhotos(_ providers: [NSItemProvider], into staging: URL, completion: @escaping (Outcome) -> Void) {
+ // The providers call back on arbitrary queues, so every write to the
+ // slots goes through one lock. Order is kept by index, not by arrival:
+ // the first photo shared is the one that becomes the front view.
+ var slots = [URL?](repeating: nil, count: providers.count)
+ let lock = NSLock()
+ let group = DispatchGroup()
+ for (index, provider) in providers.enumerated() {
+ group.enter()
+ provider.loadDataRepresentation(forTypeIdentifier: UTType.image.identifier) { data, _ in
+ defer { group.leave() }
+ guard let data, let jpeg = Self.normalisedJPEG(data) else { return }
+ let url = staging.appendingPathComponent("photo-\(index).jpg")
+ guard (try? jpeg.write(to: url, options: .atomic)) != nil else { return }
+ lock.lock()
+ slots[index] = url
+ lock.unlock()
+ }
+ }
+ group.notify(queue: .main) {
+ let files = slots.enumerated().compactMap { index, url in
+ url.map { (source: $0, name: "shared-photo-\(index + 1).jpg", type: "image/jpeg") }
+ }
+ guard !files.isEmpty else {
+ completion(.failed("That photo could not be read. Try saving it to Photos and sharing it from there."))
+ return
+ }
+ completion(Self.store(.photo, files))
+ }
+ }
+
+ private func loadModel(_ provider: NSItemProvider, into staging: URL, completion: @escaping (Outcome) -> Void) {
+ let type = provider.hasItemConformingToTypeIdentifier(Self.glbType) ? Self.glbType : UTType.data.identifier
+ let name = Self.modelName(provider.suggestedName)
+ provider.loadFileRepresentation(forTypeIdentifier: type) { url, _ in
+ // The URL is only valid inside this callback, so the copy happens here.
+ var outcome: Outcome = .failed("That model could not be read. Try sharing it again.")
+ if let url {
+ let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0
+ let target = staging.appendingPathComponent("model.glb")
+ if size > Self.maxModelBytes {
+ outcome = .failed("That model is over 64 MB. Upload it from three.ws/create on a computer instead.")
+ } else if (try? FileManager.default.copyItem(at: url, to: target)) != nil, Self.hasGlbMagic(target) {
+ outcome = Self.store(.model, [(source: target, name: name, type: "model/gltf-binary")])
+ } else {
+ outcome = .failed("That file is not a binary glTF (.glb) model.")
+ }
+ }
+ DispatchQueue.main.async { completion(outcome) }
+ }
+ }
+
+ private static func store(_ kind: SharedShare.Kind, _ files: [(source: URL, name: String, type: String)]) -> Outcome {
+ do {
+ return .stored(try SharedInbox.store(kind: kind, files: files))
+ } catch {
+ return .failed("three.ws could not save this share. Open the app once, then try again.")
+ }
+ }
+
+ /// Decodes any image iOS can read (HEIC, PNG, WebP, RAW previews) and
+ /// re-encodes it as an upright JPEG no larger than `maxPhotoEdge`.
+ private static func normalisedJPEG(_ data: Data) -> Data? {
+ guard let image = UIImage(data: data) else { return nil }
+ let longest = max(image.size.width, image.size.height)
+ guard longest > 0 else { return nil }
+ let scale = min(1, maxPhotoEdge / longest)
+ let size = CGSize(width: floor(image.size.width * scale), height: floor(image.size.height * scale))
+ let format = UIGraphicsImageRendererFormat()
+ format.scale = 1
+ let rendered = UIGraphicsImageRenderer(size: size, format: format).image { _ in
+ image.draw(in: CGRect(origin: .zero, size: size))
+ }
+ return rendered.jpegData(compressionQuality: 0.9)
+ }
+
+ private static func hasGlbMagic(_ url: URL) -> Bool {
+ guard let handle = try? FileHandle(forReadingFrom: url) else { return false }
+ defer { try? handle.close() }
+ return (try? handle.read(upToCount: 4)) == Data("glTF".utf8)
+ }
+
+ private static func modelName(_ suggested: String?) -> String {
+ let base = (suggested ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !base.isEmpty else { return "shared-model.glb" }
+ return base.lowercased().hasSuffix(".glb") ? base : "\(base).glb"
+ }
+
+ // MARK: - Finishing
+
+ private func finish(_ outcome: Outcome) {
+ try? FileManager.default.removeItem(at: staging)
+ spinner.stopAnimating()
+ doneButton.isEnabled = true
+ switch outcome {
+ case .stored(let share):
+ titleLabel.text = share.kind == .photo ? "Photo ready" : "Model ready"
+ statusLabel.text = share.kind == .photo
+ ? "Open three.ws and it will be waiting in Create, ready to become a 3D avatar."
+ : "Open three.ws and it will be waiting in Create, ready to upload."
+ doneButton.setTitle("Done", for: .normal)
+ remind(about: share)
+ UINotificationFeedbackGenerator().notificationOccurred(.success)
+ case .failed(let message):
+ titleLabel.text = "Could not share"
+ statusLabel.text = message
+ doneButton.setTitle("Close", for: .normal)
+ UINotificationFeedbackGenerator().notificationOccurred(.error)
+ }
+ UIAccessibility.post(notification: .announcement, argument: statusLabel.text)
+ }
+
+ /// A tappable way back into the app, for someone who already allowed
+ /// three.ws notifications. Never asks: a permission prompt from inside a
+ /// share sheet is the wrong moment and App Review agrees.
+ private func remind(about share: SharedShare) {
+ let center = UNUserNotificationCenter.current()
+ center.getNotificationSettings { settings in
+ guard settings.authorizationStatus == .authorized else { return }
+ let content = UNMutableNotificationContent()
+ content.title = share.kind == .photo ? "Your photo is ready" : "Your model is ready"
+ content.body = share.kind == .photo ? "Tap to turn it into a 3D avatar." : "Tap to upload it to three.ws."
+ content.threadIdentifier = "share"
+ let request = UNNotificationRequest(identifier: "share-\(share.id)", content: content,
+ trigger: UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false))
+ center.add(request)
+ }
+ }
+
+ @objc private func close() {
+ extensionContext?.completeRequest(returningItems: nil)
+ }
+
+ // MARK: - Interface
+
+ private func buildInterface() {
+ let ink = UIColor(red: 0x08 / 255.0, green: 0x08 / 255.0, blue: 0x14 / 255.0, alpha: 1)
+ view.backgroundColor = UIColor.black.withAlphaComponent(0.35)
+
+ card.backgroundColor = ink
+ card.layer.cornerRadius = 20
+ card.layer.cornerCurve = .continuous
+ card.translatesAutoresizingMaskIntoConstraints = false
+ view.addSubview(card)
+
+ let mark = UIImageView(image: UIImage(systemName: "cube.transparent"))
+ mark.tintColor = .white
+ mark.contentMode = .scaleAspectFit
+ mark.accessibilityLabel = "three.ws"
+
+ titleLabel.text = "Preparing"
+ titleLabel.font = .preferredFont(forTextStyle: .headline)
+ titleLabel.adjustsFontForContentSizeCategory = true
+ titleLabel.textColor = .white
+
+ statusLabel.text = "Copying from the app you shared from."
+ statusLabel.font = .preferredFont(forTextStyle: .subheadline)
+ statusLabel.adjustsFontForContentSizeCategory = true
+ statusLabel.textColor = UIColor.white.withAlphaComponent(0.72)
+ statusLabel.numberOfLines = 0
+
+ spinner.color = .white
+ spinner.startAnimating()
+
+ var config = UIButton.Configuration.filled()
+ config.cornerStyle = .large
+ config.baseBackgroundColor = .white
+ config.baseForegroundColor = ink
+ doneButton.configuration = config
+ doneButton.setTitle("Please wait", for: .normal)
+ doneButton.isEnabled = false
+ doneButton.addTarget(self, action: #selector(close), for: .touchUpInside)
+
+ let header = UIStackView(arrangedSubviews: [mark, titleLabel, UIView(), spinner])
+ header.spacing = 10
+ header.alignment = .center
+
+ let stack = UIStackView(arrangedSubviews: [header, statusLabel, doneButton])
+ stack.axis = .vertical
+ stack.spacing = 16
+ stack.translatesAutoresizingMaskIntoConstraints = false
+ card.addSubview(stack)
+
+ let fillMargins = card.widthAnchor.constraint(equalTo: view.layoutMarginsGuide.widthAnchor)
+ fillMargins.priority = .defaultHigh
+
+ NSLayoutConstraint.activate([
+ mark.widthAnchor.constraint(equalToConstant: 26),
+ mark.heightAnchor.constraint(equalToConstant: 26),
+ doneButton.heightAnchor.constraint(greaterThanOrEqualToConstant: 48),
+ // Full width on a phone, a 420pt card centred on an iPad: the width
+ // cap wins over the margins because the margin fit is only preferred.
+ card.centerXAnchor.constraint(equalTo: view.centerXAnchor),
+ card.centerYAnchor.constraint(equalTo: view.centerYAnchor),
+ card.widthAnchor.constraint(lessThanOrEqualToConstant: 420),
+ card.leadingAnchor.constraint(greaterThanOrEqualTo: view.layoutMarginsGuide.leadingAnchor),
+ fillMargins,
+ stack.topAnchor.constraint(equalTo: card.topAnchor, constant: 22),
+ stack.leadingAnchor.constraint(equalTo: card.leadingAnchor, constant: 22),
+ stack.trailingAnchor.constraint(equalTo: card.trailingAnchor, constant: -22),
+ stack.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -22),
+ ])
+ }
+}
diff --git a/ios/native/App/ShareExtension/SharedInbox.swift b/ios/native/App/ShareExtension/SharedInbox.swift
new file mode 100644
index 000000000..1a5f01a57
--- /dev/null
+++ b/ios/native/App/ShareExtension/SharedInbox.swift
@@ -0,0 +1,174 @@
+import Foundation
+
+/// One share, as the extension recorded it.
+struct SharedShare: Codable {
+ enum Kind: String, Codable {
+ /// One to three photos. Opens the selfie-to-avatar flow, which fills the
+ /// front, left and right slots in that order.
+ case photo
+ /// A single binary glTF. Opens the upload flow on /create.
+ case model
+ }
+
+ struct File: Codable {
+ let name: String
+ let type: String
+ }
+
+ let id: String
+ let kind: Kind
+ let createdAt: Date
+ let files: [File]
+
+ /// The page that consumes this share. `inbox` is what tells
+ /// src/shared/share-target.js to read from the app rather than from the
+ /// service worker's cache, which the iOS WebView does not have.
+ var landingPath: String {
+ switch kind {
+ case .photo: return "/create/selfie?shared=1&inbox=\(id)"
+ case .model: return "/create?shared=glb&inbox=\(id)"
+ }
+ }
+}
+
+/// The hand-off between the share extension and the app.
+///
+/// Android gets this for free: the web manifest's `share_target` makes Chrome
+/// POST the files to a service worker. The iOS WebView runs no service worker
+/// and has no share target, so the extension writes the files into the App
+/// Group container both processes can see, and the app reads them back out
+/// through the `ThreeWsApp` plugin when the page asks for them.
+///
+/// Layout, under the App Group:
+///
+/// share-inbox/
+/// pending the id of the newest share nobody has opened yet
+/// <id>/manifest.json a SharedShare
+/// <id>/0, 1, 2 the files, in the order they were shared
+///
+/// A share is consumed exactly once: `take` deletes it. The same ten minute
+/// window the web hand-off uses bounds how long a share stays claimable, so a
+/// photo shared last week cannot resurface the next time the app opens.
+enum SharedInbox {
+ static let claimWindow: TimeInterval = 10 * 60
+ static let retention: TimeInterval = 24 * 60 * 60
+
+ enum InboxError: Error {
+ case noContainer
+ case empty
+ }
+
+ /// `nil` when neither the App Group nor a caches directory is available,
+ /// which a correctly signed build never sees.
+ static var root: URL? {
+ let fm = FileManager.default
+ let base: URL?
+ if let group = appGroup {
+ base = fm.containerURL(forSecurityApplicationGroupIdentifier: group)
+ } else {
+ // Unsigned development run with no App Group: the extension and the
+ // app each get their own container and simply cannot hand off.
+ base = fm.urls(for: .cachesDirectory, in: .userDomainMask).first
+ }
+ return base?.appendingPathComponent("share-inbox", isDirectory: true)
+ }
+
+ /// Records a share and marks it as the one the app should open next.
+ ///
+ /// - Parameter files: each file's bytes already on disk (the extension
+ /// copies them out of the sending app's sandbox first), with the name and
+ /// MIME type the page will see.
+ @discardableResult
+ static func store(kind: SharedShare.Kind, files: [(source: URL, name: String, type: String)]) throws -> SharedShare {
+ guard !files.isEmpty else { throw InboxError.empty }
+ guard let root else { throw InboxError.noContainer }
+ let fm = FileManager.default
+ let id = UUID().uuidString.lowercased()
+ let dir = root.appendingPathComponent(id, isDirectory: true)
+ try fm.createDirectory(at: dir, withIntermediateDirectories: true)
+
+ var entries: [SharedShare.File] = []
+ for (index, file) in files.enumerated() {
+ let target = dir.appendingPathComponent(String(index))
+ try? fm.removeItem(at: target)
+ try fm.moveItem(at: file.source, to: target)
+ entries.append(SharedShare.File(name: file.name, type: file.type))
+ }
+
+ let share = SharedShare(id: id, kind: kind, createdAt: Date(), files: entries)
+ try encoder.encode(share).write(to: dir.appendingPathComponent("manifest.json"), options: .atomic)
+ try Data(id.utf8).write(to: root.appendingPathComponent("pending"), options: .atomic)
+ return share
+ }
+
+ /// The share waiting to be opened, if there is a fresh one. Consumes the
+ /// marker, so the next activation of the app does not route to it again.
+ static func claimPending() -> SharedShare? {
+ guard let root else { return nil }
+ let marker = root.appendingPathComponent("pending")
+ guard let data = try? Data(contentsOf: marker) else { return nil }
+ try? FileManager.default.removeItem(at: marker)
+ guard let id = String(data: data, encoding: .utf8), let share = manifest(id: id) else { return nil }
+ return Date().timeIntervalSince(share.createdAt) <= claimWindow ? share : nil
+ }
+
+ /// Reads a share's files and deletes it. `nil` for an unknown, malformed or
+ /// expired id: the id arrives from the WebView, so it is validated before
+ /// it is ever joined onto a path.
+ static func take(id: String) -> (share: SharedShare, files: [Data])? {
+ guard isValidId(id), let root, let share = manifest(id: id) else { return nil }
+ let dir = root.appendingPathComponent(id, isDirectory: true)
+ defer { try? FileManager.default.removeItem(at: dir) }
+ guard Date().timeIntervalSince(share.createdAt) <= claimWindow else { return nil }
+ var files: [Data] = []
+ for index in share.files.indices {
+ guard let bytes = try? Data(contentsOf: dir.appendingPathComponent(String(index))) else { return nil }
+ files.append(bytes)
+ }
+ return (share, files)
+ }
+
+ /// Deletes every share older than `retention`. Called at launch.
+ static func sweep() {
+ guard let root else { return }
+ let fm = FileManager.default
+ guard let entries = try? fm.contentsOfDirectory(at: root, includingPropertiesForKeys: [.creationDateKey]) else { return }
+ let cutoff = Date().addingTimeInterval(-retention)
+ for entry in entries where entry.lastPathComponent != "pending" {
+ let created = (try? entry.resourceValues(forKeys: [.creationDateKey]))?.creationDate ?? .distantPast
+ if created < cutoff { try? fm.removeItem(at: entry) }
+ }
+ }
+
+ static func isValidId(_ id: String) -> Bool {
+ UUID(uuidString: id) != nil && id == id.lowercased()
+ }
+
+ private static func manifest(id: String) -> SharedShare? {
+ guard isValidId(id), let root else { return nil }
+ let url = root.appendingPathComponent(id, isDirectory: true).appendingPathComponent("manifest.json")
+ guard let data = try? Data(contentsOf: url) else { return nil }
+ return try? decoder.decode(SharedShare.self, from: data)
+ }
+
+ /// The App Group shared with the Agent glance widget. Both targets expand
+ /// the `GLANCE_APP_GROUP` build setting into this Info.plist key; a value
+ /// starting with a dot means `DEVELOPMENT_TEAM` was unset at build time.
+ private static var appGroup: String? {
+ guard let raw = Bundle.main.object(forInfoDictionaryKey: "GlanceAppGroup") as? String else { return nil }
+ let value = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ return value.isEmpty || value.hasPrefix(".") ? nil : value
+ }
+
+ private static var encoder: JSONEncoder {
+ let e = JSONEncoder()
+ e.dateEncodingStrategy = .secondsSince1970
+ return e
+ }
+
+ private static var decoder: JSONDecoder {
+ let d = JSONDecoder()
+ d.dateDecodingStrategy = .secondsSince1970
+ return d
+ }
+}
diff --git a/scripts/check-apple-widget.mjs b/scripts/check-apple-widget.mjs
index c7a72cb23..b88810bb9 100644
--- a/scripts/check-apple-widget.mjs
+++ b/scripts/check-apple-widget.mjs
@@ -110,9 +110,13 @@ for (const file of KIT_APP_FILES) {
pass('every shared source is a member of the iOS targets that need it');
for (const setting of SETTINGS) {
- // Once in each of the app's two configurations and the extension's two.
+ // Once in each of the app's two configurations and the widget's two. The
+ // App Group is also the share extension's hand-off container, so it is
+ // defined on that target's two configurations as well
+ // (scripts/check-ios-app.mjs holds the share extension to it).
+ const expected = setting === 'GLANCE_APP_GROUP' ? 6 : 4;
const count = (pbx.match(new RegExp(`^\\s*${setting} = `, 'gm')) || []).length;
- if (count !== 4) fail(`${setting} is defined ${count} times in project.pbxproj, expected 4 (both targets, both configurations)`);
+ if (count !== expected) fail(`${setting} is defined ${count} times in project.pbxproj, expected ${expected} (every target that reads it, both configurations)`);
}
pass('the iOS project defines the three Glance build settings on both targets');