@agimon-ai/po-native 0.0.1-alpha.56 → 0.0.1-alpha.58

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-native",
3
- "version": "0.0.1-alpha.56",
3
+ "version": "0.0.1-alpha.58",
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.176",
33
- "@agimon-ai/po-expo-signing": "0.0.1-alpha.56",
34
- "@agimon-ai/po-identity": "0.0.2-alpha.123",
35
- "@agimon-ai/po-native-components": "0.0.0-alpha.176",
36
- "@agimon-ai/po-native-dashboard": "0.0.0-alpha.48",
37
- "@agimon-ai/po-template-advanced": "0.0.0-alpha.176",
38
- "@agimon-ai/po-template-elegant": "0.0.0-alpha.176",
39
- "@agimon-ai/po-voice": "0.0.0-alpha.176",
40
- "@agimon-ai/po-web-components": "0.0.0-alpha.176",
41
- "@agimon-ai/po-web-dashboard": "0.0.0-alpha.176",
42
- "@agimon-ai/po-web-security": "0.0.0-alpha.176",
32
+ "@agimon-ai/po-core": "0.0.0-alpha.178",
33
+ "@agimon-ai/po-expo-signing": "0.0.1-alpha.58",
34
+ "@agimon-ai/po-identity": "0.0.2-alpha.125",
35
+ "@agimon-ai/po-native-components": "0.0.0-alpha.178",
36
+ "@agimon-ai/po-native-dashboard": "0.0.0-alpha.50",
37
+ "@agimon-ai/po-template-advanced": "0.0.0-alpha.178",
38
+ "@agimon-ai/po-template-elegant": "0.0.0-alpha.178",
39
+ "@agimon-ai/po-voice": "0.0.0-alpha.178",
40
+ "@agimon-ai/po-web-components": "0.0.0-alpha.178",
41
+ "@agimon-ai/po-web-dashboard": "0.0.0-alpha.178",
42
+ "@agimon-ai/po-web-security": "0.0.0-alpha.178",
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",
@@ -147,6 +147,7 @@ function HostedAccountRoute({
147
147
  const { session } = current;
148
148
  return (await loadCloudHosts()).find(
149
149
  (host) =>
150
+ !host.computer &&
150
151
  host.hosted?.apiPrefix === current.cloudApiPrefix &&
151
152
  host.person.issuer === current.issuer &&
152
153
  host.person.subject === session?.userId &&
package/src/app/App.tsx CHANGED
@@ -552,7 +552,7 @@ function useSessionList(hosts: readonly HostRuntimeState[]): SessionSummary[] {
552
552
  workspaces.find((workspace) => workspace.id === summary.workspaceId)?.kind === 'session'
553
553
  ? undefined
554
554
  : summary.cwd,
555
- hostLabel: host ? (host.host.displayName ?? new URL(host.host.origin).hostname) : undefined,
555
+ hostLabel: host ? hostDisplayName(host.host) : undefined,
556
556
  status: card?.status,
557
557
  ...(card?.clock ? { clock: card.clock } : {}),
558
558
  stale: host !== undefined && host.status !== 'connected',
@@ -1964,7 +1964,7 @@ function SessionsRoute({
1964
1964
  ),
1965
1965
  hosts: hostStates.map(({ host, status }) => ({
1966
1966
  id: host.id,
1967
- label: host.displayName ?? new URL(host.origin).hostname,
1967
+ label: hostDisplayName(host),
1968
1968
  status,
1969
1969
  onRetry: connections?.find(({ id }) => id === host.id)?.onRetry ?? (() => undefined),
1970
1970
  createGeneralSession: () => {
@@ -2351,7 +2351,7 @@ function SessionsRoute({
2351
2351
  {hostStates.map(({ host, status }) => (
2352
2352
  <ComputerRow
2353
2353
  key={host.id}
2354
- name={host.displayName ?? new URL(host.origin).hostname}
2354
+ name={hostDisplayName(host)}
2355
2355
  status={status}
2356
2356
  onPress={() => {
2357
2357
  setChoosingGeneralHost(false);
@@ -3144,7 +3144,8 @@ export function App({ nativeHost }: { nativeHost?: (sessionId: string) => Native
3144
3144
  }),
3145
3145
  ]);
3146
3146
  if (!mounted) return;
3147
- for (const host of cloud)
3147
+ // The Cloud account re-discovers its computers after its first successful signed-in poll.
3148
+ for (const host of cloud.filter((candidate) => !candidate.computer))
3148
3149
  void manager.connect(host).catch((error: unknown) => {
3149
3150
  // One Po Cloud host failing must not stop the others or the paired computers.
3150
3151
  console.warn('Po Cloud host did not connect:', messageOf(error, 'unreachable'));
@@ -27,6 +27,7 @@ import {
27
27
  type HostViewRecord,
28
28
  } from '../screens/HostsView';
29
29
  import { createAccountClient, loadLocalAccount, selectedIdentityIssuer } from '../services/accountClient';
30
+ import { hostDisplayName } from '../services/deviceTrust';
30
31
  import { createHostLinkBroker, HostLinkConfirmationNeeded, type HostLinks } from '../services/hostLinkBroker';
31
32
  import { hostSnapshots } from '../services/hostSnapshots';
32
33
  import type { HostRuntimes, HostRuntimeState } from './hostRuntimes';
@@ -37,7 +38,7 @@ const message = (error: unknown) => (error instanceof Error ? error.message : 'T
37
38
  export const hostViewRecords = (states: readonly HostRuntimeState[]): HostViewRecord[] =>
38
39
  states.map(({ host, status }) => ({
39
40
  id: host.id,
40
- label: host.displayName ?? new URL(host.origin).host,
41
+ label: hostDisplayName(host),
41
42
  origin: new URL(host.origin).host,
42
43
  status: status === 'connected' ? 'Connected' : status === 'connecting' ? 'Connecting' : 'Disconnected',
43
44
  }));
@@ -21,7 +21,7 @@ import { fetch as nativeFetch } from 'expo/fetch';
21
21
 
22
22
  import { cloudCookie } from '../services/accountClient';
23
23
  import { currentClientMetadata, refreshClientDeviceName } from '../services/clientIdentity';
24
- import type { CloudHostRecord } from '../services/cloudHosts';
24
+ import { syncCloudComputers, type CloudHostRecord } from '../services/cloudHosts';
25
25
  import type { PushEnrollment } from '../services/nativePush';
26
26
  import { type SessionRuntime, startSessionRuntime } from '../services/sessionRuntime';
27
27
  import { createHomeReader } from './homeState';
@@ -63,13 +63,24 @@ export interface CloudRuntimeOptions {
63
63
  }
64
64
 
65
65
  /** Where this cloud host's API lives: the origin, under hosted Po Cloud's prefix. */
66
- export function cloudBase(host: Pick<CloudHostRecord, 'origin' | 'hosted'>): string {
67
- return `${host.origin}${host.hosted?.apiPrefix ?? ''}`;
66
+ export function cloudBase(host: Pick<CloudHostRecord, 'origin' | 'hosted' | 'computer'>): string {
67
+ return host.computer
68
+ ? `${host.origin}/hosts/${host.computer.hostId}`
69
+ : `${host.origin}${host.hosted?.apiPrefix ?? ''}`;
68
70
  }
69
71
 
70
- /** Cookie admission: the session cookie and the org it is used for. Origin stays absent. */
72
+ /** Cookie admission, scoped to the org and, for computers, the listed link generation. */
71
73
  export function cloudHeaders(host: CloudHostRecord, cookie: string): Record<string, string> {
72
- return { Cookie: cookie, 'x-po-org': host.networkId };
74
+ return {
75
+ Cookie: cookie,
76
+ 'x-po-org': host.networkId,
77
+ ...(host.computer
78
+ ? {
79
+ 'x-po-relay-generation': `${host.computer.generation}`,
80
+ 'x-po-relay-subject': encodeURIComponent(host.person.subject),
81
+ }
82
+ : {}),
83
+ };
73
84
  }
74
85
 
75
86
  /** A fetch that carries this cloud host's cookie admission, refusing to send without a cookie. */
@@ -78,21 +89,27 @@ export function cloudFetch(host: CloudHostRecord, options: Pick<CloudRuntimeOpti
78
89
  const fetcher = options.fetch ?? nativeFetch;
79
90
  return async (
80
91
  url: string,
81
- init: { method?: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal } = {},
92
+ init: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array; signal?: AbortSignal } = {},
82
93
  ): Promise<Response> => {
83
94
  const target = new URL(url);
84
95
  // Cloud API calls, plus hosted Po Cloud's own `/api/owner` routes such as push enrollment.
85
96
  if (
86
97
  target.origin !== new URL(host.origin).origin ||
87
- !(target.href.startsWith(`${cloudBase(host)}/api/`) || target.pathname.startsWith('/api/owner/'))
98
+ !(
99
+ target.href.startsWith(`${cloudBase(host)}/api/`) ||
100
+ (!host.computer && target.pathname.startsWith('/api/owner/'))
101
+ )
88
102
  )
89
103
  throw new Error('Expected a configured Po Cloud API target.');
90
104
  const cookie = await readCookie();
91
105
  if (!cookie) throw new Error(SIGNED_OUT);
92
106
  // Hosted Po Cloud admits a cookie write only from the app scheme with its CSRF header.
93
107
  const write = host.hosted !== undefined && init.method !== undefined && !['GET', 'HEAD'].includes(init.method);
108
+ const { body, ...rest } = init;
94
109
  return fetcher(url, {
95
- ...init,
110
+ ...rest,
111
+ // Bytes, such as an attachment upload, go as their own copy of the buffer.
112
+ ...(body === undefined ? {} : { body: typeof body === 'string' ? body : body.slice().buffer }),
96
113
  headers: {
97
114
  ...(write ? HOSTED_WRITE_HEADERS : {}),
98
115
  ...init.headers,
@@ -104,6 +121,24 @@ export function cloudFetch(host: CloudHostRecord, options: Pick<CloudRuntimeOpti
104
121
  };
105
122
  }
106
123
 
124
+ /** Discover only after the hosted account has been admitted. A failed read never forgets saved computers. */
125
+ export async function refreshCloudComputers(
126
+ cloud: CloudHostRecord,
127
+ options: Pick<CloudRuntimeOptions, 'cookie' | 'fetch'> = {},
128
+ signal?: AbortSignal,
129
+ ): Promise<CloudHostRecord[] | undefined> {
130
+ if (!cloud.hosted || cloud.computer) return undefined;
131
+ const response = await cloudFetch(cloud, options)(`${cloud.origin}/api/owner/relay-computers`, {
132
+ headers: { 'x-po-relay-subject': encodeURIComponent(cloud.person.subject) },
133
+ ...(signal ? { signal } : {}),
134
+ });
135
+ if (response.status === 404) return undefined; // Older or relay-disabled Cloud deployment.
136
+ if (!response.ok) throw new Error(`Could not list linked computers (${response.status}).`);
137
+ const listing: unknown = await response.json();
138
+ if (signal?.aborted) return undefined;
139
+ return syncCloudComputers(cloud, listing);
140
+ }
141
+
107
142
  /**
108
143
  * One Po API call to this cloud host, in the shape the paired-computer transport sends. Po Cloud answers
109
144
  * the same `/api` routes under its prefix, so Settings reads it the way it reads a computer.
@@ -116,18 +151,62 @@ export function cloudApiSend(host: CloudHostRecord, options: Pick<CloudRuntimeOp
116
151
  target: string;
117
152
  headers?: readonly (readonly [string, string])[];
118
153
  body?: string | Uint8Array;
154
+ signal?: AbortSignal;
119
155
  },
120
- signal?: AbortSignal,
121
- ): Promise<Response> => {
122
- // ponytail: text bodies only. A route that uploads bytes to Po Cloud needs a byte path here.
123
- if (request.body !== undefined && typeof request.body !== 'string')
124
- throw new Error('Po Cloud takes text requests only.');
125
- return send(`${cloudBase(host)}${request.target}`, {
156
+ signal = request.signal,
157
+ ): Promise<Response> =>
158
+ send(`${cloudBase(host)}${request.target}`, {
126
159
  method: request.method,
127
160
  headers: Object.fromEntries(request.headers ?? []),
128
161
  ...(request.body === undefined ? {} : { body: request.body }),
129
162
  ...(signal === undefined ? {} : { signal }),
130
163
  });
164
+ }
165
+
166
+ /** Opens one cookie-admitted socket at `path` under this host's API and resolves once it is open. */
167
+ async function openCloudSocket(
168
+ host: CloudHostRecord,
169
+ path: string,
170
+ cookie: string,
171
+ Socket: CloudSocketConstructor,
172
+ ): Promise<CloudSocket> {
173
+ const url = new URL(`${cloudBase(host).replace(/^https:/u, 'wss:')}${path}`);
174
+ url.searchParams.set('poClient', encodePoClientMetadata(currentClientMetadata()));
175
+ const socket = new Socket(url.toString(), null, {
176
+ headers: { ...cloudHeaders(host, cookie), ...(host.computer ? { origin: HOSTED_WRITE_HEADERS.origin } : {}) },
177
+ });
178
+ socket.binaryType = 'arraybuffer';
179
+ // Chord's link must start on an open socket; anything before that is a failed attempt.
180
+ await new Promise<void>((resolve, reject) => {
181
+ let settled = false;
182
+ const settle = (error?: Error) => {
183
+ if (settled) return;
184
+ settled = true;
185
+ clearTimeout(timer);
186
+ if (error) {
187
+ socket.close();
188
+ reject(error);
189
+ } else resolve();
190
+ };
191
+ const timer = setTimeout(() => settle(new Error('Po Cloud did not answer in time.')), SOCKET_OPEN_TIMEOUT_MS);
192
+ socket.addEventListener('open', () => settle());
193
+ socket.addEventListener('error', (event) => settle(new Error(event?.message ?? 'Po Cloud socket failed.')));
194
+ socket.addEventListener('close', () => settle(new Error('Po Cloud closed the socket before it opened.')));
195
+ });
196
+ return socket;
197
+ }
198
+
199
+ /** A linked computer's host protocol through Po Cloud: the socket a paired device opens, with the person's sign-in. */
200
+ export function cloudComputerLink(
201
+ host: CloudHostRecord,
202
+ options: Pick<CloudRuntimeOptions, 'cookie' | 'Socket'> = {},
203
+ ): () => Promise<Link> {
204
+ const readCookie = options.cookie ?? (() => cloudCookie(host));
205
+ const Socket = options.Socket ?? (WebSocket as unknown as CloudSocketConstructor);
206
+ return async () => {
207
+ const cookie = await readCookie();
208
+ if (!cookie) throw new Error(SIGNED_OUT);
209
+ return webSocketLink((await openCloudSocket(host, '/api/ws', cookie, Socket)) as unknown as WebSocketLike);
131
210
  };
132
211
  }
133
212
 
@@ -313,38 +392,21 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
313
392
  | { sessionId: string; runtime: SessionRuntime; sockets: Set<CloudSocket>; stopAccess(): void }
314
393
  | undefined;
315
394
  let closed = false;
395
+ let online = host.computer === undefined;
316
396
 
317
397
  const openLink = async (sessionId: string, sockets: Set<CloudSocket>, reauthenticate: () => void): Promise<Link> => {
318
398
  const workspaceId = sessionsStore.state.byId[sessionId]?.summary.workspaceId;
319
399
  if (!workspaceId) throw new Error('This Po Cloud session has no workspace yet.');
320
400
  const cookie = await readCookie();
401
+ if (closed || !online || binding?.sockets !== sockets) throw new Error('The session connection was replaced.');
321
402
  if (!cookie) throw new Error(SIGNED_OUT);
322
403
  const path = `/api/workspaces/${encodeURIComponent(localHostId(host.id, workspaceId))}/sessions/${encodeURIComponent(localHostId(host.id, sessionId))}/ws`;
323
- const url = new URL(`${cloudBase(host).replace(/^https:/u, 'wss:')}${path}`);
324
- url.searchParams.set('poClient', encodePoClientMetadata(currentClientMetadata()));
325
- const socket = new Socket(url.toString(), null, {
326
- headers: cloudHeaders(host, cookie),
327
- });
328
- socket.binaryType = 'arraybuffer';
404
+ const socket = await openCloudSocket(host, path, cookie, Socket);
405
+ if (closed || binding?.sockets !== sockets) {
406
+ socket.close();
407
+ throw new Error('The session connection was replaced.');
408
+ }
329
409
  sockets.add(socket);
330
- // Chord's link must start on an open socket; anything before that is a failed attempt.
331
- await new Promise<void>((resolve, reject) => {
332
- let settled = false;
333
- const settle = (error?: Error) => {
334
- if (settled) return;
335
- settled = true;
336
- clearTimeout(timer);
337
- if (error) {
338
- sockets.delete(socket);
339
- socket.close();
340
- reject(error);
341
- } else resolve();
342
- };
343
- const timer = setTimeout(() => settle(new Error('Po Cloud did not answer in time.')), SOCKET_OPEN_TIMEOUT_MS);
344
- socket.addEventListener('open', () => settle());
345
- socket.addEventListener('error', (event) => settle(new Error(event?.message ?? 'Po Cloud socket failed.')));
346
- socket.addEventListener('close', () => settle(new Error('Po Cloud closed the socket before it opened.')));
347
- });
348
410
  socket.addEventListener('close', (event) => {
349
411
  sockets.delete(socket);
350
412
  if (event?.code === CLOUD_REAUTHENTICATE_CLOSE) reauthenticate();
@@ -386,9 +448,11 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
386
448
  onSnapshot({ workspaces, sessions }) {
387
449
  if (closed) return;
388
450
  // Registry absence must not discard a valid cloud snapshot.
389
- void refreshClientDeviceName(() =>
390
- cloudFetch(host, { cookie: readCookie, fetch: options.fetch })(`${cloudBase(host)}/api/client-devices`),
391
- ).catch(() => undefined);
451
+ if (!host.computer)
452
+ void refreshClientDeviceName(() =>
453
+ cloudFetch(host, { cookie: readCookie, fetch: options.fetch })(`${cloudBase(host)}/api/client-devices`),
454
+ ).catch(() => undefined);
455
+ online = true;
392
456
  applySessionsSnapshot({ sessions }, host.id);
393
457
  applyWorkspacesSnapshot({ workspaces }, host.id);
394
458
  home.setSupported(false);
@@ -398,7 +462,12 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
398
462
  else if (focused !== null && binding === undefined) bind(focused);
399
463
  },
400
464
  onError(error) {
401
- if (!closed) options.onError?.(error.message);
465
+ if (closed) return;
466
+ if (host.computer) {
467
+ online = false;
468
+ stopBinding();
469
+ }
470
+ options.onError?.(error.message);
402
471
  },
403
472
  });
404
473
 
@@ -420,12 +489,12 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
420
489
  }
421
490
  setActiveSession(next);
422
491
  // Before the first list the session's workspace is unknown; the snapshot binds it.
423
- if (sessionsStore.state.byId[next]?.summary.workspaceId) bind(next);
492
+ if (online && sessionsStore.state.byId[next]?.summary.workspaceId) bind(next);
424
493
  else stopBinding();
425
494
  },
426
495
  /** A cloud session boots when its socket opens, so waking reconnects the focused one. */
427
496
  async wake(sessionId) {
428
- if (!closed && sessionId === focused) bind(sessionId);
497
+ if (!closed && online && sessionId === focused) bind(sessionId);
429
498
  },
430
499
  async searchFiles() {
431
500
  return [];
@@ -33,12 +33,20 @@ import { startNativePush, startPushEnrollment, unregisterNativePush } from '../s
33
33
  import { parsePairingUrl } from '../services/pairing';
34
34
  import type { PluginCompatibility } from '../services/pluginRuntime';
35
35
  import { createRelayTransport } from '../services/relayTransport';
36
- import { cloudApiSend, cloudPushEnrollment, startCloudRuntime } from './cloudRuntime';
36
+ import {
37
+ cloudApiSend,
38
+ cloudComputerLink,
39
+ cloudPushEnrollment,
40
+ refreshCloudComputers,
41
+ startCloudRuntime,
42
+ } from './cloudRuntime';
37
43
  import { type ActivityLoadState, type LiveRuntime, startLiveRuntime } from './liveRuntime';
38
44
  import { activateNativeTemplateHost, resetNativeTemplateChoice } from './nativeTemplate';
39
45
 
40
46
  /** Forget tells a reachable computer or Po Cloud to stop pushing to this phone, but never waits on an offline one. */
41
47
  const PUSH_DEREGISTER_DEADLINE_MS = 2_000;
48
+ /** A Cloud-linked computer's protocol socket dropped: try again after this, so an offline computer is not hammered. */
49
+ const CLOUD_COMPUTER_RECONNECT_MS = 3_000;
42
50
 
43
51
  async function withinDeadline(operation: Promise<unknown>, deferred: string): Promise<void> {
44
52
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -156,30 +164,122 @@ export function createHostRuntimes(
156
164
  entry.lanTransport = undefined;
157
165
  };
158
166
 
159
- /** Cloud hosts poll and focus over cookie admission, and enroll push with the person's account. */
167
+ const dropCloudEntry = (entry: HostRuntimeEntry) => {
168
+ const { id } = entry.host;
169
+ stopEntry(entry);
170
+ entries.delete(id);
171
+ applySessionsSnapshot({ sessions: [] }, id);
172
+ applyWorkspacesSnapshot({ workspaces: [] }, id);
173
+ if (focused !== null && splitHostId(focused)?.hostId === id) focused = null;
174
+ changed();
175
+ };
176
+
177
+ /** Cloud hosts poll and focus over cookie admission. Only the Cloud service enrolls push. */
160
178
  const connectCloud = (host: CloudHostRecord, requestPermission: boolean): LiveRuntime => {
161
179
  const previous = entries.get(host.id);
162
180
  if (previous) stopEntry(previous);
163
181
  const entry: HostRuntimeEntry = { host, status: 'connecting', controller: new AbortController() };
164
182
  entries.set(host.id, entry);
165
183
  const active = () => !closed && entries.get(host.id) === entry && !forgetting.has(host.id);
166
- const runtime = startCloudRuntime(host, {
167
- onSummariesLoaded() {
168
- if (!active() || entry.status === 'connected') return;
169
- entry.status = 'connected';
170
- changed();
171
- },
172
- onError(message) {
173
- if (!active() || entry.error === message) return;
174
- entry.error = message;
175
- if (message !== undefined && entry.status === 'connecting') entry.status = 'disconnected';
176
- changed();
177
- },
178
- });
184
+ let discovering = false;
185
+ const discoverComputers = async () => {
186
+ discovering = true;
187
+ try {
188
+ const computers = await refreshCloudComputers(host, {}, entry.controller.signal);
189
+ if (!active() || !computers) return;
190
+ for (const candidate of entries.values()) {
191
+ const existing = candidate.host;
192
+ if (
193
+ !isCloudHost(existing) ||
194
+ !existing.computer ||
195
+ existing.networkId !== host.networkId ||
196
+ existing.person.issuer !== host.person.issuer ||
197
+ existing.person.subject !== host.person.subject
198
+ )
199
+ continue;
200
+ const latest = computers.find(({ id }) => id === existing.id);
201
+ if (!latest || latest.computer?.generation !== existing.computer.generation) dropCloudEntry(candidate);
202
+ else if (latest.label !== existing.label || latest.computer?.publicKey !== existing.computer.publicKey) {
203
+ // A newly listed bundle signer moves the computer onto the full runtime.
204
+ if (latest.computer?.publicKey !== existing.computer.publicKey) connectCloud(latest, false);
205
+ else {
206
+ candidate.host = latest;
207
+ changed();
208
+ }
209
+ }
210
+ }
211
+ for (const computer of computers) {
212
+ if (!entries.has(computer.id) && !forgetting.has(computer.id)) connectCloud(computer, false);
213
+ }
214
+ } catch (error) {
215
+ if (active())
216
+ console.warn('Linked computer refresh deferred:', error instanceof Error ? error.name : 'unknown');
217
+ } finally {
218
+ discovering = false;
219
+ }
220
+ };
221
+ const publicKey = host.computer?.publicKey;
222
+ // A computer whose bundle signer Cloud lists runs as a paired computer does: activity, plugins and its own UI.
223
+ const runtime = publicKey
224
+ ? startLiveRuntime(
225
+ { hostId: host.id, origin: host.origin, sealed: cloudApiSend(host), openLink: cloudComputerLink(host) },
226
+ {
227
+ id: host.id,
228
+ origin: host.origin,
229
+ trustedDeviceId: `cloud:${host.person.subject}`,
230
+ signer: { publicKey, revision: 0 },
231
+ label: host.label,
232
+ ...(host.displayName === undefined ? {} : { displayName: host.displayName }),
233
+ },
234
+ () => {
235
+ if (active())
236
+ setTimeout(() => {
237
+ if (active()) connectCloud(host, false);
238
+ }, CLOUD_COMPUTER_RECONNECT_MS);
239
+ },
240
+ (owner, state) => {
241
+ if (active()) options.activity?.(host.id, owner, state);
242
+ },
243
+ {
244
+ onSummariesLoaded() {
245
+ if (!active() || entry.status === 'connected') return;
246
+ entry.status = 'connected';
247
+ entry.error = undefined;
248
+ changed();
249
+ },
250
+ onPluginCompatibility(issues) {
251
+ if (!active()) return;
252
+ entry.pluginCompatibility = issues;
253
+ changed();
254
+ },
255
+ onUpdateRequired() {
256
+ if (!active()) return;
257
+ entry.status = 'update_required';
258
+ changed();
259
+ },
260
+ },
261
+ )
262
+ : startCloudRuntime(host, {
263
+ onSummariesLoaded() {
264
+ if (!active()) return;
265
+ if (entry.status !== 'connected') {
266
+ entry.status = 'connected';
267
+ changed();
268
+ }
269
+ if (!host.computer && host.hosted && !discovering) void discoverComputers();
270
+ },
271
+ onError(message) {
272
+ if (!active() || entry.error === message) return;
273
+ entry.error = message;
274
+ if (message !== undefined && (entry.status === 'connecting' || host.computer))
275
+ entry.status = 'disconnected';
276
+ changed();
277
+ },
278
+ });
179
279
  entry.runtime = runtime;
180
280
  // Settings and other host calls reach this Po Cloud host with the person's sign-in until it stops.
181
281
  entry.controller.signal.addEventListener('abort', bindCloudApi(host.id, cloudApiSend(host)), { once: true });
182
- entry.push = startPushEnrollment(cloudPushEnrollment(host), requestPermission);
282
+ if (!host.computer) entry.push = startPushEnrollment(cloudPushEnrollment(host), requestPermission);
183
283
  runtime.open(focused !== null && splitHostId(focused)?.hostId === host.id ? focused : null);
184
284
  changed();
185
285
  return runtime;
@@ -317,6 +417,8 @@ export function createHostRuntimes(
317
417
  if (scan) throw new Error('A pairing scan is already running.');
318
418
  signal?.throwIfAborted();
319
419
  const invitation = parsePairingUrl(scanned);
420
+ if (invitation.relay)
421
+ throw new Error('Sign in to Po Cloud to use this computer. Relay links no longer pair phones.');
320
422
  const entry = [...entries.values()].find(
321
423
  (candidate): candidate is HostRuntimeEntry & { host: HostRecord } =>
322
424
  !isCloudHost(candidate.host) && candidate.host.signer.publicKey === invitation.trust.publicKey,
@@ -325,8 +427,7 @@ export function createHostRuntimes(
325
427
  const operation = { controller: new AbortController(), hostId: entry?.host.id };
326
428
  scan = operation;
327
429
  // A route switch keeps the current route running until the new one proves the same host.
328
- const switching =
329
- entry !== undefined && (entry.host.relayRoute !== undefined) !== (invitation.relay !== undefined);
430
+ const switching = entry?.host.relayRoute !== undefined;
330
431
  if (entry && !switching) {
331
432
  stopEntry(entry);
332
433
  entry.runtime = undefined;
@@ -338,16 +439,9 @@ export function createHostRuntimes(
338
439
  let transport: Pick<ReturnType<typeof createPinnedLanTransport>, 'fetch' | 'close' | 'Socket'> | undefined;
339
440
  try {
340
441
  const combined = AbortSignal.any([operation.controller.signal, ...(signal ? [signal] : [])]);
341
- transport = invitation.relay
342
- ? createRelayTransport({
343
- origin: invitation.origin,
344
- route: invitation.relay.route,
345
- capability: invitation.relay.capability,
346
- signer: invitation.trust.publicKey,
347
- })
348
- : invitation.tlsCertificateSha256
349
- ? createPinnedLanTransport(invitation.origin, invitation.tlsCertificateSha256)
350
- : undefined;
442
+ transport = invitation.tlsCertificateSha256
443
+ ? createPinnedLanTransport(invitation.origin, invitation.tlsCertificateSha256)
444
+ : undefined;
351
445
  const trusted = await rescanHost(scanned, transport?.fetch ?? nativeFetch, combined);
352
446
  if (transport) trusted.lanTransport = transport;
353
447
  committed = true;
@@ -408,10 +502,11 @@ export function createHostRuntimes(
408
502
  (entry) =>
409
503
  entry !== forgotten &&
410
504
  isCloudHost(entry.host) &&
505
+ !entry.host.computer &&
411
506
  entry.host.person.issuer === cloudHost.person.issuer &&
412
507
  entry.host.person.subject === cloudHost.person.subject,
413
508
  );
414
- if (!sameAccount)
509
+ if (!cloudHost.computer && !sameAccount)
415
510
  await withinDeadline(
416
511
  cloudPushEnrollment(cloudHost)
417
512
  .unregister()
@@ -420,13 +515,8 @@ export function createHostRuntimes(
420
515
  }),
421
516
  'Push deregistration deferred; Po Cloud keeps this phone until it signs in again.',
422
517
  );
423
- stopEntry(forgotten);
424
- entries.delete(hostId);
518
+ dropCloudEntry(forgotten);
425
519
  await removeCloudHost(hostId);
426
- applySessionsSnapshot({ sessions: [] }, hostId);
427
- applyWorkspacesSnapshot({ workspaces: [] }, hostId);
428
- if (focused !== null && splitHostId(focused)?.hostId === hostId) focused = null;
429
- changed();
430
520
  } finally {
431
521
  forgetting.delete(hostId);
432
522
  }
@@ -1,4 +1,5 @@
1
1
  import type { FederationWorkPaused } from '@agimon-ai/po-core/packageApi';
2
+ import type { ProtocolLink } from '@agimon-ai/po-core/protocolTransport';
2
3
  import {
3
4
  transcriptPageQuery,
4
5
  type TranscriptPage,
@@ -82,6 +83,17 @@ import { setNativeTemplateChoice } from './nativeTemplate';
82
83
  /** `client=native` tells the host a phone needs its native build, which it otherwise defers. */
83
84
  const COMPOSITIONS_ROUTE = '/api/compositions?client=native';
84
85
  const BUNDLED_IDS: ReadonlySet<string> = new Set(bundledPlugins.map((plugin) => plugin.id));
86
+
87
+ /**
88
+ * A computer linked to the person's Po Cloud account: HTTP and the host protocol go through Po Cloud with their
89
+ * sign-in. There are no pairing keys, so nothing here can show a Face ID step-up.
90
+ */
91
+ export interface CloudComputerSession {
92
+ hostId: string;
93
+ origin: string;
94
+ sealed: TrustedSession['sealed'];
95
+ openLink: () => Promise<ProtocolLink>;
96
+ }
85
97
  // All host runtimes share one mode source. A disconnected host must not unbind the others.
86
98
  let liveHosts = 0;
87
99
  let stopFileLinkModes: (() => void) | undefined;
@@ -239,9 +251,9 @@ function isRecord(value: unknown): value is Record<string, unknown> {
239
251
  return typeof value === 'object' && value !== null && !Array.isArray(value);
240
252
  }
241
253
 
242
- /** Wires connection, hub frames, session runtime and native compositions for one trusted session. */
254
+ /** Wires connection, hub frames, session runtime and native compositions for one trusted or Cloud-linked session. */
243
255
  export function startLiveRuntime(
244
- session: TrustedSession | Promise<TrustedSession>,
256
+ session: TrustedSession | CloudComputerSession | Promise<TrustedSession>,
245
257
  host: HostRecord,
246
258
  onReconnectNeeded: () => void,
247
259
  receiveActivityLoad: (owner: string, state: ActivityLoadState) => void = () => {},
@@ -255,6 +267,7 @@ export function startLiveRuntime(
255
267
  federationHostId?: string;
256
268
  } = {},
257
269
  ): LiveRuntime {
270
+ const cloudComputer = !(session instanceof Promise) && 'openLink' in session;
258
271
  const snapshotLease = hostSnapshots.open(host);
259
272
  const lastKnown: HostSnapshot = { sessions: [], workspaces: [] };
260
273
  const persist = () => {
@@ -368,8 +381,9 @@ export function startLiveRuntime(
368
381
  const kept = hostPluginsFor(host);
369
382
  const { updates, plugins, compositions, selectedSessions, sessionMounts, mountedWorkspaces } = kept;
370
383
 
371
- const connect = (session: TrustedSession): Connection => {
372
- if ((host.tlsCertificateSha256 || host.relayRoute) && !session.lanTransport)
384
+ const connect = (session: TrustedSession | CloudComputerSession): Connection => {
385
+ const cloud = 'openLink' in session;
386
+ if (!cloud && (host.tlsCertificateSha256 || host.relayRoute) && !session.lanTransport)
373
387
  throw new Error(
374
388
  host.relayRoute
375
389
  ? 'The relay session has no relay transport.'
@@ -377,11 +391,15 @@ export function startLiveRuntime(
377
391
  );
378
392
  return createConnection({
379
393
  hostId: host.id,
380
- http: session.http,
381
- channels: session.channels,
394
+ ...(cloud
395
+ ? { openLink: session.openLink }
396
+ : {
397
+ http: session.http,
398
+ channels: session.channels,
399
+ // React Native's WebSocket takes (url, protocols, { headers }); the DOM lib typing omits the third argument.
400
+ Socket: session.lanTransport?.Socket ?? (WebSocket as unknown as NativeSocketConstructor),
401
+ }),
382
402
  sealed: session.sealed,
383
- // React Native's WebSocket takes (url, protocols, { headers }); the DOM lib typing omits the third argument.
384
- Socket: session.lanTransport?.Socket ?? (WebSocket as unknown as NativeSocketConstructor),
385
403
  onAccess: (rights) => applySessionInteractions(rights, host.id),
386
404
  onSessions(sessions) {
387
405
  if (closed) return;
@@ -795,15 +813,11 @@ export function startLiveRuntime(
795
813
  applyFocus();
796
814
  },
797
815
  async wake(sessionId) {
798
- const response = await fetchWithStepUp(
799
- {
800
- method: 'POST',
801
- target: hostPath(sessionId, '/revive'),
802
- },
803
- undefined,
804
- undefined,
805
- host.id,
806
- );
816
+ const target = hostPath(sessionId, '/revive');
817
+ // A Cloud-linked computer has no Face ID key to confirm with; its sign-in is what admits the wake.
818
+ const response = cloudComputer
819
+ ? await request({ method: 'POST', target })
820
+ : await fetchWithStepUp({ method: 'POST', target }, undefined, undefined, host.id);
807
821
  if (response.ok) return;
808
822
  const body: unknown = await response.json().catch(() => undefined);
809
823
  throw new Error(
@@ -20,13 +20,23 @@ const MENU = (
20
20
  );
21
21
 
22
22
  /** The host drawer open over a tab: the Po menu, All hosts, each host with its waiting count, then add and manage. */
23
- function Target({ scheme = 'light', scope, menu = false }: { scheme?: DesignScheme; scope?: string; menu?: boolean }) {
23
+ function Target({
24
+ scheme = 'light',
25
+ scope,
26
+ menu = false,
27
+ hosts = HOSTS,
28
+ }: {
29
+ scheme?: DesignScheme;
30
+ scope?: string;
31
+ menu?: boolean;
32
+ hosts?: DrawerHost[];
33
+ }) {
24
34
  return (
25
35
  <PhoneFrame scheme={scheme}>
26
36
  <HostDrawer
27
37
  open
28
38
  onClose={noop}
29
- hosts={HOSTS}
39
+ hosts={hosts}
30
40
  {...(scope ? { scope } : {})}
31
41
  onScope={noop}
32
42
  onAdd={noop}
@@ -43,6 +53,13 @@ export const OneHostLight = { render: () => <Target scope="studio" /> };
43
53
  // Matches the approved target in tmp/design-evidence/native-drawer-menu-2026-11-16.
44
54
  export const MenuDark = { render: () => <Target scheme="dark" menu /> };
45
55
  export const MenuLight = { render: () => <Target menu /> };
56
+ const linked = [
57
+ { id: 'cloud', label: 'Po Cloud', address: 'cloud.example.com', online: true, waiting: 0 },
58
+ { ...HOSTS[0]!, address: 'cloud.example.com' },
59
+ { ...HOSTS[1]!, address: 'cloud.example.com', online: false, waiting: 0 },
60
+ ];
61
+ export const LinkedComputersLight = { render: () => <Target hosts={linked} menu /> };
62
+ export const LinkedComputersDark = { render: () => <Target hosts={linked} scheme="dark" menu /> };
46
63
  export const hostDrawerMeta = {
47
64
  title: 'Native/Design/Host drawer',
48
65
  tags: ['style-system', 'mockup', 'native'],
@@ -1,10 +1,11 @@
1
1
  import { PoNativeProvider } from '@agimon-ai/po-native-components';
2
2
 
3
+ import { PhoneFrame, type DesignScheme } from './designFrame';
3
4
  import { PairingScreen } from './PairingScreen';
4
5
 
5
6
  const noop = () => {};
6
7
 
7
- const meta = {
8
+ export const meta = {
8
9
  title: 'Native/Screens/Pairing',
9
10
  component: PairingScreen,
10
11
  tags: ['style-system', 'mockup', 'native'],
@@ -32,3 +33,17 @@ export const BiometricsMissing = {
32
33
  </PoNativeProvider>
33
34
  ),
34
35
  };
36
+
37
+ function RelayLinkStory({ scheme }: { scheme: DesignScheme }) {
38
+ return (
39
+ <PhoneFrame scheme={scheme}>
40
+ <PairingScreen
41
+ onPair={noop}
42
+ cameraEnabled={false}
43
+ error="Sign in to Po Cloud to use this computer. Relay links no longer pair phones."
44
+ />
45
+ </PhoneFrame>
46
+ );
47
+ }
48
+ export const RelayLinkLight = { render: () => <RelayLinkStory scheme="light" /> };
49
+ export const RelayLinkDark = { render: () => <RelayLinkStory scheme="dark" /> };
@@ -4,7 +4,7 @@ import { useCallback, useEffect, useState } from 'react';
4
4
  import { Alert, ScrollView, Text } from 'react-native';
5
5
  import { StyleSheet } from 'react-native-unistyles';
6
6
 
7
- import { disableRemote, readRemote, revokeTrustedDevice } from '../services/settingsApi';
7
+ import { disableRemote, NO_REMOTE_ACCESS, readRemote, revokeTrustedDevice } from '../services/settingsApi';
8
8
  import { ErrorLine, Group, OnComputer, remoteSummary, Row } from './SettingsScreen';
9
9
 
10
10
  /*
@@ -88,7 +88,11 @@ export function RemoteControlScreen({ remote, error, busy, turnOff, revokeDevice
88
88
  <Text style={styles.lede}>
89
89
  Reach this Po from your phone or another computer. Turning access on and pairing happen on your computer.
90
90
  </Text>
91
- <ErrorLine>{error}</ErrorLine>
91
+ {error === NO_REMOTE_ACCESS ? (
92
+ <OnComputer>Remote access and trusted devices change on that computer only.</OnComputer>
93
+ ) : (
94
+ <ErrorLine>{error}</ErrorLine>
95
+ )}
92
96
  {remote && summary ? (
93
97
  <>
94
98
  <Group label="Remote access">
@@ -144,10 +144,10 @@ export function settingsTransportForHost(hostId: string): ApiTransport {
144
144
  input === '/api/remote' || input.startsWith('/api/remote/') ? shell(input, init) : scoped(input, init);
145
145
  }
146
146
 
147
- /** Native plugins may name a connected host. Unknown hosts never fall back to another session. */
147
+ /** Native plugins may name a connected host: paired, or reached through Po Cloud. Unknown hosts never fall back to another session. */
148
148
  export function transportForHost(hostId: string): ApiTransport {
149
149
  return async (input, init) => {
150
- if (!currentSession(hostId)) throw new Error('This host is unavailable.');
150
+ if (!currentSession(hostId) && !cloudApis.has(hostId)) throw new Error('This host is unavailable.');
151
151
  const request = apiTransportForHost(hostId);
152
152
  const workspace = /^\/api\/network\/workspaces\/([^/?]+)\/calendar\//u.exec(input)?.[1];
153
153
  if (!workspace) return request(input, init);
@@ -8,6 +8,8 @@ const OPTIONS: SecureStore.SecureStoreOptions = { keychainAccessible: SecureStor
8
8
  const UUID = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/u;
9
9
  const ORG_ID = /^[a-zA-Z0-9_-]{1,128}$/u;
10
10
  const API_PREFIX = /^\/[a-z0-9-]+(?:\/[a-z0-9-]+)*$/u;
11
+ const RELAY_HOST_ID = /^relay-[a-zA-Z0-9_-]{43}$/u;
12
+ const PUBLIC_KEY = /^[A-Za-z0-9_-]{1,512}$/u;
11
13
 
12
14
  /** A Po Cloud org reached with the person's identity session cookie, not a QR pairing. */
13
15
  export interface CloudHostRecord {
@@ -24,6 +26,11 @@ export interface CloudHostRecord {
24
26
  workspaceId?: string;
25
27
  /** Hosted Po Cloud: signed in with its own email-code session, its cloud API under this path of `origin`. */
26
28
  hosted?: { apiPrefix: string };
29
+ /**
30
+ * A distinct computer discovered through the hosted account, never a paired host. Its bundle signer, when Cloud
31
+ * lists one, lets the phone check that computer's plugins and run it as it runs a paired computer.
32
+ */
33
+ computer?: { hostId: string; generation: number; publicKey?: string };
27
34
  }
28
35
 
29
36
  export function isCloudHost(host: object): host is CloudHostRecord {
@@ -48,6 +55,17 @@ function httpsOrigin(value: unknown): value is string {
48
55
  }
49
56
  }
50
57
 
58
+ function computerOf(value: unknown): CloudHostRecord['computer'] {
59
+ if (!isRecord(value) || typeof value.hostId !== 'string' || !RELAY_HOST_ID.test(value.hostId)) return undefined;
60
+ const generation = value.generation;
61
+ if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 1) return undefined;
62
+ return {
63
+ hostId: value.hostId,
64
+ generation,
65
+ ...(typeof value.publicKey === 'string' && PUBLIC_KEY.test(value.publicKey) ? { publicKey: value.publicKey } : {}),
66
+ };
67
+ }
68
+
51
69
  function cloudHostOf(value: unknown): CloudHostRecord | undefined {
52
70
  if (
53
71
  !isRecord(value) ||
@@ -64,6 +82,15 @@ function cloudHostOf(value: unknown): CloudHostRecord | undefined {
64
82
  !value.person.subject
65
83
  )
66
84
  return undefined;
85
+ const computer = computerOf(value.computer);
86
+ if (
87
+ value.computer !== undefined &&
88
+ (!computer ||
89
+ !isRecord(value.hosted) ||
90
+ value.hosted.apiPrefix !== '/hosts/cloud' ||
91
+ value.origin !== value.person.issuer)
92
+ )
93
+ return undefined;
67
94
  return {
68
95
  kind: 'cloud',
69
96
  id: value.id,
@@ -83,6 +110,7 @@ function cloudHostOf(value: unknown): CloudHostRecord | undefined {
83
110
  ...(isRecord(value.hosted) && typeof value.hosted.apiPrefix === 'string' && API_PREFIX.test(value.hosted.apiPrefix)
84
111
  ? { hosted: { apiPrefix: value.hosted.apiPrefix } }
85
112
  : {}),
113
+ ...(computer ? { computer } : {}),
86
114
  };
87
115
  }
88
116
 
@@ -119,10 +147,7 @@ export function ensureCloudHost(input: {
119
147
  hosted?: { apiPrefix: string };
120
148
  }): Promise<CloudHostRecord> {
121
149
  return serialize(async () => {
122
- const same = (host: CloudHostRecord) =>
123
- host.networkId === input.networkId &&
124
- host.person.issuer === input.person.issuer &&
125
- host.person.subject === input.person.subject;
150
+ const same = (host: CloudHostRecord) => host.computer === undefined && sameCloudAccount(host, input);
126
151
  const all = await read();
127
152
  // A record from before hosted sign-in reaches the wrong API path; it gives way to the hosted one.
128
153
  const hosts = all.filter((host) => !same(host) || host.hosted?.apiPrefix === input.hosted?.apiPrefix);
@@ -158,6 +183,58 @@ export function ensureCloudHost(input: {
158
183
  });
159
184
  }
160
185
 
186
+ function sameCloudAccount(
187
+ a: Pick<CloudHostRecord, 'person' | 'networkId'>,
188
+ b: Pick<CloudHostRecord, 'person' | 'networkId'>,
189
+ ) {
190
+ return a.networkId === b.networkId && a.person.issuer === b.person.issuer && a.person.subject === b.person.subject;
191
+ }
192
+
193
+ /** Apply only a complete, authenticated listing. Never alter the Cloud service or QR-paired hosts. */
194
+ export function syncCloudComputers(cloud: CloudHostRecord, listing: unknown): Promise<CloudHostRecord[]> {
195
+ return serialize(async () => {
196
+ if (
197
+ cloud.computer ||
198
+ cloud.hosted?.apiPrefix !== '/hosts/cloud' ||
199
+ !isRecord(listing) ||
200
+ !Array.isArray(listing.computers)
201
+ )
202
+ throw new Error('Invalid linked computer list.');
203
+ const all = await read();
204
+ if (!all.some((host) => host.id === cloud.id && host.computer === undefined && sameCloudAccount(host, cloud)))
205
+ return [];
206
+ const scope = (host: CloudHostRecord) => host.computer !== undefined && sameCloudAccount(host, cloud);
207
+ const previous = all.filter(scope);
208
+ const seen = new Set<string>();
209
+ const records = listing.computers.map((item: unknown) => {
210
+ const computer = computerOf(item);
211
+ if (
212
+ !computer ||
213
+ seen.has(computer.hostId) ||
214
+ !isRecord(item) ||
215
+ typeof item.label !== 'string' ||
216
+ !validDisplayName(item.label)
217
+ )
218
+ throw new Error('Invalid linked computer.');
219
+ seen.add(computer.hostId);
220
+ const existing = previous.find((host) => host.computer?.hostId === computer.hostId);
221
+ return {
222
+ kind: 'cloud' as const,
223
+ id: existing?.id ?? crypto.randomUUID(),
224
+ origin: cloud.origin,
225
+ label: item.label,
226
+ ...(existing?.displayName ? { displayName: existing.displayName } : {}),
227
+ person: cloud.person,
228
+ networkId: cloud.networkId,
229
+ hosted: cloud.hosted,
230
+ computer,
231
+ };
232
+ });
233
+ if (JSON.stringify(records) !== JSON.stringify(previous))
234
+ await write([...all.filter((host) => !scope(host)), ...records]);
235
+ return records;
236
+ });
237
+ }
161
238
  export function renameCloudHost(id: string, displayName: string): Promise<CloudHostRecord> {
162
239
  if (!validDisplayName(displayName))
163
240
  return Promise.reject(new Error('Use a name of 1 to 64 characters without control characters.'));
@@ -1,4 +1,4 @@
1
- import { createProtocolClient, type ProtocolClient } from '@agimon-ai/po-core/protocolTransport';
1
+ import { createProtocolClient, type ProtocolClient, type ProtocolLink } from '@agimon-ai/po-core/protocolTransport';
2
2
  import {
3
3
  bindTransport,
4
4
  bindHostTransport,
@@ -20,19 +20,22 @@ const TELEMETRY_ROUTE = '/api/telemetry/browser';
20
20
  /** One sealed channel per transport, established by pairing or device authentication. */
21
21
  export type ConnectionChannels = Record<'session' | 'protocol' | 'http', SealedTransport>;
22
22
 
23
- export interface ConnectionOptions extends Omit<SessionSocketHandlers, 'onOpen' | 'onClose'> {
24
- hostId?: string;
25
- http: RemoteHttp;
26
- channels: ConnectionChannels;
27
- /** The trusted session owns the single exchange queue for its HTTP channel. */
28
- sealed: ReturnType<typeof createSealedHttp>;
29
- Socket: NativeSocketConstructor;
30
- /**
31
- * Called when an open hub connection drops, so the shell can re-authenticate and rebuild channels.
32
- * Not called once the server needs a newer app: reconnecting cannot help, `onUpdateRequired` is heard instead.
33
- */
34
- onReconnectNeeded(): void;
35
- }
23
+ /** A paired computer's sealed channels, or a link a Po Cloud sign-in already opened to a linked computer. */
24
+ type ProtocolSource =
25
+ | { http: RemoteHttp; channels: ConnectionChannels; Socket: NativeSocketConstructor; openLink?: undefined }
26
+ | { openLink: () => Promise<ProtocolLink>; http?: undefined; channels?: undefined; Socket?: undefined };
27
+
28
+ export type ConnectionOptions = Omit<SessionSocketHandlers, 'onOpen' | 'onClose'> &
29
+ ProtocolSource & {
30
+ hostId?: string;
31
+ /** The trusted session owns the single exchange queue for its HTTP channel. */
32
+ sealed: ReturnType<typeof createSealedHttp>;
33
+ /**
34
+ * Called when an open hub connection drops, so the shell can re-authenticate and rebuild channels.
35
+ * Not called once the server needs a newer app: reconnecting cannot help, `onUpdateRequired` is heard instead.
36
+ */
37
+ onReconnectNeeded(): void;
38
+ };
36
39
 
37
40
  export interface Connection {
38
41
  readonly client: ProtocolClient;
@@ -44,10 +47,13 @@ export interface Connection {
44
47
 
45
48
  /** Wires the protocol client, hub socket and dashboard transport over already-established channels. */
46
49
  export function createConnection(options: ConnectionOptions): Connection {
47
- const { http, channels, sealed: request } = options;
50
+ const { sealed: request } = options;
48
51
  const client = createProtocolClient({
49
52
  name: 'native',
50
- openLink: createNativeProtocolLink(http, channels.protocol, options.Socket, undefined, request),
53
+ openLink:
54
+ options.openLink !== undefined
55
+ ? options.openLink
56
+ : createNativeProtocolLink(options.http, options.channels.protocol, options.Socket, undefined, request),
51
57
  });
52
58
  let opened = false;
53
59
  let closed = false;
@@ -9,6 +9,7 @@ import {
9
9
  type PinnedLanTransport,
10
10
  } from '../../../modules/po-lan-tls';
11
11
  import { createRemoteHttp, createSealedHttp, type RemoteHttp, type SealedHttpRequest } from '../../adapters/remoteHttp';
12
+ import { isCloudHost } from '../cloudHosts';
12
13
  import { hostSnapshots } from '../hostSnapshots';
13
14
  import { type Channels, establishChannels, pairDevice, parsePairingUrl } from '../pairing';
14
15
  import { isRelayTrustError, PRIVATE_RELAY_CAPABILITY, PRIVATE_RELAY_ROUTE } from '../relayTransport/route';
@@ -305,9 +306,9 @@ export function validHostDisplayName(value: string): boolean {
305
306
  return value === value.trim() && value.length >= 1 && value.length <= 64 && !/[\p{Cc}\p{Cf}]/u.test(value);
306
307
  }
307
308
 
308
- /** Also names Po Cloud hosts, which carry the same origin and optional name. */
309
+ /** Also names Po Cloud hosts: they share the Cloud origin, so each falls back to its own label instead. */
309
310
  export function hostDisplayName(host: Pick<HostRecord, 'displayName' | 'origin'>): string {
310
- return host.displayName ?? new URL(host.origin).hostname;
311
+ return host.displayName ?? (isCloudHost(host) ? host.label : new URL(host.origin).hostname);
311
312
  }
312
313
 
313
314
  /** Renames the computer, never the phone label sent during registration. */
@@ -152,6 +152,9 @@ function sessionSummary(value: unknown): SessionSummary {
152
152
  createdAt: text(record, 'createdAt'),
153
153
  updatedAt: text(record, 'updatedAt'),
154
154
  ...(typeof record.workspaceId === 'string' ? { workspaceId: record.workspaceId } : {}),
155
+ ...(typeof record.parentSessionId === 'string' ? { parentSessionId: record.parentSessionId } : {}),
156
+ ...(typeof record.sessionProvenance === 'string' ? { sessionProvenance: record.sessionProvenance } : {}),
157
+ ...(record.dormant === true ? { dormant: true } : {}),
155
158
  phase: 'idle',
156
159
  phaseSince: '',
157
160
  attach: 'closed',
@@ -81,6 +81,8 @@ async function request<T>(
81
81
  if (picked !== undefined) return picked;
82
82
  }
83
83
  if (missing !== undefined && (response.status === 404 || (response.ok && !isRecord(body)))) return { error: missing };
84
+ // A computer reached through Po Cloud keeps its remote access to itself: the same quiet answer, not a failure.
85
+ if (missing === NO_REMOTE_ACCESS && response.status === 403) return { error: missing };
84
86
  if (response.status === 0) return { error: UNANSWERED };
85
87
  return {
86
88
  error: isRecord(body) && typeof body.error === 'string' ? body.error : `Po answered ${String(response.status)}.`,
@@ -158,7 +160,7 @@ export function logoutProvider(providerId: string, hostId?: string): Promise<Res
158
160
  return request(`${AUTH_PROVIDERS_API_ROUTE}/${encodeURIComponent(providerId)}`, { method: 'DELETE' }, ok, hostId);
159
161
  }
160
162
 
161
- /** What `readRemote` answers for a host with no remote access of its own, such as Po Cloud. Not a failure. */
163
+ /** What `readRemote` answers for a host with no remote access this phone may read, such as Po Cloud or a computer reached through it. Not a failure. */
162
164
  export const NO_REMOTE_ACCESS = 'This host has no remote access settings.';
163
165
 
164
166
  export function readRemote(hostId?: string): Promise<Result<{ state: RemoteAccessStateView }>> {