@agimon-ai/po-native 0.0.1-alpha.78 → 0.0.1-alpha.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/app.config.ts +11 -0
- package/package.json +14 -12
- package/src/app/App.tsx +33 -12
- package/src/app/hostRuntimes.ts +6 -0
- package/src/components/WakePeriodView.tsx +1 -1
- package/src/components/liveActivity/SessionActivity.stories.tsx +149 -0
- package/src/services/liveActivity/SessionActivity.ios.tsx +108 -0
- package/src/services/liveActivity/index.ios.ts +216 -0
- package/src/services/liveActivity/index.ts +6 -0
- package/src/services/liveActivity/lifecycle.ts +253 -0
- package/src/services/nativePush/index.ts +4 -14
- package/src/services/sessionTap.ts +47 -0
package/README.md
CHANGED
|
@@ -52,7 +52,8 @@ The build script validates required inputs before replacing earlier final artifa
|
|
|
52
52
|
| Input | Use |
|
|
53
53
|
| ------------------------------------- | ------------------------------------------------------------------------------ |
|
|
54
54
|
| `APPLE_TEAM_ID` | Required iOS signing team |
|
|
55
|
-
| `PO_NATIVE_IOS_PROFILE` | Required installed
|
|
55
|
+
| `PO_NATIVE_IOS_PROFILE` | Required installed profile for `ai.po.app` |
|
|
56
|
+
| `PO_NATIVE_IOS_WIDGET_PROFILE` | Required installed profile for `ai.po.app.ExpoWidgetsTarget` |
|
|
56
57
|
| `PO_NATIVE_IOS_CODE_SIGN_IDENTITY` | Optional signing certificate name; TestFlight defaults to `Apple Distribution` |
|
|
57
58
|
| `PO_NATIVE_ANDROID_KEYSTORE` | Required Android keystore path |
|
|
58
59
|
| `PO_NATIVE_ANDROID_KEYSTORE_PASSWORD` | Required keystore password |
|
|
@@ -60,15 +61,16 @@ The build script validates required inputs before replacing earlier final artifa
|
|
|
60
61
|
| `PO_NATIVE_ANDROID_KEY_PASSWORD` | Required key password |
|
|
61
62
|
| `JAVA_HOME` | JDK 17; macOS scripts can resolve it through `java_home` |
|
|
62
63
|
|
|
63
|
-
iOS archives and exports with manual signing (`release-testing` for ad hoc). Android runs `assembleRelease`. Secrets come from the environment or keychain, not generated project files. Outputs are `.build/adhoc/po-native.ipa` or `po-native.apk`, with `SHA256SUMS`. Private per-step logs are under `.build/adhoc/logs/`; work files are under `.build/adhoc/work/`. A failed build preserves the previous final artifact.
|
|
64
|
+
iOS archives and exports with manual signing (`release-testing` for ad hoc). Both iOS profiles must include the `group.ai.po.app` App Group. Android runs `assembleRelease`. Secrets come from the environment or keychain, not generated project files. Outputs are `.build/adhoc/po-native.ipa` or `po-native.apk`, with `SHA256SUMS`. Private per-step logs are under `.build/adhoc/logs/`; work files are under `.build/adhoc/work/`. A failed build preserves the previous final artifact.
|
|
64
65
|
|
|
65
66
|
### TestFlight export
|
|
66
67
|
|
|
67
|
-
Install
|
|
68
|
+
Install App Store Connect distribution profiles for `ai.po.app` and `ai.po.app.ExpoWidgetsTarget`, with the `group.ai.po.app` App Group on both and Push Notifications on `ai.po.app`. Install the matching Apple Distribution certificate/private key. Run `ios:setup`, then set:
|
|
68
69
|
|
|
69
70
|
```sh
|
|
70
71
|
export APPLE_TEAM_ID="YOUR_TEAM_ID"
|
|
71
72
|
export PO_NATIVE_IOS_PROFILE="YOUR_APP_STORE_CONNECT_PROFILE"
|
|
73
|
+
export PO_NATIVE_IOS_WIDGET_PROFILE="YOUR_WIDGET_APP_STORE_CONNECT_PROFILE"
|
|
72
74
|
export PO_NATIVE_IOS_CODE_SIGN_IDENTITY="Apple Distribution"
|
|
73
75
|
export PO_NATIVE_IOS_BUILD_NUMBER="42"
|
|
74
76
|
export PO_NATIVE_IDENTITY_ISSUER="https://your-identity-home.example"
|
|
@@ -77,7 +79,7 @@ pnpm nx run @agimon-ai/po-native:ios:testflight
|
|
|
77
79
|
|
|
78
80
|
Choose the actual HTTPS identity-home origin, not the example. Production builds require it. The command supplies production APNs and rejects an explicitly configured sandbox environment. Build numbers must increase for submissions and satisfy `CFBundleVersion` (for example `42` or `1.2.3`; first component 1–9999, others 0–99). The marketing version comes from `app.config.ts`.
|
|
79
81
|
|
|
80
|
-
Before export the script checks the archive's bundle ID, build number
|
|
82
|
+
Before export the script checks the archive's bundle ID, build number and signed production APNs entitlement. It also verifies the embedded extension's signature and bundle ID and the App Group entitlement on both targets. It uses `app-store-connect` export with manual signing. It does not create credentials, alter the Apple portal, upload, or submit. Output is `.build/testflight/po-native.ipa` with `SHA256SUMS`; archive/dSYMs and private logs remain under that directory's `work/` and `logs/` trees. Existing ad hoc outputs stay separate.
|
|
81
83
|
|
|
82
84
|
## Push and remaining acceptance
|
|
83
85
|
|
package/app.config.ts
CHANGED
|
@@ -37,6 +37,8 @@ const config: ExpoConfig = {
|
|
|
37
37
|
bundleIdentifier: 'ai.po.app',
|
|
38
38
|
usesAppleSignIn: true,
|
|
39
39
|
infoPlist: { NSLocalNetworkUsageDescription: 'Connect to your paired Po computer on your local network.' },
|
|
40
|
+
// Pinned here: expo-widgets otherwise writes 'development' first and expo-notifications keeps it.
|
|
41
|
+
entitlements: { 'aps-environment': apnsEnvironment },
|
|
40
42
|
// Export compliance answer on App Store Connect: no non-exempt encryption.
|
|
41
43
|
config: { usesNonExemptEncryption: false },
|
|
42
44
|
...(iosBuildNumber ? { buildNumber: iosBuildNumber } : {}),
|
|
@@ -78,7 +80,16 @@ const config: ExpoConfig = {
|
|
|
78
80
|
},
|
|
79
81
|
],
|
|
80
82
|
'@config-plugins/react-native-webrtc',
|
|
83
|
+
// Xcode mods run in reverse registration order. Generate the extension before signing it.
|
|
81
84
|
'@agimon-ai/po-expo-signing',
|
|
85
|
+
[
|
|
86
|
+
'expo-widgets',
|
|
87
|
+
{
|
|
88
|
+
bundleIdentifier: 'ai.po.app.ExpoWidgetsTarget',
|
|
89
|
+
groupIdentifier: 'group.ai.po.app',
|
|
90
|
+
enablePushNotifications: true,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
82
93
|
],
|
|
83
94
|
};
|
|
84
95
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-native",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.79",
|
|
4
4
|
"description": "Po for iOS and Android",
|
|
5
5
|
"homepage": "https://agimon.ai",
|
|
6
6
|
"bugs": {
|
|
@@ -29,20 +29,21 @@
|
|
|
29
29
|
"access": "public"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
33
|
-
"@agimon-ai/po-expo-signing": "0.0.1-alpha.
|
|
34
|
-
"@agimon-ai/po-identity": "0.0.2-alpha.
|
|
35
|
-
"@agimon-ai/po-native-components": "0.0.0-alpha.
|
|
36
|
-
"@agimon-ai/po-native-dashboard": "0.0.0-alpha.
|
|
37
|
-
"@agimon-ai/po-template-advanced": "0.0.0-alpha.
|
|
38
|
-
"@agimon-ai/po-template-elegant": "0.0.0-alpha.
|
|
39
|
-
"@agimon-ai/po-voice": "0.0.0-alpha.
|
|
40
|
-
"@agimon-ai/po-web-components": "0.0.0-alpha.
|
|
41
|
-
"@agimon-ai/po-web-dashboard": "0.0.0-alpha.
|
|
42
|
-
"@agimon-ai/po-web-security": "0.0.0-alpha.
|
|
32
|
+
"@agimon-ai/po-core": "0.0.0-alpha.199",
|
|
33
|
+
"@agimon-ai/po-expo-signing": "0.0.1-alpha.79",
|
|
34
|
+
"@agimon-ai/po-identity": "0.0.2-alpha.146",
|
|
35
|
+
"@agimon-ai/po-native-components": "0.0.0-alpha.199",
|
|
36
|
+
"@agimon-ai/po-native-dashboard": "0.0.0-alpha.71",
|
|
37
|
+
"@agimon-ai/po-template-advanced": "0.0.0-alpha.199",
|
|
38
|
+
"@agimon-ai/po-template-elegant": "0.0.0-alpha.199",
|
|
39
|
+
"@agimon-ai/po-voice": "0.0.0-alpha.199",
|
|
40
|
+
"@agimon-ai/po-web-components": "0.0.0-alpha.199",
|
|
41
|
+
"@agimon-ai/po-web-dashboard": "0.0.0-alpha.199",
|
|
42
|
+
"@agimon-ai/po-web-security": "0.0.0-alpha.199",
|
|
43
43
|
"@better-auth/expo": "1.7.12",
|
|
44
44
|
"@config-plugins/react-native-webrtc": "15.0.2",
|
|
45
45
|
"@earendil-works/chord": "1.6.1",
|
|
46
|
+
"@expo/ui": "58.0.26",
|
|
46
47
|
"@expo/vector-icons": "15.1.1",
|
|
47
48
|
"@gorhom/bottom-sheet": "5.2.14",
|
|
48
49
|
"@native-html/render": "1.0.4",
|
|
@@ -77,6 +78,7 @@
|
|
|
77
78
|
"expo-symbols": "~58.0.4",
|
|
78
79
|
"expo-video": "~58.0.13",
|
|
79
80
|
"expo-web-browser": "~58.0.7",
|
|
81
|
+
"expo-widgets": "58.0.26",
|
|
80
82
|
"react": "19.3.0",
|
|
81
83
|
"react-native": "0.88.1",
|
|
82
84
|
"react-native-audio-api": "0.13.6",
|
package/src/app/App.tsx
CHANGED
|
@@ -262,6 +262,7 @@ import {
|
|
|
262
262
|
uploadSessionAttachment,
|
|
263
263
|
} from '../services/hostActions';
|
|
264
264
|
import { calendarSnapshots } from '../services/hostSnapshots';
|
|
265
|
+
import { useSessionActivity } from '../services/liveActivity';
|
|
265
266
|
import { recordNativeLog } from '../services/logExport';
|
|
266
267
|
import { loadNativeAuthorDraft, saveNativeAuthorDraft } from '../services/nativeAuthorDrafts';
|
|
267
268
|
import { startNativePushRouting } from '../services/nativePush';
|
|
@@ -269,6 +270,7 @@ import { NativeRealtimeHost } from '../services/nativeRealtime';
|
|
|
269
270
|
import { createNativeAudioSession } from '../services/nativeVoice';
|
|
270
271
|
import { clearCached, useCachedRequest } from '../services/requestCache';
|
|
271
272
|
import { whenConnected } from '../services/sessionRuntime';
|
|
273
|
+
import { sessionActivityTarget, type SessionTapTarget } from '../services/sessionTap';
|
|
272
274
|
import {
|
|
273
275
|
listMcpServers,
|
|
274
276
|
listProviders,
|
|
@@ -3535,6 +3537,8 @@ export function App({ nativeHost }: { nativeHost?: (sessionId: string) => Native
|
|
|
3535
3537
|
const [hydrated, setHydrated] = useState(false);
|
|
3536
3538
|
const [trustLoaded, setTrustLoaded] = useState(false);
|
|
3537
3539
|
const [navigationReady, setNavigationReady] = useState(false);
|
|
3540
|
+
const [activitySessionId, setActivitySessionId] = useState<string | null>(null);
|
|
3541
|
+
const sessionActivity = useSessionActivity(activitySessionId, hostStates, trustLoaded);
|
|
3538
3542
|
// The tree mounts once the last installed templates and plugins are back from disk, so it does not
|
|
3539
3543
|
// draw the phone's default and then swap; a slow disk waits no longer than BOOT_HOLD_MS.
|
|
3540
3544
|
const [booted, setBooted] = useState(false);
|
|
@@ -3599,6 +3603,7 @@ export function App({ nativeHost }: { nativeHost?: (sessionId: string) => Native
|
|
|
3599
3603
|
if (loaded) setPhase(states.length === 1 && !states[0].runtime ? 'pairing' : states.length ? 'ready' : 'pairing');
|
|
3600
3604
|
};
|
|
3601
3605
|
const manager = createHostRuntimes({
|
|
3606
|
+
beforeForget: sessionActivity.stopHost,
|
|
3602
3607
|
changed: reportStates,
|
|
3603
3608
|
activity: (hostId, owner, state) => {
|
|
3604
3609
|
if (mounted) setActivityLoad(hostId, owner, state);
|
|
@@ -3684,20 +3689,36 @@ export function App({ nativeHost }: { nativeHost?: (sessionId: string) => Native
|
|
|
3684
3689
|
|
|
3685
3690
|
useEffect(() => {
|
|
3686
3691
|
if (!trustLoaded || !navigationReady) return;
|
|
3687
|
-
const
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
|
|
3691
|
-
|
|
3692
|
-
|
|
3693
|
-
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3692
|
+
const hasHost = (hostRef: string) => hosts.current?.snapshot().some(({ host }) => host.id === hostRef) ?? false;
|
|
3693
|
+
const openSession = ({ hostRef, sessionId: localId }: SessionTapTarget) => {
|
|
3694
|
+
const sessionId = qualifyHostId(hostRef, localId);
|
|
3695
|
+
navigation.navigate('Session', {
|
|
3696
|
+
sessionId,
|
|
3697
|
+
title: sessionsStore.state.byId[sessionId]?.summary.name || t('native.app.session', 'Session'),
|
|
3698
|
+
});
|
|
3699
|
+
};
|
|
3700
|
+
const routing = startNativePushRouting({ hasHost, openSession });
|
|
3701
|
+
let stopped = false;
|
|
3702
|
+
const openLink = (url: string | null | undefined) => {
|
|
3703
|
+
if (stopped || !url) return;
|
|
3704
|
+
const target = sessionActivityTarget(url, hasHost);
|
|
3705
|
+
if (target) openSession(target);
|
|
3706
|
+
};
|
|
3707
|
+
const links = Linking.addEventListener('url', ({ url }) => openLink(url));
|
|
3708
|
+
void Linking.getInitialURL()
|
|
3709
|
+
.then(openLink)
|
|
3710
|
+
.catch(() => console.warn('Live Activity tap unavailable.'));
|
|
3711
|
+
return () => {
|
|
3712
|
+
stopped = true;
|
|
3713
|
+
routing.stop();
|
|
3714
|
+
links.remove();
|
|
3715
|
+
};
|
|
3698
3716
|
}, [trustLoaded, navigationReady, navigation]);
|
|
3699
3717
|
|
|
3700
|
-
const focusSession = useCallback((sessionId: string | null) =>
|
|
3718
|
+
const focusSession = useCallback((sessionId: string | null) => {
|
|
3719
|
+
hosts.current?.open(sessionId);
|
|
3720
|
+
setActivitySessionId(sessionId);
|
|
3721
|
+
}, []);
|
|
3701
3722
|
const connectCloud = useCallback(async (host: CloudHostRecord) => {
|
|
3702
3723
|
const manager = hosts.current;
|
|
3703
3724
|
if (!manager) throw new Error(t('native.app.starting', 'Po is still starting. Try again in a moment.'));
|
package/src/app/hostRuntimes.ts
CHANGED
|
@@ -104,6 +104,7 @@ function sameHostState(left: HostRuntimeState, right: HostRuntimeState): boolean
|
|
|
104
104
|
/** Each host owns its lifetime. A failed reconnect never closes a sibling host. */
|
|
105
105
|
export function createHostRuntimes(
|
|
106
106
|
options: {
|
|
107
|
+
beforeForget?: (hostId: string) => Promise<void>;
|
|
107
108
|
changed?: (states: readonly HostRuntimeState[]) => void;
|
|
108
109
|
activity?: (hostId: string, owner: string, state: ActivityLoadState) => void;
|
|
109
110
|
onBundleUpdate?: (host: HostRecord | CloudHostRecord, choice: NativeBundleUpdateChoice) => void;
|
|
@@ -724,6 +725,11 @@ export function createHostRuntimes(
|
|
|
724
725
|
try {
|
|
725
726
|
// Stop token renewal first, so a late token cannot enroll this phone with the computer again.
|
|
726
727
|
entries.get(hostId)?.push?.stop();
|
|
728
|
+
if (options.beforeForget)
|
|
729
|
+
await withinDeadline(
|
|
730
|
+
options.beforeForget(hostId),
|
|
731
|
+
'Live Activity removal deferred; its registration expires automatically.',
|
|
732
|
+
);
|
|
727
733
|
const session = currentSession(hostId);
|
|
728
734
|
if (session)
|
|
729
735
|
await withinDeadline(
|
|
@@ -42,7 +42,7 @@ export function WakePeriodView({
|
|
|
42
42
|
<Text style={sessionChoicesStyles.meta}>
|
|
43
43
|
{t(
|
|
44
44
|
'native.wake.explainer',
|
|
45
|
-
'How far ahead
|
|
45
|
+
'How long Po waits between check-ins and how far ahead it looks for scheduled work. Upcoming work can skip a check-in without changing when events run.',
|
|
46
46
|
)}
|
|
47
47
|
</Text>
|
|
48
48
|
<Label>{t('native.wake.period', 'Period (minutes)')}</Label>
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { AgentAvatar, fontOf } from '@agimon-ai/po-native-components';
|
|
2
|
+
import { Image, Text, View } from 'react-native';
|
|
3
|
+
import { StyleSheet } from 'react-native-unistyles';
|
|
4
|
+
|
|
5
|
+
import profileAvatar from '../../../assets/po-avatars/dev.png';
|
|
6
|
+
import { type DesignScheme, PhoneFrame } from '../../screens/designFrame';
|
|
7
|
+
|
|
8
|
+
// The browser story shows the target layout, not the system's WidgetKit chrome.
|
|
9
|
+
export const meta = { title: 'Native/Design/Session Live Activity', tags: ['style-system', 'mockup', 'native'] };
|
|
10
|
+
export default meta;
|
|
11
|
+
|
|
12
|
+
const sessionName = 'Review component stories';
|
|
13
|
+
const states = [
|
|
14
|
+
{ label: 'Working', tone: 'work', photo: true },
|
|
15
|
+
{ label: 'Question waiting', tone: 'ask', photo: true },
|
|
16
|
+
{ label: 'Approval needed', tone: 'ask', photo: true },
|
|
17
|
+
{ label: 'Finished', tone: 'quiet', photo: true },
|
|
18
|
+
{ label: 'Status unavailable', tone: 'quiet', photo: false },
|
|
19
|
+
{ label: 'Status may be out of date', tone: 'quiet', photo: true },
|
|
20
|
+
] as const;
|
|
21
|
+
|
|
22
|
+
type Status = (typeof states)[number];
|
|
23
|
+
|
|
24
|
+
function Face({ photo, small = false }: { photo: boolean; small?: boolean }) {
|
|
25
|
+
return photo ? (
|
|
26
|
+
<Image source={profileAvatar} style={styles.avatar(small)} accessible accessibilityLabel="Developer profile" />
|
|
27
|
+
) : (
|
|
28
|
+
<AgentAvatar name="Developer" size={small ? 'sm' : 'md'} />
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function StateLine({ status }: { status: Status }) {
|
|
33
|
+
return (
|
|
34
|
+
<View style={styles.stateLine}>
|
|
35
|
+
<View style={styles.dot(status.tone)} />
|
|
36
|
+
<Text style={styles.secondary}>{status.label}</Text>
|
|
37
|
+
</View>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function ActivityTarget({ scheme }: { scheme: DesignScheme }) {
|
|
42
|
+
return (
|
|
43
|
+
<PhoneFrame scheme={scheme}>
|
|
44
|
+
<View style={styles.canvas}>
|
|
45
|
+
<Text style={styles.heading}>Lock Screen</Text>
|
|
46
|
+
{states.map((status) => (
|
|
47
|
+
<View key={status.label} style={styles.banner}>
|
|
48
|
+
<Face photo={status.photo} />
|
|
49
|
+
<View style={styles.summary}>
|
|
50
|
+
<Text style={styles.name} numberOfLines={1}>
|
|
51
|
+
{sessionName}
|
|
52
|
+
</Text>
|
|
53
|
+
<StateLine status={status} />
|
|
54
|
+
</View>
|
|
55
|
+
</View>
|
|
56
|
+
))}
|
|
57
|
+
<Text style={styles.heading}>Dynamic Island</Text>
|
|
58
|
+
<View style={styles.islandRow}>
|
|
59
|
+
<View style={styles.island}>
|
|
60
|
+
<Face photo small />
|
|
61
|
+
</View>
|
|
62
|
+
<View style={styles.island}>
|
|
63
|
+
<Face photo small />
|
|
64
|
+
<View style={styles.dot(states[0].tone)} accessible accessibilityLabel={states[0].label} />
|
|
65
|
+
</View>
|
|
66
|
+
</View>
|
|
67
|
+
<View style={styles.expanded}>
|
|
68
|
+
<Face photo />
|
|
69
|
+
<View style={styles.summary}>
|
|
70
|
+
<Text style={styles.name} numberOfLines={1}>
|
|
71
|
+
{sessionName}
|
|
72
|
+
</Text>
|
|
73
|
+
<StateLine status={states[2]} />
|
|
74
|
+
</View>
|
|
75
|
+
<Text style={styles.secondary} accessibilityLabel="1 approval waiting">
|
|
76
|
+
1
|
|
77
|
+
</Text>
|
|
78
|
+
</View>
|
|
79
|
+
</View>
|
|
80
|
+
</PhoneFrame>
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const Playground = { render: () => <ActivityTarget scheme="dark" /> };
|
|
85
|
+
export const Light = { render: () => <ActivityTarget scheme="light" /> };
|
|
86
|
+
|
|
87
|
+
const styles = StyleSheet.create((theme) => ({
|
|
88
|
+
canvas: { flex: 1, backgroundColor: theme.colors.bg, padding: theme.spacing(5), gap: theme.spacing(2) },
|
|
89
|
+
heading: {
|
|
90
|
+
color: theme.colors.hi,
|
|
91
|
+
fontFamily: fontOf(theme.fontFamily.sans),
|
|
92
|
+
fontSize: theme.fontSize.lg,
|
|
93
|
+
fontWeight: theme.fontWeight.semibold,
|
|
94
|
+
marginVertical: theme.spacing(2),
|
|
95
|
+
},
|
|
96
|
+
banner: {
|
|
97
|
+
flexDirection: 'row',
|
|
98
|
+
alignItems: 'center',
|
|
99
|
+
gap: theme.spacing(3),
|
|
100
|
+
padding: theme.spacing(3),
|
|
101
|
+
borderRadius: theme.borderRadius.lg,
|
|
102
|
+
backgroundColor: theme.colors.panel,
|
|
103
|
+
},
|
|
104
|
+
summary: { flex: 1, minWidth: 0, gap: theme.spacing(1) },
|
|
105
|
+
name: {
|
|
106
|
+
color: theme.colors.hi,
|
|
107
|
+
fontFamily: fontOf(theme.fontFamily.sans),
|
|
108
|
+
fontSize: theme.fontSize.base,
|
|
109
|
+
lineHeight: theme.lineHeight.base,
|
|
110
|
+
fontWeight: theme.fontWeight.semibold,
|
|
111
|
+
},
|
|
112
|
+
secondary: {
|
|
113
|
+
color: theme.colors.dim,
|
|
114
|
+
fontFamily: fontOf(theme.fontFamily.sans),
|
|
115
|
+
fontSize: theme.fontSize.sm,
|
|
116
|
+
lineHeight: theme.lineHeight.sm,
|
|
117
|
+
},
|
|
118
|
+
avatar: (small: boolean) => ({
|
|
119
|
+
width: theme.spacing(small ? 6 : 8),
|
|
120
|
+
height: theme.spacing(small ? 6 : 8),
|
|
121
|
+
borderRadius: theme.borderRadius.full,
|
|
122
|
+
}),
|
|
123
|
+
stateLine: { flexDirection: 'row', alignItems: 'center', gap: theme.spacing(2) },
|
|
124
|
+
dot: (tone: Status['tone']) => ({
|
|
125
|
+
width: theme.spacing(2),
|
|
126
|
+
height: theme.spacing(2),
|
|
127
|
+
borderRadius: theme.borderRadius.full,
|
|
128
|
+
backgroundColor: tone === 'work' ? theme.colors.green : tone === 'ask' ? theme.colors.magenta : theme.colors.dim,
|
|
129
|
+
}),
|
|
130
|
+
islandRow: { flexDirection: 'row', gap: theme.spacing(3) },
|
|
131
|
+
island: {
|
|
132
|
+
flexDirection: 'row',
|
|
133
|
+
alignItems: 'center',
|
|
134
|
+
gap: theme.spacing(3),
|
|
135
|
+
minHeight: theme.spacing(11),
|
|
136
|
+
paddingHorizontal: theme.spacing(3),
|
|
137
|
+
borderRadius: theme.borderRadius.full,
|
|
138
|
+
backgroundColor: theme.colors.panel,
|
|
139
|
+
},
|
|
140
|
+
expanded: {
|
|
141
|
+
flexDirection: 'row',
|
|
142
|
+
alignItems: 'center',
|
|
143
|
+
gap: theme.spacing(3),
|
|
144
|
+
minHeight: theme.spacing(16),
|
|
145
|
+
padding: theme.spacing(4),
|
|
146
|
+
borderRadius: theme.borderRadius.lg,
|
|
147
|
+
backgroundColor: theme.colors.panel,
|
|
148
|
+
},
|
|
149
|
+
}));
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { HStack, VStack, Text, Image, Circle, Spacer } from '@expo/ui/swift-ui';
|
|
2
|
+
import {
|
|
3
|
+
accessibilityLabel,
|
|
4
|
+
background,
|
|
5
|
+
clipShape,
|
|
6
|
+
font,
|
|
7
|
+
foregroundStyle,
|
|
8
|
+
frame,
|
|
9
|
+
lineLimit,
|
|
10
|
+
padding,
|
|
11
|
+
resizable,
|
|
12
|
+
} from '@expo/ui/swift-ui/modifiers';
|
|
13
|
+
import { createLiveActivity, type LiveActivityEnvironment } from 'expo-widgets';
|
|
14
|
+
|
|
15
|
+
import type { SessionActivityProps } from './lifecycle';
|
|
16
|
+
|
|
17
|
+
export const sessionActivity = createLiveActivity(
|
|
18
|
+
'SessionActivity',
|
|
19
|
+
(props: SessionActivityProps, environment: LiveActivityEnvironment) => {
|
|
20
|
+
'widget';
|
|
21
|
+
const theme = props.themes[environment.colorScheme];
|
|
22
|
+
// The Dynamic Island is always black, whatever the system appearance.
|
|
23
|
+
const island = props.themes.dark;
|
|
24
|
+
const unit = props.spacing;
|
|
25
|
+
const status = environment.isStale && props.status !== 'finished' ? 'stale' : props.status;
|
|
26
|
+
const ink = (t: typeof theme) =>
|
|
27
|
+
status === 'working' ? t.green : status === 'question' || status === 'approval' ? t.magenta : t.dim;
|
|
28
|
+
const face = (small: boolean, t: typeof theme) =>
|
|
29
|
+
props.avatar ? (
|
|
30
|
+
<Image
|
|
31
|
+
uiImage={props.avatar}
|
|
32
|
+
modifiers={[
|
|
33
|
+
resizable(),
|
|
34
|
+
frame({ width: unit * (small ? 6 : 8), height: unit * (small ? 6 : 8) }),
|
|
35
|
+
clipShape('circle'),
|
|
36
|
+
]}
|
|
37
|
+
/>
|
|
38
|
+
) : (
|
|
39
|
+
<Text
|
|
40
|
+
modifiers={[
|
|
41
|
+
font({ textStyle: 'caption' }),
|
|
42
|
+
foregroundStyle(t.hi),
|
|
43
|
+
frame({ width: unit * (small ? 6 : 8), height: unit * (small ? 6 : 8) }),
|
|
44
|
+
background(t.tint),
|
|
45
|
+
clipShape('circle'),
|
|
46
|
+
]}
|
|
47
|
+
>
|
|
48
|
+
{props.initials}
|
|
49
|
+
</Text>
|
|
50
|
+
);
|
|
51
|
+
const dot = (t: typeof theme) => (
|
|
52
|
+
<Circle modifiers={[frame({ width: unit * 2, height: unit * 2 }), foregroundStyle(ink(t))]} />
|
|
53
|
+
);
|
|
54
|
+
const stateLine = (t: typeof theme) => (
|
|
55
|
+
<HStack spacing={unit * 2}>
|
|
56
|
+
{dot(t)}
|
|
57
|
+
<Text modifiers={[font({ textStyle: 'caption' }), foregroundStyle(t.dim)]}>{props.labels[status]}</Text>
|
|
58
|
+
</HStack>
|
|
59
|
+
);
|
|
60
|
+
const name = (t: typeof theme) => (
|
|
61
|
+
<Text
|
|
62
|
+
modifiers={[
|
|
63
|
+
// System font: the widget extension does not bundle the app's fonts, and a missing custom family drops the weight.
|
|
64
|
+
font({ weight: 'semibold', textStyle: 'footnote' }),
|
|
65
|
+
foregroundStyle(t.hi),
|
|
66
|
+
lineLimit(1),
|
|
67
|
+
]}
|
|
68
|
+
>
|
|
69
|
+
{props.name}
|
|
70
|
+
</Text>
|
|
71
|
+
);
|
|
72
|
+
return {
|
|
73
|
+
banner: (
|
|
74
|
+
<HStack spacing={unit * 3} modifiers={[padding({ all: unit * 3 }), background(theme.panel)]}>
|
|
75
|
+
{face(false, theme)}
|
|
76
|
+
<VStack alignment="leading" spacing={unit}>
|
|
77
|
+
{name(theme)}
|
|
78
|
+
{stateLine(theme)}
|
|
79
|
+
</VStack>
|
|
80
|
+
<Spacer />
|
|
81
|
+
</HStack>
|
|
82
|
+
),
|
|
83
|
+
minimal: face(true, island),
|
|
84
|
+
compactLeading: face(true, island),
|
|
85
|
+
// Labels like "Question waiting" do not fit beside the camera; the dot carries the state, VoiceOver the words.
|
|
86
|
+
compactTrailing: <HStack modifiers={[accessibilityLabel(props.labels[status])]}>{dot(island)}</HStack>,
|
|
87
|
+
expandedLeading: face(false, island),
|
|
88
|
+
expandedCenter: (
|
|
89
|
+
<VStack alignment="leading" spacing={unit} modifiers={[frame({ maxWidth: Infinity, alignment: 'leading' })]}>
|
|
90
|
+
{name(island)}
|
|
91
|
+
{stateLine(island)}
|
|
92
|
+
</VStack>
|
|
93
|
+
),
|
|
94
|
+
expandedTrailing:
|
|
95
|
+
props.approvalCount > 0 ? (
|
|
96
|
+
<Text
|
|
97
|
+
modifiers={[
|
|
98
|
+
font({ textStyle: 'caption' }),
|
|
99
|
+
foregroundStyle(island.dim),
|
|
100
|
+
accessibilityLabel(props.approvalLabel),
|
|
101
|
+
]}
|
|
102
|
+
>
|
|
103
|
+
{props.approvalCount}
|
|
104
|
+
</Text>
|
|
105
|
+
) : null,
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
);
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { t } from '@agimon-ai/po-core/native';
|
|
2
|
+
import { LIVE_ACTIVITY_ROUTE } from '@agimon-ai/po-core/remoteContract';
|
|
3
|
+
import { agentInitials, tintFor } from '@agimon-ai/po-native-components';
|
|
4
|
+
import { NATIVE_THEMES } from '@agimon-ai/po-web-components/nativeTheme';
|
|
5
|
+
import { sessionsStore, splitHostId } from '@agimon-ai/po-web-dashboard/core';
|
|
6
|
+
import { useStore } from '@tanstack/react-store';
|
|
7
|
+
import {
|
|
8
|
+
ApplicationReleaseType,
|
|
9
|
+
getIosApplicationReleaseTypeAsync,
|
|
10
|
+
getIosPushNotificationServiceEnvironmentAsync,
|
|
11
|
+
} from 'expo-application';
|
|
12
|
+
import { Directory, File } from 'expo-file-system';
|
|
13
|
+
import { widgetsDirectory } from 'expo-widgets';
|
|
14
|
+
import { useEffect, useMemo, useRef, useState } from 'react';
|
|
15
|
+
import { AppState } from 'react-native';
|
|
16
|
+
|
|
17
|
+
import type { HostRuntimeState } from '../../app/hostRuntimes';
|
|
18
|
+
import { useSessionAvatars } from '../../app/sessionAvatars';
|
|
19
|
+
import { isCloudHost } from '../cloudHosts';
|
|
20
|
+
import { currentSession, type TrustedSession } from '../deviceTrust';
|
|
21
|
+
import { sessionActivityURL } from '../sessionTap';
|
|
22
|
+
import { activityStatus, createSessionActivityOwner, type SessionActivityProps } from './lifecycle';
|
|
23
|
+
import { sessionActivity } from './SessionActivity.ios';
|
|
24
|
+
|
|
25
|
+
/** The extension receives only a small serializable snapshot, never app state or transcript data. */
|
|
26
|
+
export function useSessionActivity(sessionId: string | null, hosts: readonly HostRuntimeState[], ready: boolean) {
|
|
27
|
+
const owner = useRef<ReturnType<typeof createSessionActivityOwner> | undefined>(undefined);
|
|
28
|
+
const blockedHosts = useRef(new Set<string>());
|
|
29
|
+
const knownHosts = useRef(hosts);
|
|
30
|
+
knownHosts.current = hosts;
|
|
31
|
+
const pushSessions = useRef(new Map<string, TrustedSession>());
|
|
32
|
+
const files = useRef(new Map<string, { data: string; file: File; hostId: string }>());
|
|
33
|
+
const chain = useRef(Promise.resolve());
|
|
34
|
+
const preparedAssets = useRef(false);
|
|
35
|
+
const byId = useStore(sessionsStore, (state) => state.byId);
|
|
36
|
+
const avatars = useSessionAvatars(sessionId ? [sessionId] : [], byId);
|
|
37
|
+
const avatar = sessionId ? avatars[sessionId] : undefined;
|
|
38
|
+
const [tick, setTick] = useState(0);
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
// Refresh the system stale date only while this process is actually active.
|
|
41
|
+
const timer = setInterval(() => {
|
|
42
|
+
if (AppState.currentState === 'active') setTick((value) => value + 1);
|
|
43
|
+
}, 60_000);
|
|
44
|
+
const listener = AppState.addEventListener('change', (state) => {
|
|
45
|
+
if (state === 'active') setTick((value) => value + 1);
|
|
46
|
+
});
|
|
47
|
+
return () => {
|
|
48
|
+
clearInterval(timer);
|
|
49
|
+
listener.remove();
|
|
50
|
+
};
|
|
51
|
+
}, []);
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
if (!ready) return;
|
|
54
|
+
for (const id of blockedHosts.current)
|
|
55
|
+
if (!hosts.some((item) => item.host.id === id)) blockedHosts.current.delete(id);
|
|
56
|
+
const hostId = sessionId ? splitHostId(sessionId)?.hostId : undefined;
|
|
57
|
+
const host = hosts.find((item) => item.host.id === hostId);
|
|
58
|
+
const entry = sessionId ? byId[sessionId] : undefined;
|
|
59
|
+
const summary = entry?.summary;
|
|
60
|
+
const status = activityStatus(summary, host?.status === 'connected', entry?.attach === 'attached');
|
|
61
|
+
const theme = NATIVE_THEMES.dark;
|
|
62
|
+
// The same name and rules as the session's AgentAvatar in the app, so the faces match.
|
|
63
|
+
const persona = summary?.profile?.displayName ?? summary?.profile?.name ?? summary?.name ?? '';
|
|
64
|
+
const colors = (scheme: 'light' | 'dark') => {
|
|
65
|
+
const { hi, dim, panel, green, magenta } = NATIVE_THEMES[scheme].colors;
|
|
66
|
+
return { hi, dim, panel, green, magenta, tint: NATIVE_THEMES[scheme].colors[`tint-${tintFor(persona)}`] };
|
|
67
|
+
};
|
|
68
|
+
const props: SessionActivityProps | undefined = summary
|
|
69
|
+
? {
|
|
70
|
+
name: summary.name || t('native.app.session', 'Session'),
|
|
71
|
+
initials: agentInitials(persona),
|
|
72
|
+
status,
|
|
73
|
+
approvalCount: summary.pendingApprovalCount ?? 0,
|
|
74
|
+
labels: {
|
|
75
|
+
working: t('native.liveActivity.working', 'Working'),
|
|
76
|
+
question: t('native.liveActivity.question', 'Question waiting'),
|
|
77
|
+
approval: t('native.liveActivity.approval', 'Approval needed'),
|
|
78
|
+
finished: t('native.liveActivity.finished', 'Finished'),
|
|
79
|
+
stale: t('native.liveActivity.stale', 'Status may be out of date'),
|
|
80
|
+
unavailable: t('native.liveActivity.unavailable', 'Status unavailable'),
|
|
81
|
+
},
|
|
82
|
+
approvalLabel: t('native.liveActivity.approvals', '{count} approvals waiting', {
|
|
83
|
+
count: String(summary.pendingApprovalCount ?? 0),
|
|
84
|
+
}),
|
|
85
|
+
themes: { light: colors('light'), dark: colors('dark') },
|
|
86
|
+
spacing: theme.spacing(1),
|
|
87
|
+
}
|
|
88
|
+
: undefined;
|
|
89
|
+
chain.current = chain.current
|
|
90
|
+
.then(async () => {
|
|
91
|
+
owner.current ??= createSessionActivityOwner(sessionActivity, Date.now, {
|
|
92
|
+
presentation: (value) => {
|
|
93
|
+
const { initials, avatar, labels, themes, spacing } = value;
|
|
94
|
+
return {
|
|
95
|
+
initials,
|
|
96
|
+
...(avatar ? { avatar } : {}),
|
|
97
|
+
labels,
|
|
98
|
+
themes,
|
|
99
|
+
spacing,
|
|
100
|
+
nameFallback: t('native.app.session', 'Session'),
|
|
101
|
+
approvalLabel: t('native.liveActivity.approvals', '{count} approvals waiting', { count: '{count}' }),
|
|
102
|
+
};
|
|
103
|
+
},
|
|
104
|
+
environment: async () => {
|
|
105
|
+
const environment = await getIosPushNotificationServiceEnvironmentAsync();
|
|
106
|
+
if (environment === 'development' || environment === 'production') return environment;
|
|
107
|
+
return (await getIosApplicationReleaseTypeAsync()) === ApplicationReleaseType.APP_STORE
|
|
108
|
+
? 'production'
|
|
109
|
+
: undefined;
|
|
110
|
+
},
|
|
111
|
+
register: async (id, registration) => {
|
|
112
|
+
// Only the QR-paired host's existing sealed queue. Never Cloud-account or unsealed HTTP fallback.
|
|
113
|
+
const paired = knownHosts.current.find((item) => item.host.id === id && !isCloudHost(item.host));
|
|
114
|
+
const session = paired && currentSession(id);
|
|
115
|
+
if (!session || blockedHosts.current.has(id)) throw new Error('Paired activity transport unavailable.');
|
|
116
|
+
pushSessions.current.set(id, session);
|
|
117
|
+
const response = await session.sealed({
|
|
118
|
+
method: 'POST',
|
|
119
|
+
target: LIVE_ACTIVITY_ROUTE,
|
|
120
|
+
headers: [['content-type', 'application/json']],
|
|
121
|
+
body: JSON.stringify(registration),
|
|
122
|
+
});
|
|
123
|
+
if (!response.ok) throw new Error('Activity enrollment refused.');
|
|
124
|
+
},
|
|
125
|
+
unregister: async (id, activityId, token) => {
|
|
126
|
+
const session = pushSessions.current.get(id);
|
|
127
|
+
pushSessions.current.delete(id);
|
|
128
|
+
if (!session) return;
|
|
129
|
+
const response = await session.sealed({
|
|
130
|
+
method: 'DELETE',
|
|
131
|
+
target: LIVE_ACTIVITY_ROUTE,
|
|
132
|
+
headers: [['content-type', 'application/json']],
|
|
133
|
+
body: JSON.stringify({ activityId, token }),
|
|
134
|
+
});
|
|
135
|
+
if (!response.ok) throw new Error('Activity removal refused.');
|
|
136
|
+
},
|
|
137
|
+
onError: () => console.warn('Live Activity enrollment unavailable.'),
|
|
138
|
+
});
|
|
139
|
+
const retired: File[] = [];
|
|
140
|
+
if (!preparedAssets.current) {
|
|
141
|
+
preparedAssets.current = true;
|
|
142
|
+
try {
|
|
143
|
+
// This directory belongs only to the app-driven activity, not other widgets.
|
|
144
|
+
const directory = new Directory(widgetsDirectory, 'po-session-avatars');
|
|
145
|
+
if (directory.exists) directory.delete();
|
|
146
|
+
} catch {
|
|
147
|
+
console.warn('Previous Live Activity avatar cleanup unavailable.');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (props && avatar && sessionId && hostId && host) {
|
|
151
|
+
try {
|
|
152
|
+
const previous = files.current.get(sessionId);
|
|
153
|
+
if (previous?.data === avatar) props.avatar = previous.file.uri;
|
|
154
|
+
else {
|
|
155
|
+
const match = /^data:image\/(png|jpeg|webp);base64,(.+)$/su.exec(avatar);
|
|
156
|
+
if (match) {
|
|
157
|
+
const directory = new Directory(widgetsDirectory, 'po-session-avatars');
|
|
158
|
+
directory.create({ intermediates: true, idempotent: true });
|
|
159
|
+
const file = new File(directory, `${Date.now()}-${files.current.size}.${match[1]}`);
|
|
160
|
+
await file.write(match[2], { encoding: 'base64' });
|
|
161
|
+
if (previous) retired.push(previous.file);
|
|
162
|
+
files.current.set(sessionId, { data: avatar, file, hostId });
|
|
163
|
+
props.avatar = file.uri;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
} catch {
|
|
167
|
+
// An inaccessible shared image falls back to the same profile initials.
|
|
168
|
+
console.warn('Live Activity avatar unavailable.');
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
await owner.current.reconcile({
|
|
172
|
+
sessionId,
|
|
173
|
+
enrollmentSessionId: sessionId ? splitHostId(sessionId)?.localId : undefined,
|
|
174
|
+
hostId,
|
|
175
|
+
hostIds: hosts
|
|
176
|
+
.filter((item) => !isCloudHost(item.host) && !blockedHosts.current.has(item.host.id))
|
|
177
|
+
.map((item) => item.host.id),
|
|
178
|
+
props,
|
|
179
|
+
url:
|
|
180
|
+
sessionId && hostId
|
|
181
|
+
? sessionActivityURL({ hostRef: hostId, sessionId: splitHostId(sessionId)!.localId })
|
|
182
|
+
: undefined,
|
|
183
|
+
});
|
|
184
|
+
for (const file of retired) if (file.exists) file.delete();
|
|
185
|
+
for (const [id, asset] of files.current) {
|
|
186
|
+
if (hosts.some((item) => item.host.id === asset.hostId)) continue;
|
|
187
|
+
if (asset.file.exists) asset.file.delete();
|
|
188
|
+
files.current.delete(id);
|
|
189
|
+
}
|
|
190
|
+
})
|
|
191
|
+
.catch(() => console.warn('Live Activity reconciliation unavailable.'));
|
|
192
|
+
}, [sessionId, hosts, ready, byId, avatar, tick]);
|
|
193
|
+
useEffect(
|
|
194
|
+
() => () => {
|
|
195
|
+
chain.current = chain.current
|
|
196
|
+
.then(async () => {
|
|
197
|
+
await owner.current?.stop();
|
|
198
|
+
for (const { file } of files.current.values()) if (file.exists) file.delete();
|
|
199
|
+
files.current.clear();
|
|
200
|
+
})
|
|
201
|
+
.catch(() => console.warn('Live Activity cleanup unavailable.'));
|
|
202
|
+
},
|
|
203
|
+
[],
|
|
204
|
+
);
|
|
205
|
+
return useMemo(
|
|
206
|
+
() => ({
|
|
207
|
+
async stopHost(hostId: string) {
|
|
208
|
+
// Synchronous block prevents an in-flight token event from re-enrolling before trust keys are removed.
|
|
209
|
+
blockedHosts.current.add(hostId);
|
|
210
|
+
await chain.current;
|
|
211
|
+
await owner.current?.stop(hostId);
|
|
212
|
+
},
|
|
213
|
+
}),
|
|
214
|
+
[],
|
|
215
|
+
);
|
|
216
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { HostRuntimeState } from '../../app/hostRuntimes';
|
|
2
|
+
|
|
3
|
+
/** Android and web never load ActivityKit, Expo Widgets or SwiftUI. */
|
|
4
|
+
export function useSessionActivity(_sessionId: string | null, _hosts: readonly HostRuntimeState[], _ready: boolean) {
|
|
5
|
+
return { stopHost: async (_hostId: string): Promise<void> => {} };
|
|
6
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import {
|
|
2
|
+
LIVE_ACTIVITY_MAX_LIFETIME_MS,
|
|
3
|
+
type LiveActivityPresentation,
|
|
4
|
+
type LiveActivityRegistration,
|
|
5
|
+
} from '@agimon-ai/po-core/remoteContract';
|
|
6
|
+
import type { SessionSummary } from '@agimon-ai/po-web-dashboard/types';
|
|
7
|
+
|
|
8
|
+
export type ActivityStatus = 'working' | 'question' | 'approval' | 'finished' | 'stale' | 'unavailable';
|
|
9
|
+
export interface SessionActivityProps {
|
|
10
|
+
name: string;
|
|
11
|
+
initials: string;
|
|
12
|
+
avatar?: string;
|
|
13
|
+
status: ActivityStatus;
|
|
14
|
+
approvalCount: number;
|
|
15
|
+
labels: Record<ActivityStatus, string>;
|
|
16
|
+
approvalLabel: string;
|
|
17
|
+
themes: LiveActivityPresentation['themes'];
|
|
18
|
+
spacing: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Unknown owned work and a lost attachment are never evidence of completion. */
|
|
22
|
+
export function activityStatus(
|
|
23
|
+
summary: SessionSummary | undefined,
|
|
24
|
+
connected: boolean,
|
|
25
|
+
attached: boolean,
|
|
26
|
+
): ActivityStatus {
|
|
27
|
+
if (!summary) return 'unavailable';
|
|
28
|
+
if (!connected || !attached) return 'stale';
|
|
29
|
+
if (summary.dormant) return 'unavailable';
|
|
30
|
+
if (summary.awaitingInput) return 'question';
|
|
31
|
+
if ((summary.pendingApprovalCount ?? 0) > 0) return 'approval';
|
|
32
|
+
if (summary.phase !== 'idle' || summary.backgroundWorkActive === true || summary.pendingMessageCount > 0)
|
|
33
|
+
return 'working';
|
|
34
|
+
if (summary.backgroundWorkActive !== false || !summary.lastSettledAt) return 'unavailable';
|
|
35
|
+
return 'finished';
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ActivityHandle {
|
|
39
|
+
getPushToken?(): Promise<string | null>;
|
|
40
|
+
addPushTokenListener?(listener: (event: { activityId: string; pushToken: string }) => void): { remove(): void };
|
|
41
|
+
getId(): string;
|
|
42
|
+
update(props: SessionActivityProps, staleDate?: Date): Promise<void>;
|
|
43
|
+
end(policy: 'immediate' | { after: Date }, props?: SessionActivityProps): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
export interface ActivityFactory {
|
|
46
|
+
start(props: SessionActivityProps, url: string, staleDate: Date): ActivityHandle;
|
|
47
|
+
getInstances(): ActivityHandle[];
|
|
48
|
+
}
|
|
49
|
+
export interface ActivitySnapshot {
|
|
50
|
+
sessionId: string | null;
|
|
51
|
+
enrollmentSessionId?: string;
|
|
52
|
+
hostIds: readonly string[];
|
|
53
|
+
hostId?: string;
|
|
54
|
+
url?: string;
|
|
55
|
+
props?: SessionActivityProps;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ActivityPushPorts {
|
|
59
|
+
presentation(props: SessionActivityProps): LiveActivityPresentation;
|
|
60
|
+
environment(): Promise<'development' | 'production' | undefined>;
|
|
61
|
+
register(hostId: string, registration: LiveActivityRegistration): Promise<void>;
|
|
62
|
+
unregister(hostId: string, activityId: string, expectedToken: string): Promise<void>;
|
|
63
|
+
onError(): void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A single handle owns its listener and serialized sealed writes. Late token reads cannot enroll a stopped handle. */
|
|
67
|
+
export function bindActivityPush(
|
|
68
|
+
handle: ActivityHandle,
|
|
69
|
+
hostId: string,
|
|
70
|
+
sessionId: string,
|
|
71
|
+
initial: SessionActivityProps,
|
|
72
|
+
ports: ActivityPushPorts,
|
|
73
|
+
now = Date.now,
|
|
74
|
+
) {
|
|
75
|
+
let stopped = false;
|
|
76
|
+
let props = initial;
|
|
77
|
+
let token: string | undefined;
|
|
78
|
+
let queue = Promise.resolve();
|
|
79
|
+
const startedAt = now();
|
|
80
|
+
const enroll = (next: string) => {
|
|
81
|
+
if (stopped || !/^(?:[a-fA-F0-9]{2})+$/u.test(next) || next.length > 4096) return;
|
|
82
|
+
queue = queue
|
|
83
|
+
.then(async () => {
|
|
84
|
+
if (stopped) return;
|
|
85
|
+
const environment = await ports.environment();
|
|
86
|
+
if (stopped || !environment) return;
|
|
87
|
+
// Only bounded presentation fields go over the wire, never client-derived session state or arbitrary props.
|
|
88
|
+
|
|
89
|
+
token = next.toLowerCase();
|
|
90
|
+
await ports.register(hostId, {
|
|
91
|
+
platform: 'ios',
|
|
92
|
+
activityId: handle.getId(),
|
|
93
|
+
sessionId,
|
|
94
|
+
token,
|
|
95
|
+
environment,
|
|
96
|
+
startedAt,
|
|
97
|
+
expiresAt: startedAt + LIVE_ACTIVITY_MAX_LIFETIME_MS,
|
|
98
|
+
presentation: ports.presentation(props),
|
|
99
|
+
});
|
|
100
|
+
})
|
|
101
|
+
.catch(() => ports.onError());
|
|
102
|
+
};
|
|
103
|
+
let observed = false;
|
|
104
|
+
const listener = handle.addPushTokenListener?.((event) => {
|
|
105
|
+
if (event.activityId !== handle.getId()) return;
|
|
106
|
+
observed = true;
|
|
107
|
+
enroll(event.pushToken);
|
|
108
|
+
});
|
|
109
|
+
// Subscribe before reading: token availability between these two operations is not lost.
|
|
110
|
+
void handle
|
|
111
|
+
.getPushToken?.()
|
|
112
|
+
.then((value) => {
|
|
113
|
+
if (value && !observed) enroll(value);
|
|
114
|
+
})
|
|
115
|
+
.catch(() => ports.onError());
|
|
116
|
+
return {
|
|
117
|
+
update(next: SessionActivityProps) {
|
|
118
|
+
props = next;
|
|
119
|
+
},
|
|
120
|
+
async stop() {
|
|
121
|
+
if (stopped) return;
|
|
122
|
+
stopped = true;
|
|
123
|
+
listener?.remove();
|
|
124
|
+
await queue;
|
|
125
|
+
if (token) {
|
|
126
|
+
try {
|
|
127
|
+
await ports.unregister(hostId, handle.getId(), token);
|
|
128
|
+
} catch {
|
|
129
|
+
ports.onError();
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export const ACTIVITY_STALE_MS = 2 * 60 * 1000;
|
|
137
|
+
export const FINISHED_RETENTION_MS = 15 * 60 * 1000;
|
|
138
|
+
|
|
139
|
+
/** Single app owner. All native operations, including orphan cleanup, are serialized. */
|
|
140
|
+
export function createSessionActivityOwner(factory: ActivityFactory, now = Date.now, push?: ActivityPushPorts) {
|
|
141
|
+
let queue = Promise.resolve();
|
|
142
|
+
let initialized = false;
|
|
143
|
+
let visit: string | null = null;
|
|
144
|
+
let attempted = false;
|
|
145
|
+
let current:
|
|
146
|
+
| {
|
|
147
|
+
sessionId: string;
|
|
148
|
+
hostId: string;
|
|
149
|
+
handle: ActivityHandle;
|
|
150
|
+
props: SessionActivityProps;
|
|
151
|
+
finished: boolean;
|
|
152
|
+
push?: ReturnType<typeof bindActivityPush>;
|
|
153
|
+
}
|
|
154
|
+
| undefined;
|
|
155
|
+
const reconcile = async (snapshot: ActivitySnapshot) => {
|
|
156
|
+
if (!initialized) {
|
|
157
|
+
// Handles expose getId(), not props. Unbound activities from a previous process cannot be adopted safely.
|
|
158
|
+
for (const handle of factory.getInstances()) await handle.end('immediate');
|
|
159
|
+
initialized = true;
|
|
160
|
+
}
|
|
161
|
+
if (current && !snapshot.hostIds.includes(current.hostId)) {
|
|
162
|
+
await current.push?.stop();
|
|
163
|
+
await current.handle.end('immediate');
|
|
164
|
+
current = undefined;
|
|
165
|
+
}
|
|
166
|
+
if (visit !== snapshot.sessionId) {
|
|
167
|
+
if (current && !current.finished) {
|
|
168
|
+
await current.push?.stop();
|
|
169
|
+
await current.handle.end('immediate');
|
|
170
|
+
}
|
|
171
|
+
// An already-ended Finished card keeps its system dismissal date on navigation.
|
|
172
|
+
if (!current?.finished) current = undefined;
|
|
173
|
+
visit = snapshot.sessionId;
|
|
174
|
+
attempted = false;
|
|
175
|
+
}
|
|
176
|
+
const { sessionId, hostId, url } = snapshot;
|
|
177
|
+
const props =
|
|
178
|
+
snapshot.props ??
|
|
179
|
+
(current?.sessionId === sessionId ? { ...current.props, status: 'unavailable' as const } : undefined);
|
|
180
|
+
if (!sessionId || !hostId || !snapshot.hostIds.includes(hostId) || !props || !url) return;
|
|
181
|
+
if (
|
|
182
|
+
current?.sessionId === sessionId &&
|
|
183
|
+
current.finished &&
|
|
184
|
+
(props.status === 'working' || props.status === 'question' || props.status === 'approval')
|
|
185
|
+
) {
|
|
186
|
+
await current.push?.stop();
|
|
187
|
+
await current.handle.end('immediate');
|
|
188
|
+
current = undefined;
|
|
189
|
+
attempted = false;
|
|
190
|
+
}
|
|
191
|
+
if (current?.sessionId !== sessionId) {
|
|
192
|
+
if (attempted || props.status === 'finished' || props.status === 'unavailable' || props.status === 'stale')
|
|
193
|
+
return;
|
|
194
|
+
// End a retained card before starting another one, maintaining one visible activity at most.
|
|
195
|
+
if (current) {
|
|
196
|
+
await current.push?.stop();
|
|
197
|
+
await current.handle.end('immediate');
|
|
198
|
+
}
|
|
199
|
+
current = undefined;
|
|
200
|
+
attempted = true;
|
|
201
|
+
current = {
|
|
202
|
+
sessionId,
|
|
203
|
+
hostId,
|
|
204
|
+
props,
|
|
205
|
+
handle: factory.start(props, url, new Date(now() + ACTIVITY_STALE_MS)),
|
|
206
|
+
finished: false,
|
|
207
|
+
};
|
|
208
|
+
if (push && snapshot.enrollmentSessionId)
|
|
209
|
+
current.push = bindActivityPush(current.handle, hostId, snapshot.enrollmentSessionId, props, push, now);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (current.finished) return;
|
|
213
|
+
if (!factory.getInstances().some((handle) => handle.getId() === current?.handle.getId())) {
|
|
214
|
+
// Dismissal is not a request to start again on the next summary snapshot.
|
|
215
|
+
await current.push?.stop();
|
|
216
|
+
current = undefined;
|
|
217
|
+
attempted = true;
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
current.push?.update(props);
|
|
221
|
+
if (props.status === 'finished') {
|
|
222
|
+
await current.push?.stop();
|
|
223
|
+
await current.handle.end({ after: new Date(now() + FINISHED_RETENTION_MS) }, props);
|
|
224
|
+
current.finished = true;
|
|
225
|
+
} else {
|
|
226
|
+
await current.handle.update(props, new Date(now() + ACTIVITY_STALE_MS));
|
|
227
|
+
}
|
|
228
|
+
current.props = props;
|
|
229
|
+
};
|
|
230
|
+
return {
|
|
231
|
+
reconcile(snapshot: ActivitySnapshot): Promise<void> {
|
|
232
|
+
const result = queue.then(() => reconcile(snapshot));
|
|
233
|
+
queue = result.catch(() => {
|
|
234
|
+
/* The caller reports failure; later cleanup must still run. */
|
|
235
|
+
});
|
|
236
|
+
return result;
|
|
237
|
+
},
|
|
238
|
+
stop(hostId?: string): Promise<void> {
|
|
239
|
+
const result = queue.then(async () => {
|
|
240
|
+
if (hostId !== undefined && current?.hostId !== hostId) return;
|
|
241
|
+
if (current) {
|
|
242
|
+
await current.push?.stop();
|
|
243
|
+
await current.handle.end('immediate');
|
|
244
|
+
}
|
|
245
|
+
current = undefined;
|
|
246
|
+
});
|
|
247
|
+
queue = result.catch(() => {
|
|
248
|
+
/* The caller reports failure. */
|
|
249
|
+
});
|
|
250
|
+
return result;
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -9,6 +9,7 @@ import * as Notifications from 'expo-notifications';
|
|
|
9
9
|
import { AppState, Platform } from 'react-native';
|
|
10
10
|
|
|
11
11
|
import { loadHosts, type TrustedSession } from '../deviceTrust';
|
|
12
|
+
import { trustedSessionTap } from '../sessionTap';
|
|
12
13
|
|
|
13
14
|
const NATIVE_PUSH_ROUTE = '/api/remote/native-push';
|
|
14
15
|
|
|
@@ -172,21 +173,10 @@ export function startNativePushRouting(options: {
|
|
|
172
173
|
if (stopped || !response || response.actionIdentifier !== Notifications.DEFAULT_ACTION_IDENTIFIER) return;
|
|
173
174
|
const { identifier, content } = response.notification.request;
|
|
174
175
|
if (handled.has(identifier)) return;
|
|
175
|
-
const target = content.data;
|
|
176
|
-
if (!target
|
|
177
|
-
const { hostRef, sessionId } = target as Record<string, unknown>;
|
|
178
|
-
if (
|
|
179
|
-
typeof hostRef !== 'string' ||
|
|
180
|
-
!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u.test(hostRef) ||
|
|
181
|
-
typeof sessionId !== 'string' ||
|
|
182
|
-
!sessionId ||
|
|
183
|
-
sessionId.length > 512 ||
|
|
184
|
-
Array.from(sessionId).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127) ||
|
|
185
|
-
!options.hasHost(hostRef)
|
|
186
|
-
)
|
|
187
|
-
return;
|
|
176
|
+
const target = trustedSessionTap(content.data, (id) => options.hasHost(id));
|
|
177
|
+
if (!target) return;
|
|
188
178
|
handled.add(identifier);
|
|
189
|
-
options.openSession(
|
|
179
|
+
options.openSession(target);
|
|
190
180
|
};
|
|
191
181
|
const listener = Notifications.addNotificationResponseReceivedListener(route);
|
|
192
182
|
void Notifications.getLastNotificationResponseAsync()
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export interface SessionTapTarget {
|
|
2
|
+
hostRef: string;
|
|
3
|
+
sessionId: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Push and Live Activity taps must resolve through the app's bound, known hosts. */
|
|
7
|
+
export function trustedSessionTap(target: unknown, hasHost: (id: string) => boolean): SessionTapTarget | undefined {
|
|
8
|
+
if (!target || typeof target !== 'object' || Array.isArray(target)) return undefined;
|
|
9
|
+
const { hostRef, sessionId } = target as Record<string, unknown>;
|
|
10
|
+
if (
|
|
11
|
+
typeof hostRef !== 'string' ||
|
|
12
|
+
!/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u.test(hostRef) ||
|
|
13
|
+
typeof sessionId !== 'string' ||
|
|
14
|
+
!sessionId ||
|
|
15
|
+
sessionId.length > 512 ||
|
|
16
|
+
Array.from(sessionId).some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127) ||
|
|
17
|
+
!hasHost(hostRef)
|
|
18
|
+
)
|
|
19
|
+
return undefined;
|
|
20
|
+
return { hostRef, sessionId };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function sessionActivityURL(target: SessionTapTarget): string {
|
|
24
|
+
return `po://session-activity?hostRef=${encodeURIComponent(target.hostRef)}&sessionId=${encodeURIComponent(target.sessionId)}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function sessionActivityTarget(url: string, hasHost: (id: string) => boolean): SessionTapTarget | undefined {
|
|
28
|
+
try {
|
|
29
|
+
const parsed = new URL(url);
|
|
30
|
+
if (
|
|
31
|
+
parsed.protocol !== 'po:' ||
|
|
32
|
+
parsed.hostname !== 'session-activity' ||
|
|
33
|
+
parsed.pathname ||
|
|
34
|
+
parsed.hash ||
|
|
35
|
+
parsed.username ||
|
|
36
|
+
parsed.password ||
|
|
37
|
+
parsed.port
|
|
38
|
+
)
|
|
39
|
+
return undefined;
|
|
40
|
+
const keys = [...parsed.searchParams.keys()];
|
|
41
|
+
if (keys.length !== 2 || !keys.includes('hostRef') || !keys.includes('sessionId')) return undefined;
|
|
42
|
+
return trustedSessionTap(Object.fromEntries(parsed.searchParams), hasHost);
|
|
43
|
+
} catch {
|
|
44
|
+
// A malformed external link has no trusted destination.
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
}
|