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

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.57",
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.177",
33
+ "@agimon-ai/po-expo-signing": "0.0.1-alpha.57",
34
+ "@agimon-ai/po-identity": "0.0.2-alpha.124",
35
+ "@agimon-ai/po-native-components": "0.0.0-alpha.177",
36
+ "@agimon-ai/po-native-dashboard": "0.0.0-alpha.49",
37
+ "@agimon-ai/po-template-advanced": "0.0.0-alpha.177",
38
+ "@agimon-ai/po-template-elegant": "0.0.0-alpha.177",
39
+ "@agimon-ai/po-voice": "0.0.0-alpha.177",
40
+ "@agimon-ai/po-web-components": "0.0.0-alpha.177",
41
+ "@agimon-ai/po-web-dashboard": "0.0.0-alpha.177",
42
+ "@agimon-ai/po-web-security": "0.0.0-alpha.177",
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
@@ -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'));
@@ -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. */
@@ -84,7 +95,10 @@ export function cloudFetch(host: CloudHostRecord, options: Pick<CloudRuntimeOpti
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();
@@ -104,6 +118,24 @@ export function cloudFetch(host: CloudHostRecord, options: Pick<CloudRuntimeOpti
104
118
  };
105
119
  }
106
120
 
121
+ /** Discover only after the hosted account has been admitted. A failed read never forgets saved computers. */
122
+ export async function refreshCloudComputers(
123
+ cloud: CloudHostRecord,
124
+ options: Pick<CloudRuntimeOptions, 'cookie' | 'fetch'> = {},
125
+ signal?: AbortSignal,
126
+ ): Promise<CloudHostRecord[] | undefined> {
127
+ if (!cloud.hosted || cloud.computer) return undefined;
128
+ const response = await cloudFetch(cloud, options)(`${cloud.origin}/api/owner/relay-computers`, {
129
+ headers: { 'x-po-relay-subject': encodeURIComponent(cloud.person.subject) },
130
+ ...(signal ? { signal } : {}),
131
+ });
132
+ if (response.status === 404) return undefined; // Older or relay-disabled Cloud deployment.
133
+ if (!response.ok) throw new Error(`Could not list linked computers (${response.status}).`);
134
+ const listing: unknown = await response.json();
135
+ if (signal?.aborted) return undefined;
136
+ return syncCloudComputers(cloud, listing);
137
+ }
138
+
107
139
  /**
108
140
  * One Po API call to this cloud host, in the shape the paired-computer transport sends. Po Cloud answers
109
141
  * the same `/api` routes under its prefix, so Settings reads it the way it reads a computer.
@@ -313,17 +345,19 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
313
345
  | { sessionId: string; runtime: SessionRuntime; sockets: Set<CloudSocket>; stopAccess(): void }
314
346
  | undefined;
315
347
  let closed = false;
348
+ let online = host.computer === undefined;
316
349
 
317
350
  const openLink = async (sessionId: string, sockets: Set<CloudSocket>, reauthenticate: () => void): Promise<Link> => {
318
351
  const workspaceId = sessionsStore.state.byId[sessionId]?.summary.workspaceId;
319
352
  if (!workspaceId) throw new Error('This Po Cloud session has no workspace yet.');
320
353
  const cookie = await readCookie();
354
+ if (closed || !online || binding?.sockets !== sockets) throw new Error('The session connection was replaced.');
321
355
  if (!cookie) throw new Error(SIGNED_OUT);
322
356
  const path = `/api/workspaces/${encodeURIComponent(localHostId(host.id, workspaceId))}/sessions/${encodeURIComponent(localHostId(host.id, sessionId))}/ws`;
323
357
  const url = new URL(`${cloudBase(host).replace(/^https:/u, 'wss:')}${path}`);
324
358
  url.searchParams.set('poClient', encodePoClientMetadata(currentClientMetadata()));
325
359
  const socket = new Socket(url.toString(), null, {
326
- headers: cloudHeaders(host, cookie),
360
+ headers: { ...cloudHeaders(host, cookie), ...(host.computer ? { origin: HOSTED_WRITE_HEADERS.origin } : {}) },
327
361
  });
328
362
  socket.binaryType = 'arraybuffer';
329
363
  sockets.add(socket);
@@ -386,9 +420,11 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
386
420
  onSnapshot({ workspaces, sessions }) {
387
421
  if (closed) return;
388
422
  // 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);
423
+ if (!host.computer)
424
+ void refreshClientDeviceName(() =>
425
+ cloudFetch(host, { cookie: readCookie, fetch: options.fetch })(`${cloudBase(host)}/api/client-devices`),
426
+ ).catch(() => undefined);
427
+ online = true;
392
428
  applySessionsSnapshot({ sessions }, host.id);
393
429
  applyWorkspacesSnapshot({ workspaces }, host.id);
394
430
  home.setSupported(false);
@@ -398,7 +434,12 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
398
434
  else if (focused !== null && binding === undefined) bind(focused);
399
435
  },
400
436
  onError(error) {
401
- if (!closed) options.onError?.(error.message);
437
+ if (closed) return;
438
+ if (host.computer) {
439
+ online = false;
440
+ stopBinding();
441
+ }
442
+ options.onError?.(error.message);
402
443
  },
403
444
  });
404
445
 
@@ -420,12 +461,12 @@ export function startCloudRuntime(host: CloudHostRecord, options: CloudRuntimeOp
420
461
  }
421
462
  setActiveSession(next);
422
463
  // Before the first list the session's workspace is unknown; the snapshot binds it.
423
- if (sessionsStore.state.byId[next]?.summary.workspaceId) bind(next);
464
+ if (online && sessionsStore.state.byId[next]?.summary.workspaceId) bind(next);
424
465
  else stopBinding();
425
466
  },
426
467
  /** A cloud session boots when its socket opens, so waking reconnects the focused one. */
