@agimon-ai/po-native 0.0.1-alpha.70 → 0.0.1-alpha.72

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.
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-native",
3
- "version": "0.0.1-alpha.70",
3
+ "version": "0.0.1-alpha.72",
4
4
  "description": "Po for iOS and Android",
5
5
  "homepage": "https://agimon.ai",
6
6
  "bugs": {
@@ -29,17 +29,17 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@agimon-ai/po-core": "0.0.0-alpha.190",
33
- "@agimon-ai/po-expo-signing": "0.0.1-alpha.70",
34
- "@agimon-ai/po-identity": "0.0.2-alpha.137",
35
- "@agimon-ai/po-native-components": "0.0.0-alpha.190",
36
- "@agimon-ai/po-native-dashboard": "0.0.0-alpha.62",
37
- "@agimon-ai/po-template-advanced": "0.0.0-alpha.190",
38
- "@agimon-ai/po-template-elegant": "0.0.0-alpha.190",
39
- "@agimon-ai/po-voice": "0.0.0-alpha.190",
40
- "@agimon-ai/po-web-components": "0.0.0-alpha.190",
41
- "@agimon-ai/po-web-dashboard": "0.0.0-alpha.190",
42
- "@agimon-ai/po-web-security": "0.0.0-alpha.190",
32
+ "@agimon-ai/po-core": "0.0.0-alpha.192",
33
+ "@agimon-ai/po-expo-signing": "0.0.1-alpha.72",
34
+ "@agimon-ai/po-identity": "0.0.2-alpha.139",
35
+ "@agimon-ai/po-native-components": "0.0.0-alpha.192",
36
+ "@agimon-ai/po-native-dashboard": "0.0.0-alpha.64",
37
+ "@agimon-ai/po-template-advanced": "0.0.0-alpha.192",
38
+ "@agimon-ai/po-template-elegant": "0.0.0-alpha.192",
39
+ "@agimon-ai/po-voice": "0.0.0-alpha.192",
40
+ "@agimon-ai/po-web-components": "0.0.0-alpha.192",
41
+ "@agimon-ai/po-web-dashboard": "0.0.0-alpha.192",
42
+ "@agimon-ai/po-web-security": "0.0.0-alpha.192",
43
43
  "@better-auth/expo": "1.7.12",
44
44
  "@config-plugins/react-native-webrtc": "15.0.2",
45
45
  "@earendil-works/chord": "1.5.2",
@@ -27,7 +27,7 @@ const UNREACHABLE =
27
27
  export function createRemoteHttp(originInput: string, fetcher: typeof fetch, relay = false) {
28
28
  const origin = remoteOrigin(originInput);
29
29
  let deviceCookie: string | undefined;
30
- async function direct(path: string, body?: unknown): Promise<Response> {
30
+ async function direct(path: string, body?: unknown, signal?: AbortSignal): Promise<Response> {
31
31
  rootPath(path);
32
32
  if (
33
33
  !/^\/api\/remote\/(?:pair(?:\/status\?request=[\w%-]+)?|channel|request|device-auth\/(?:challenge|authenticate))$/u.test(
@@ -51,6 +51,7 @@ export function createRemoteHttp(originInput: string, fetcher: typeof fetch, rel
51
51
  ...(body === undefined ? {} : { body: JSON.stringify(body) }),
52
52
  credentials: 'omit',
53
53
  redirect: 'error',
54
+ signal,
54
55
  });
55
56
  if (
56
57
  response.redirected ||
@@ -144,7 +145,7 @@ export function createSealedHttp(http: RemoteHttp, channel: SealedTransport) {
144
145
  if (body !== undefined)
145
146
  request.body = encodeBase64(typeof body === 'string' ? new TextEncoder().encode(body) : body);
146
147
  const envelope = await channel.sealText(JSON.stringify(request));
147
- const response = await http.direct('/api/remote/request', JSON.parse(envelope));
148
+ const response = await http.direct('/api/remote/request', JSON.parse(envelope), signal);
148
149
  if (!response.ok) throw new Error(`Sealed HTTP failed (${response.status}).`);
149
150
  const text = await response.text();
150
151
  if (text.length > 8 * 1024 * 1024) throw new Error('Sealed HTTP response exceeds the size limit.');
@@ -21,6 +21,33 @@ export type NativeSocketConstructor = new (
21
21
  options: { headers: Record<string, string> },
22
22
  ) => NativeSocket;
23
23
 
24
+ async function preparePreface(
25
+ channel: SealedTransport,
26
+ request: ReturnType<typeof createSealedHttp>,
27
+ signal: AbortSignal,
28
+ ): Promise<Uint8Array | undefined> {
29
+ const response = await request({ method: 'GET', target: '/api/client-devices', signal });
30
+ signal.throwIfAborted();
31
+ if (response.status === 404) return undefined;
32
+ // A team host keeps its device list from a teammate (403) and still takes the preface.
33
+ if (!response.ok && response.status !== 403) throw new Error(`Client device probe failed (${response.status}).`);
34
+ const body: unknown = response.ok ? await response.json() : undefined;
35
+ signal.throwIfAborted();
36
+ if (typeof body === 'object' && body !== null && 'devices' in body && Array.isArray(body.devices)) {
37
+ const own = body.devices.find(
38
+ (device: unknown) =>
39
+ typeof device === 'object' &&
40
+ device !== null &&
41
+ 'deviceId' in device &&
42
+ device.deviceId === currentClientMetadata().deviceId,
43
+ );
44
+ if (own && typeof own.nameUpdatedAt === 'number')
45
+ await (await initializeClientIdentity()).updateName(own.deviceName, own.nameUpdatedAt);
46
+ }
47
+ signal.throwIfAborted();
48
+ const text = JSON.stringify(poClientMetadataPreface(currentClientMetadata()));
49
+ return new TextEncoder().encode(await channel.sealText(text));
50
+ }
24
51
  /** RN supplies explicit upgrade headers. Browser WebSocket cannot implement this boundary. */
25
52
  export function createNativeProtocolLink(
26
53
  http: RemoteHttp,
@@ -29,25 +56,17 @@ export function createNativeProtocolLink(
29
56
  limit = 64 * 1024 * 1024,
30
57
  request: ReturnType<typeof createSealedHttp>,
31
58
  ): () => Promise<Link> {
32
- return async () => {
33
- const cookie = http.cookie();
34
- if (!cookie || !channel.active()) throw new Error('A paired sealed protocol channel is required.');
59
+ const openSocket = async (
60
+ cookie: string,
61
+ preface: Uint8Array | undefined,
62
+ deadline: Promise<never>,
63
+ ): Promise<Link> => {
35
64
  const socket = new Socket(`${http.origin.replace('https:', 'wss:')}/api/ws`, null, {
36
65
  headers: { Origin: http.origin, Cookie: cookie },
37
66
  });
38
67
  socket.binaryType = 'arraybuffer';
39
- const capability = Promise.resolve()
40
- .then(() => request({ method: 'GET', target: '/api/client-devices' }))
41
- .then(
42
- (response) => ({ response }),
43
- (error: unknown) => ({ error }),
44
- );
45
68
  const encoder = new TextEncoder();
46
69
  const decoder = new TextDecoder();
47
- let ended: () => void = () => {};
48
- const stopped = new Promise<void>((resolve) => {
49
- ended = resolve;
50
- });
51
70
  let terminal = false;
52
71
  let connected = false;
53
72
  let incoming = Promise.resolve();
@@ -88,14 +107,11 @@ export function createNativeProtocolLink(
88
107
  const stop = (error?: Error) => {
89
108
  if (terminal) return;
90
109
  terminal = true;
91
- ended();
92
- clearTimeout(timeout);
93
110
  socket.close();
94
111
  if (!connected) rejectOpen(error ?? new Error('Protocol socket closed before opening.'));
95
112
  port.ended(error?.message ?? 'socket closed');
96
113
  };
97
114
  const failure = (error: unknown) => stop(error instanceof Error ? error : new Error('Protocol transport failed.'));
98
- const timeout = setTimeout(() => stop(new Error('Protocol socket connection timed out.')), 15_000);
99
115
  socket.onopen = () => {
100
116
  if (terminal) return;
101
117
  connected = true;
@@ -132,49 +148,33 @@ export function createNativeProtocolLink(
132
148
  });
133
149
  };
134
150
  try {
135
- await ready;
136
- const result = capability
137
- ? await Promise.race([
138
- capability,
139
- stopped.then(() => {
140
- throw new Error('Protocol socket closed during capability probe.');
141
- }),
142
- ])
143
- : undefined;
144
- if (result && 'error' in result)
145
- throw result.error instanceof Error
146
- ? result.error
147
- : new Error('Client device probe failed.', { cause: result.error });
148
- const response = result?.response;
149
- if (response && response.status !== 404) {
150
- // A team host keeps its device list from a teammate (403) and still takes the preface.
151
- if (!response.ok && response.status !== 403)
152
- throw new Error(`Client device probe failed (${response.status}).`);
153
- const body: unknown = response.ok ? await response.json() : undefined;
154
- if (typeof body === 'object' && body !== null && 'devices' in body && Array.isArray(body.devices)) {
155
- const own = body.devices.find(
156
- (device: unknown) =>
157
- typeof device === 'object' &&
158
- device !== null &&
159
- 'deviceId' in device &&
160
- device.deviceId === currentClientMetadata().deviceId,
161
- );
162
- if (own && typeof own.nameUpdatedAt === 'number')
163
- await (await initializeClientIdentity()).updateName(own.deviceName, own.nameUpdatedAt);
164
- }
165
- if (terminal) throw new Error('Protocol socket closed while opening.');
166
- const sealed = encoder.encode(
167
- await channel.sealText(JSON.stringify(poClientMetadataPreface(currentClientMetadata()))),
168
- );
169
- if (terminal) throw new Error('Protocol socket closed while opening.');
170
- socket.send(sealed.slice().buffer as ArrayBuffer);
171
- }
151
+ await Promise.race([ready, deadline]);
172
152
  if (terminal) throw new Error('Protocol socket closed while opening.');
173
- clearTimeout(timeout);
153
+ if (preface !== undefined) socket.send(preface.slice().buffer as ArrayBuffer);
174
154
  return port.link;
175
155
  } catch (error) {
176
156
  failure(error);
177
157
  throw error;
178
158
  }
179
159
  };
160
+
161
+ return async () => {
162
+ const cookie = http.cookie();
163
+ if (!cookie || !channel.active()) throw new Error('A paired sealed protocol channel is required.');
164
+ const probe = new AbortController();
165
+ let timeout: ReturnType<typeof setTimeout> | undefined;
166
+ const deadline = new Promise<never>((_, reject) => {
167
+ timeout = setTimeout(() => {
168
+ reject(new Error('Protocol socket connection timed out.'));
169
+ probe.abort();
170
+ }, 15_000);
171
+ });
172
+ try {
173
+ // Slow HTTP must not consume the host's first-frame window after upgrade.
174
+ const preface = await Promise.race([preparePreface(channel, request, probe.signal), deadline]);
175
+ return await openSocket(cookie, preface, deadline);
176
+ } finally {
177
+ clearTimeout(timeout);
178
+ }
179
+ };
180
180
  }
@@ -130,6 +130,8 @@ export function AccountRoute(props: AccountRouteProps) {
130
130
  page="welcome"
131
131
  firstRun
132
132
  busy={mode.kind === 'checking'}
133
+ // Most people sign in with Po Cloud, so the wait wears its look rather than flashing the plain one.
134
+ hosted={mode.kind === 'checking'}
133
135
  signInUnavailable={mode.kind === 'unreachable'}
134
136
  error={mode.kind === 'unreachable' ? mode.error : undefined}
135
137
  onAction={(action) => {
package/src/app/App.tsx CHANGED
@@ -101,6 +101,8 @@ import {
101
101
  setUiTraceSink,
102
102
  traceStore,
103
103
  useRenderTrace,
104
+ useNoSessions,
105
+ STARTER_POS,
104
106
  ToolRendererBoundary,
105
107
  installedWebPlugins,
106
108
  nativeTemplateCatalog,
@@ -183,6 +185,7 @@ import { GlobalSettings } from '../screens/GlobalSettings';
183
185
  import { keepEqual, type HomeAttentionRow } from '../screens/homeModel';
184
186
  import { HomeAppsSection, HomeAttentionScreen, HomeScreen, type HomeView } from '../screens/HomeScreen';
185
187
  import { HostDrawer, HostMenuButton } from '../screens/HostDrawer';
188
+ import { FirstSessionWelcome } from '../screens/HostedOnboarding';
186
189
  import { ImagesScreen, imagesSummary, useImageSettings } from '../screens/ImagesScreen';
187
190
  import { McpServersScreen, mcpServersSummary, useMcpServers } from '../screens/McpServersScreen';
188
191
  import { MetricsScreen, useMetrics } from '../screens/MetricsScreen';
@@ -264,7 +267,13 @@ import { AccountRoute } from './AccountRoute';
264
267
  import { setActivityLoad, useActivityLoad } from './activityLoads';
265
268
  import { appearanceStore, loadAppearance, setAppearance } from './appearance';
266
269
  import { addCloudCoordinator, createCloudSession, deleteCloudSession, setCloudSessionRole } from './cloudRuntime';
267
- import { loadSentFromPhone, markSentFromPhone, sentFromPhoneStore } from './firstSteps';
270
+ import {
271
+ firstSessionWelcomeStore,
272
+ loadFirstSessionWelcome,
273
+ loadSentFromPhone,
274
+ markSentFromPhone,
275
+ sentFromPhoneStore,
276
+ } from './firstSteps';
268
277
  import { GrantNotices, SignInAskWhenSignedOut } from './GrantNotices';
269
278
  import type { HomeReadState } from './homeState';
270
279
  import { HostBackdrop, useBackdropFills } from './HostBackdrop';
@@ -279,6 +288,7 @@ import {
279
288
  setNativeTemplateChoice,
280
289
  useNativeTemplateScreen,
281
290
  } from './nativeTemplate';
291
+ import { OnboardingRoute } from './OnboardingRoute';
282
292
  import { loadOtherWorkspacesOpen, otherWorkspacesOpenStore, setOtherWorkspacesOpen } from './otherWorkspaces';
283
293
  import { pickSettingsAvatar } from './pickSettingsAvatar';
284
294
  import { useRailWorkspaces } from './railWorkspaces';
@@ -1160,6 +1170,47 @@ function SessionRoute({
1160
1170
  [sessionId]: (current[sessionId] ?? []).filter((item) => item.source !== source || item.id !== id),
1161
1171
  }));
1162
1172
  };
1173
+ /** One send for the composer and the first session's starters: not connected keeps the draft rather than throw. */
1174
+ const send = (text: string, tab?: TransientTab | ReturnType<typeof webTabs>[number]): boolean => {
1175
+ if (text.trim().startsWith('/') && capturesRef.current.length > 0) return false;
1176
+ const read = tab && 'composerContext' in tab ? tab.composerContext : undefined;
1177
+ const message = nativeComposerMessage(
1178
+ text,
1179
+ sessionId,
1180
+ [...(contexts[sessionId] ?? []), ...capturesRef.current.map((capture) => capture.context)],
1181
+ read,
1182
+ );
1183
+ if (
1184
+ !whenConnected(sessionId, () =>
1185
+ submitMessage(
1186
+ message,
1187
+ capturesRef.current.map(({ data, mimeType }) => ({ type: 'image' as const, data, mimeType })),
1188
+ sessionId,
1189
+ ),
1190
+ )
1191
+ )
1192
+ return false;
1193
+ capturesRef.current = [];
1194
+ composer.contexts.setState((current) => ({ ...current, [sessionId]: [] }));
1195
+ markSentFromPhone();
1196
+ return true;
1197
+ };
1198
+ // The session first run opened greets the person with their Po's starters until the first message.
1199
+ const welcome = useStore(firstSessionWelcomeStore, (saved) => (saved?.sessionId === sessionId ? saved : null));
1200
+ // Notices, such as Help mode turning on, do not end the welcome; the first message does.
1201
+ const conversing = useStore(store, (state) =>
1202
+ state.entries.some((entry) => entry.kind === 'user' || entry.kind === 'assistant'),
1203
+ );
1204
+ const welcomePo = STARTER_POS.find((po) => po.id === welcome?.poId);
1205
+ const firstSessionWelcome =
1206
+ welcome && welcomePo && !conversing && entry?.canInteract === true && summary?.dormant !== true ? (
1207
+ <FirstSessionWelcome
1208
+ po={welcomePo}
1209
+ name={welcome.name}
1210
+ interests={welcome.interests}
1211
+ onAsk={(ask) => void send(ask)}
1212
+ />
1213
+ ) : undefined;
1163
1214
  const isAside = (tab?: TransientTab | ReturnType<typeof webTabs>[number]) =>
1164
1215
  tab !== undefined && 'composerAside' in tab && tab.composerAside === true;
1165
1216
  const renderScreen = (
@@ -1170,6 +1221,7 @@ function SessionRoute({
1170
1221
  <LiveSessionScreen
1171
1222
  // Only the conversation is the template's; Activity detail pages stay the app's own.
1172
1223
  {...(tab ? {} : { templated: true, phoneTemplate, header, setHeader: setTemplateHeader })}
1224
+ {...(tab || firstSessionWelcome === undefined ? {} : { empty: firstSessionWelcome })}
1173
1225
  readOnly={
1174
1226
  entry?.canInteract !== true ||
1175
1227
  Boolean(tab && (!tab.retainComposer || (tab.targetSessionId && summary?.dormant)))
@@ -1207,31 +1259,7 @@ function SessionRoute({
1207
1259
  statuses={statuses}
1208
1260
  sessionToolRenderer={sessionToolRenderer}
1209
1261
  {...(offline ? { offline } : {})}
1210
- onSend={(text) => {
1211
- // Not connected: keep the draft rather than throw, which a release build turns into a crash.
1212
- if (text.trim().startsWith('/') && capturesRef.current.length > 0) return false;
1213
- const read = tab && 'composerContext' in tab ? tab.composerContext : undefined;
1214
- const message = nativeComposerMessage(
1215
- text,
1216
- sessionId,
1217
- [...(contexts[sessionId] ?? []), ...capturesRef.current.map((capture) => capture.context)],
1218
- read,
1219
- );
1220
- if (
1221
- !whenConnected(sessionId, () =>
1222
- submitMessage(
1223
- message,
1224
- capturesRef.current.map(({ data, mimeType }) => ({ type: 'image' as const, data, mimeType })),
1225
- sessionId,
1226
- ),
1227
- )
1228
- )
1229
- return false;
1230
- capturesRef.current = [];
1231
- composer.contexts.setState((current) => ({ ...current, [sessionId]: [] }));
1232
- markSentFromPhone();
1233
- return true;
1234
- }}
1262
+ onSend={(text) => send(text, tab)}
1235
1263
  composer={{
1236
1264
  live: true,
1237
1265
  searchFiles: (query: string) => searchFiles(sessionId, query),
@@ -1951,7 +1979,7 @@ async function withSummaryChange<R>(
1951
1979
  return result;
1952
1980
  } catch (error) {
1953
1981
  restore();
1954
- throw error;
1982
+ throw error instanceof Error ? error : new Error(String(error), { cause: error });
1955
1983
  }
1956
1984
  }
1957
1985
 
@@ -2631,6 +2659,14 @@ function HomeRoute({
2631
2659
  const [refreshing, setRefreshing] = useState(false);
2632
2660
  const sentFromPhone = useStore(sentFromPhoneStore, (value) => value);
2633
2661
  const onOpenSession = useOpenSession();
2662
+ const noSessions = useNoSessions();
2663
+ // First run stays up until it opens its session, so the new session's listing cannot flash Home first.
2664
+ const firstRun = useRef(false);
2665
+ const navigation = useNavigation<NativeStackNavigationProp<Routes>>();
2666
+ const onConnectProvider = useCallback(
2667
+ () => navigation.navigate('SettingsProviders', hostId === undefined ? undefined : { hostId }),
2668
+ [navigation, hostId],
2669
+ );
2634
2670
  const onOpenTarget = useOpenAttention();
2635
2671
  const onRefresh = useCallback(() => {
2636
2672
  setRefreshing(true);
@@ -2652,6 +2688,20 @@ function HomeRoute({
2652
2688
  () => (connect ? { ...connect, cameraEnabled: focused && connect.cameraEnabled !== false } : undefined),
2653
2689
  [connect, focused],
2654
2690
  );
2691
+ // A computer with no sessions yet starts with first run, as the web does: choose a Po, then meet it.
2692
+ // ponytail: one computer only; with several paired, Home stays as it is until one is chosen.
2693
+ if (noSessions) firstRun.current = true;
2694
+ if (firstRun.current && !signedOut && !multi && runtime !== undefined && hostId !== undefined)
2695
+ return (
2696
+ <OnboardingRoute
2697
+ hostId={hostId}
2698
+ onOpenSession={(sessionId) => {
2699
+ firstRun.current = false;
2700
+ onOpenSession(sessionId);
2701
+ }}
2702
+ onConnectProvider={onConnectProvider}
2703
+ />
2704
+ );
2655
2705
  return (
2656
2706
  <StableHomeScreen
2657
2707
  view={view}
@@ -3259,6 +3309,7 @@ export function App({ nativeHost }: { nativeHost?: (sessionId: string) => Native
3259
3309
  }, [hostStates, trustLoaded, composer]);
3260
3310
 
3261
3311
  useEffect(loadSentFromPhone, []);
3312
+ useEffect(loadFirstSessionWelcome, []);
3262
3313
  useEffect(loadAppearance, []);
3263
3314
  useEffect(loadOtherWorkspacesOpen, []);
3264
3315
  useEffect(loadSessionView, []);
@@ -0,0 +1,134 @@
1
+ import { encodeBase64 } from '@agimon-ai/po-core/native';
2
+ import {
3
+ createStarterProfile,
4
+ runCommand,
5
+ saveStarterAboutYou,
6
+ STARTER_POS,
7
+ type StarterPo,
8
+ waitForSession,
9
+ whenSessionReady,
10
+ } from '@agimon-ai/po-web-dashboard/core';
11
+ import { useFocusEffect } from '@react-navigation/native';
12
+ import { useCallback, useState } from 'react';
13
+ import { Image } from 'react-native';
14
+
15
+ import { AboutYouStep, ChoosePoDeck, ConnectProviderStep, PO_ART } from '../screens/HostedOnboarding';
16
+ import { apiTransportForHost } from '../services/apiTransport';
17
+ import { openFirstSession } from '../services/hostActions';
18
+ import { listProviders } from '../services/settingsApi';
19
+ import { rememberFirstSessionWelcome } from './firstSteps';
20
+
21
+ /** The mode's own activate action, as the mode menu sends it: a mode already on stays on. */
22
+ const HELP_COMMAND = 'mode help activate';
23
+ const NOT_LISTED = 'Your Po is ready, but its conversation has not shown up yet. Pull to refresh Home.';
24
+
25
+ /** The panda as a PNG data URL for the profile; undefined if it cannot be read, so the Po starts without one. */
26
+ async function avatarPngBase64(po: StarterPo): Promise<string | undefined> {
27
+ try {
28
+ const uri = Image.resolveAssetSource(PO_ART[po.id].avatar)?.uri;
29
+ if (uri === undefined) return undefined;
30
+ const response = await fetch(uri);
31
+ if (!response.ok) return undefined;
32
+ return `data:image/png;base64,${encodeBase64(new Uint8Array(await response.arrayBuffer()))}`;
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * The phone's first run on a computer with no sessions yet: an AI provider if none is connected, then
40
+ * the deck, then About you, then the Po's first session with Help mode on. That session ends it.
41
+ */
42
+ export function OnboardingRoute({
43
+ hostId,
44
+ onOpenSession,
45
+ onConnectProvider,
46
+ }: {
47
+ hostId: string;
48
+ onOpenSession: (sessionId: string) => void;
49
+ onConnectProvider: () => void;
50
+ }) {
51
+ const [provider, setProvider] = useState<'checking' | 'connected' | 'missing'>('checking');
52
+ const [po, setPo] = useState<StarterPo | null>(null);
53
+ const [settingUpId, setSettingUpId] = useState<string | undefined>(undefined);
54
+ const [failed, setFailed] = useState<{ id: string; error: string } | undefined>(undefined);
55
+ const [name, setName] = useState('');
56
+ const [interests, setInterests] = useState('');
57
+ const [busy, setBusy] = useState(false);
58
+ const [error, setError] = useState('');
59
+
60
+ // Read again on coming back from the Providers screen.
61
+ useFocusEffect(
62
+ useCallback(() => {
63
+ let active = true;
64
+ void listProviders(hostId).then((result) => {
65
+ if (!active) return;
66
+ // An unreadable list must not trap anyone in setup, so it counts as connected.
67
+ const connected =
68
+ !('providers' in result) ||
69
+ result.providers.some((entry) => entry.kind !== 'po-feature' && entry.authenticated !== undefined);
70
+ setProvider(connected ? 'connected' : 'missing');
71
+ });
72
+ return () => {
73
+ active = false;
74
+ };
75
+ }, [hostId]),
76
+ );
77
+
78
+ const choose = async (chosen: StarterPo): Promise<void> => {
79
+ setFailed(undefined);
80
+ setSettingUpId(chosen.id);
81
+ const ready = await createStarterProfile(chosen, apiTransportForHost(hostId), await avatarPngBase64(chosen));
82
+ setSettingUpId(undefined);
83
+ if (ready) setPo(chosen);
84
+ else setFailed({ id: chosen.id, error: `${chosen.name} couldn't get ready. Nothing was changed, so try again.` });
85
+ };
86
+
87
+ // The new session ends this flow, so only a failure comes back here.
88
+ const finish = async (chosen: StarterPo): Promise<void> => {
89
+ if (busy) return;
90
+ setError('');
91
+ setBusy(true);
92
+ const fail = (message: string) => {
93
+ setBusy(false);
94
+ setError(message);
95
+ };
96
+ if (!(await saveStarterAboutYou(name, interests, apiTransportForHost(hostId))))
97
+ return fail(`${chosen.name} couldn't save that just now. Your answers are still here, so you can try again.`);
98
+ const opened = await openFirstSession(hostId, chosen);
99
+ if ('error' in opened) return fail(opened.error);
100
+ const { sessionId } = opened;
101
+ rememberFirstSessionWelcome({ sessionId, poId: chosen.id, name: name.trim(), interests: interests.trim() });
102
+ if (!(await waitForSession(sessionId))) return fail(NOT_LISTED);
103
+ void whenSessionReady(sessionId, () => runCommand(HELP_COMMAND, sessionId));
104
+ onOpenSession(sessionId);
105
+ };
106
+
107
+ if (provider === 'checking') return null;
108
+ if (provider === 'missing') return <ConnectProviderStep onConnect={onConnectProvider} />;
109
+ if (po === null)
110
+ return (
111
+ <ChoosePoDeck
112
+ pos={STARTER_POS}
113
+ {...(settingUpId === undefined ? {} : { settingUpId })}
114
+ {...(failed === undefined ? {} : { failed })}
115
+ onChoose={(chosen) => void choose(chosen)}
116
+ />
117
+ );
118
+ return (
119
+ <AboutYouStep
120
+ po={po}
121
+ name={name}
122
+ interests={interests}
123
+ busy={busy}
124
+ {...(error === '' ? {} : { error })}
125
+ onNameChange={setName}
126
+ onInterestsChange={setInterests}
127
+ onBack={() => {
128
+ setError('');
129
+ setPo(null);
130
+ }}
131
+ onContinue={() => void finish(po)}
132
+ />
133
+ );
134
+ }
@@ -1,9 +1,50 @@
1
+ import type { StarterPo } from '@agimon-ai/po-web-dashboard/core';
1
2
  import { Store } from '@tanstack/store';
2
3
  import * as SecureStore from 'expo-secure-store';
3
4
 
4
5
  const SENT_FROM_PHONE_KEY = 'po.sent-from-phone';
6
+ const FIRST_SESSION_WELCOME_KEY = 'po.first-session-welcome';
5
7
  const SET = '1';
6
8
 
9
+ /** The session first run opened, and what its Po greets the person with until the first message. */
10
+ export interface FirstSessionWelcome {
11
+ sessionId: string;
12
+ poId: StarterPo['id'];
13
+ name: string;
14
+ interests: string;
15
+ }
16
+
17
+ /**
18
+ * ponytail: this phone only, as the web keeps its own; another device shows the plain empty
19
+ * conversation. Move it to the session's metadata if the welcome should follow the person.
20
+ */
21
+ export const firstSessionWelcomeStore = new Store<FirstSessionWelcome | null>(null);
22
+
23
+ export function loadFirstSessionWelcome(): void {
24
+ SecureStore.getItemAsync(FIRST_SESSION_WELCOME_KEY)
25
+ .then((value) => {
26
+ if (value === null) return;
27
+ const parsed: unknown = JSON.parse(value);
28
+ if (
29
+ typeof parsed === 'object' &&
30
+ parsed !== null &&
31
+ typeof (parsed as FirstSessionWelcome).sessionId === 'string'
32
+ )
33
+ firstSessionWelcomeStore.setState(() => parsed as FirstSessionWelcome);
34
+ })
35
+ // Unreadable or malformed means no welcome; the session shows its plain empty conversation.
36
+ .catch(() => undefined);
37
+ }
38
+
39
+ export function rememberFirstSessionWelcome(welcome: FirstSessionWelcome): void {
40
+ firstSessionWelcomeStore.setState(() => welcome);
41
+ SecureStore.setItemAsync(FIRST_SESSION_WELCOME_KEY, JSON.stringify(welcome)).then(
42
+ () => undefined,
43
+ // Kept in memory for this run; an unsaved welcome only means the plain conversation after a restart.
44
+ () => undefined,
45
+ );
46
+ }
47
+
7
48
  /** Whether this phone has ever sent Po a message: Home's last getting-started step. */
8
49
  export const sentFromPhoneStore = new Store(false);
9
50
 
@@ -535,9 +535,10 @@ export function createHostRuntimes(
535
535
  });
536
536
  },
537
537
  onSummariesLoaded() {
538
- if (!active()) return;
538
+ if (!active() || entry.status === 'connected') return;
539
539
  entry.status = 'connected';
540
540
  changed();
541
+ repairLinks();
541
542
  },
542
543
  onPluginCompatibility(issues) {
543
544
  if (!active()) return;
@@ -557,10 +558,8 @@ export function createHostRuntimes(
557
558
  changed();
558
559
  const trusted = await trustedSession;
559
560
  if (!active()) throw new Error('The host connection was replaced.');
560
- if (!saved) entry.status = 'connected';
561
561
  entry.push = startNativePush(trusted, requestPermission, host.id);
562
562
  changed();
563
- repairLinks();
564
563
  return runtime;
565
564
  } catch (error) {
566
565
  entry.lanTransport?.close();