427
468
  async wake(sessionId) {
428
- if (!closed && sessionId === focused) bind(sessionId);
469
+ if (!closed && online && sessionId === focused) bind(sessionId);
429
470
  },
430
471
  async searchFiles() {
431
472
  return [];
@@ -33,7 +33,7 @@ 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 { cloudApiSend, cloudPushEnrollment, refreshCloudComputers, startCloudRuntime } from './cloudRuntime';
37
37
  import { type ActivityLoadState, type LiveRuntime, startLiveRuntime } from './liveRuntime';
38
38
  import { activateNativeTemplateHost, resetNativeTemplateChoice } from './nativeTemplate';
39
39
 
@@ -156,30 +156,76 @@ export function createHostRuntimes(
156
156
  entry.lanTransport = undefined;
157
157
  };
158
158
 
159
- /** Cloud hosts poll and focus over cookie admission, and enroll push with the person's account. */
159
+ const dropCloudEntry = (entry: HostRuntimeEntry) => {
160
+ const { id } = entry.host;
161
+ stopEntry(entry);
162
+ entries.delete(id);
163
+ applySessionsSnapshot({ sessions: [] }, id);
164
+ applyWorkspacesSnapshot({ workspaces: [] }, id);
165
+ if (focused !== null && splitHostId(focused)?.hostId === id) focused = null;
166
+ changed();
167
+ };
168
+
169
+ /** Cloud hosts poll and focus over cookie admission. Only the Cloud service enrolls push. */
160
170
  const connectCloud = (host: CloudHostRecord, requestPermission: boolean): LiveRuntime => {
161
171
  const previous = entries.get(host.id);
162
172
  if (previous) stopEntry(previous);
163
173
  const entry: HostRuntimeEntry = { host, status: 'connecting', controller: new AbortController() };
164
174
  entries.set(host.id, entry);
165
175
  const active = () => !closed && entries.get(host.id) === entry && !forgetting.has(host.id);
176
+ let discovering = false;
177
+ const discoverComputers = async () => {
178
+ discovering = true;
179
+ try {
180
+ const computers = await refreshCloudComputers(host, {}, entry.controller.signal);
181
+ if (!active() || !computers) return;
182
+ for (const candidate of entries.values()) {
183
+ const existing = candidate.host;
184
+ if (
185
+ !isCloudHost(existing) ||
186
+ !existing.computer ||
187
+ existing.networkId !== host.networkId ||
188
+ existing.person.issuer !== host.person.issuer ||
189
+ existing.person.subject !== host.person.subject
190
+ )
191
+ continue;
192
+ const latest = computers.find(({ id }) => id === existing.id);
193
+ if (!latest || latest.computer?.generation !== existing.computer.generation) dropCloudEntry(candidate);
194
+ else if (latest.label !== existing.label) {
195
+ candidate.host = latest;
196
+ changed();
197
+ }
198
+ }
199
+ for (const computer of computers) {
200
+ if (!entries.has(computer.id) && !forgetting.has(computer.id)) connectCloud(computer, false);
201
+ }
202
+ } catch (error) {
203
+ if (active())
204
+ console.warn('Linked computer refresh deferred:', error instanceof Error ? error.name : 'unknown');
205
+ } finally {
206
+ discovering = false;
207
+ }
208
+ };
166
209
  const runtime = startCloudRuntime(host, {
167
210
  onSummariesLoaded() {
168
- if (!active() || entry.status === 'connected') return;
169
- entry.status = 'connected';
170
- changed();
211
+ if (!active()) return;
212
+ if (entry.status !== 'connected') {
213
+ entry.status = 'connected';
214
+ changed();
215
+ }
216
+ if (!host.computer && host.hosted && !discovering) void discoverComputers();
171
217
  },
172
218
  onError(message) {
173
219
  if (!active() || entry.error === message) return;
174
220
  entry.error = message;
175
- if (message !== undefined && entry.status === 'connecting') entry.status = 'disconnected';
221
+ if (message !== undefined && (entry.status === 'connecting' || host.computer)) entry.status = 'disconnected';
176
222
  changed();
177
223
  },
178
224
  });
179
225
  entry.runtime = runtime;
180
226
  // Settings and other host calls reach this Po Cloud host with the person's sign-in until it stops.
181
227
  entry.controller.signal.addEventListener('abort', bindCloudApi(host.id, cloudApiSend(host)), { once: true });
182
- entry.push = startPushEnrollment(cloudPushEnrollment(host), requestPermission);
228
+ if (!host.computer) entry.push = startPushEnrollment(cloudPushEnrollment(host), requestPermission);
183
229
  runtime.open(focused !== null && splitHostId(focused)?.hostId === host.id ? focused : null);
184
230
  changed();
185
231
  return runtime;
@@ -317,6 +363,8 @@ export function createHostRuntimes(
317
363
  if (scan) throw new Error('A pairing scan is already running.');
318
364
  signal?.throwIfAborted();
319
365
  const invitation = parsePairingUrl(scanned);
366
+ if (invitation.relay)
367
+ throw new Error('Sign in to Po Cloud to use this computer. Relay links no longer pair phones.');
320
368
  const entry = [...entries.values()].find(
321
369
  (candidate): candidate is HostRuntimeEntry & { host: HostRecord } =>
322
370
  !isCloudHost(candidate.host) && candidate.host.signer.publicKey === invitation.trust.publicKey,
@@ -325,8 +373,7 @@ export function createHostRuntimes(
325
373
  const operation = { controller: new AbortController(), hostId: entry?.host.id };
326
374
  scan = operation;
327
375
  // 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);
376
+ const switching = entry?.host.relayRoute !== undefined;
330
377
  if (entry && !switching) {
331
378
  stopEntry(entry);
332
379
  entry.runtime = undefined;
@@ -338,16 +385,9 @@ export function createHostRuntimes(
338
385
  let transport: Pick<ReturnType<typeof createPinnedLanTransport>, 'fetch' | 'close' | 'Socket'> | undefined;
339
386
  try {
340
387
  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;
388
+ transport = invitation.tlsCertificateSha256
389
+ ? createPinnedLanTransport(invitation.origin, invitation.tlsCertificateSha256)
390
+ : undefined;
351
391
  const trusted = await rescanHost(scanned, transport?.fetch ?? nativeFetch, combined);
352
392
  if (transport) trusted.lanTransport = transport;
353
393
  committed = true;
@@ -408,10 +448,11 @@ export function createHostRuntimes(
408
448
  (entry) =>
409
449
  entry !== forgotten &&
410
450
  isCloudHost(entry.host) &&
451
+ !entry.host.computer &&
411
452
  entry.host.person.issuer === cloudHost.person.issuer &&
412
453
  entry.host.person.subject === cloudHost.person.subject,
413
454
  );
414
- if (!sameAccount)
455
+ if (!cloudHost.computer && !sameAccount)
415
456
  await withinDeadline(
416
457
  cloudPushEnrollment(cloudHost)
417
458
  .unregister()
@@ -420,13 +461,8 @@ export function createHostRuntimes(
420
461
  }),
421
462
  'Push deregistration deferred; Po Cloud keeps this phone until it signs in again.',
422
463
  );
423
- stopEntry(forgotten);
424
- entries.delete(hostId);
464
+ dropCloudEntry(forgotten);
425
465
  await removeCloudHost(hostId);
426
- applySessionsSnapshot({ sessions: [] }, hostId);
427
- applyWorkspacesSnapshot({ workspaces: [] }, hostId);
428
- if (focused !== null && splitHostId(focused)?.hostId === hostId) focused = null;
429
- changed();
430
466
  } finally {
431
467
  forgetting.delete(hostId);
432
468
  }
@@ -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" /> };
@@ -8,6 +8,7 @@ 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;
11
12
 
12
13
  /** A Po Cloud org reached with the person's identity session cookie, not a QR pairing. */
13
14
  export interface CloudHostRecord {
@@ -24,6 +25,8 @@ export interface CloudHostRecord {
24
25
  workspaceId?: string;
25
26
  /** Hosted Po Cloud: signed in with its own email-code session, its cloud API under this path of `origin`. */
26
27
  hosted?: { apiPrefix: string };
28
+ /** A distinct computer discovered through the hosted account, never a paired host. */
29
+ computer?: { hostId: string; generation: number };
27
30
  }
28
31
 
29
32
  export function isCloudHost(host: object): host is CloudHostRecord {
@@ -48,6 +51,13 @@ function httpsOrigin(value: unknown): value is string {
48
51
  }
49
52
  }
50
53
 
54
+ function computerOf(value: unknown): CloudHostRecord['computer'] {
55
+ if (!isRecord(value) || typeof value.hostId !== 'string' || !RELAY_HOST_ID.test(value.hostId)) return undefined;
56
+ const generation = value.generation;
57
+ if (typeof generation !== 'number' || !Number.isSafeInteger(generation) || generation < 1) return undefined;
58
+ return { hostId: value.hostId, generation };
59
+ }
60
+
51
61
  function cloudHostOf(value: unknown): CloudHostRecord | undefined {
52
62
  if (
53
63
  !isRecord(value) ||
@@ -64,6 +74,15 @@ function cloudHostOf(value: unknown): CloudHostRecord | undefined {
64
74
  !value.person.subject
65
75
  )
66
76
  return undefined;
77
+ const computer = computerOf(value.computer);
78
+ if (
79
+ value.computer !== undefined &&
80
+ (!computer ||
81
+ !isRecord(value.hosted) ||
82
+ value.hosted.apiPrefix !== '/hosts/cloud' ||
83
+ value.origin !== value.person.issuer)
84
+ )
85
+ return undefined;
67
86
  return {
68
87
  kind: 'cloud',
69
88
  id: value.id,
@@ -83,6 +102,7 @@ function cloudHostOf(value: unknown): CloudHostRecord | undefined {
83
102
  ...(isRecord(value.hosted) && typeof value.hosted.apiPrefix === 'string' && API_PREFIX.test(value.hosted.apiPrefix)
84
103
  ? { hosted: { apiPrefix: value.hosted.apiPrefix } }
85
104
  : {}),
105
+ ...(computer ? { computer } : {}),
86
106
  };
87
107
  }
88
108
 
@@ -119,10 +139,7 @@ export function ensureCloudHost(input: {
119
139
  hosted?: { apiPrefix: string };
120
140
  }): Promise<CloudHostRecord> {
121
141
  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;
142
+ const same = (host: CloudHostRecord) => host.computer === undefined && sameCloudAccount(host, input);
126
143
  const all = await read();
127
144
  // A record from before hosted sign-in reaches the wrong API path; it gives way to the hosted one.
128
145
  const hosts = all.filter((host) => !same(host) || host.hosted?.apiPrefix === input.hosted?.apiPrefix);
@@ -158,6 +175,58 @@ export function ensureCloudHost(input: {
158
175
  });
159
176
  }
160
177
 
178
+ function sameCloudAccount(
179
+ a: Pick<CloudHostRecord, 'person' | 'networkId'>,
180
+ b: Pick<CloudHostRecord, 'person' | 'networkId'>,
181
+ ) {
182
+ return a.networkId === b.networkId && a.person.issuer === b.person.issuer && a.person.subject === b.person.subject;
183
+ }
184
+
185
+ /** Apply only a complete, authenticated listing. Never alter the Cloud service or QR-paired hosts. */
186
+ export function syncCloudComputers(cloud: CloudHostRecord, listing: unknown): Promise<CloudHostRecord[]> {
187
+ return serialize(async () => {
188
+ if (
189
+ cloud.computer ||
190
+ cloud.hosted?.apiPrefix !== '/hosts/cloud' ||
191
+ !isRecord(listing) ||
192
+ !Array.isArray(listing.computers)
193
+ )
194
+ throw new Error('Invalid linked computer list.');
195
+ const all = await read();
196
+ if (!all.some((host) => host.id === cloud.id && host.computer === undefined && sameCloudAccount(host, cloud)))
197
+ return [];
198
+ const scope = (host: CloudHostRecord) => host.computer !== undefined && sameCloudAccount(host, cloud);
199
+ const previous = all.filter(scope);
200
+ const seen = new Set<string>();
201
+ const records = listing.computers.map((item: unknown) => {
202
+ const computer = computerOf(item);
203
+ if (
204
+ !computer ||
205
+ seen.has(computer.hostId) ||
206
+ !isRecord(item) ||
207
+ typeof item.label !== 'string' ||
208
+ !validDisplayName(item.label)
209
+ )
210
+ throw new Error('Invalid linked computer.');
211
+ seen.add(computer.hostId);
212
+ const existing = previous.find((host) => host.computer?.hostId === computer.hostId);
213
+ return {
214
+ kind: 'cloud' as const,
215
+ id: existing?.id ?? crypto.randomUUID(),
216
+ origin: cloud.origin,
217
+ label: item.label,
218
+ ...(existing?.displayName ? { displayName: existing.displayName } : {}),
219
+ person: cloud.person,
220
+ networkId: cloud.networkId,
221
+ hosted: cloud.hosted,
222
+ computer,
223
+ };
224
+ });
225
+ if (JSON.stringify(records) !== JSON.stringify(previous))
226
+ await write([...all.filter((host) => !scope(host)), ...records]);
227
+ return records;
228
+ });
229
+ }
161
230
  export function renameCloudHost(id: string, displayName: string): Promise<CloudHostRecord> {
162
231
  if (!validDisplayName(displayName))
163
232
  return Promise.reject(new Error('Use a name of 1 to 64 characters without control characters.'));
@@ -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',