@agimon-ai/po-native 0.0.1-alpha.25 → 0.0.1-alpha.26

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.25",
3
+ "version": "0.0.1-alpha.26",
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.145",
33
- "@agimon-ai/po-expo-signing": "0.0.1-alpha.25",
34
- "@agimon-ai/po-identity": "0.0.2-alpha.92",
35
- "@agimon-ai/po-native-components": "0.0.0-alpha.145",
36
- "@agimon-ai/po-native-dashboard": "0.0.0-alpha.17",
37
- "@agimon-ai/po-template-advanced": "0.0.0-alpha.145",
38
- "@agimon-ai/po-template-elegant": "0.0.0-alpha.145",
39
- "@agimon-ai/po-voice": "0.0.0-alpha.145",
40
- "@agimon-ai/po-web-components": "0.0.0-alpha.145",
41
- "@agimon-ai/po-web-dashboard": "0.0.0-alpha.145",
42
- "@agimon-ai/po-web-security": "0.0.0-alpha.145",
32
+ "@agimon-ai/po-core": "0.0.0-alpha.146",
33
+ "@agimon-ai/po-expo-signing": "0.0.1-alpha.26",
34
+ "@agimon-ai/po-identity": "0.0.2-alpha.93",
35
+ "@agimon-ai/po-native-components": "0.0.0-alpha.146",
36
+ "@agimon-ai/po-native-dashboard": "0.0.0-alpha.18",
37
+ "@agimon-ai/po-template-advanced": "0.0.0-alpha.146",
38
+ "@agimon-ai/po-template-elegant": "0.0.0-alpha.146",
39
+ "@agimon-ai/po-voice": "0.0.0-alpha.146",
40
+ "@agimon-ai/po-web-components": "0.0.0-alpha.146",
41
+ "@agimon-ai/po-web-dashboard": "0.0.0-alpha.146",
42
+ "@agimon-ai/po-web-security": "0.0.0-alpha.146",
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.1",
package/src/app/App.tsx CHANGED
@@ -169,6 +169,7 @@ import {
169
169
  useSettingsSections,
170
170
  } from '../screens/ContributedSettingsScreen';
171
171
  import { GitRemoteScreen, useGitRemote } from '../screens/GitRemoteScreen';
172
+ import { GlobalSettings } from '../screens/GlobalSettings';
172
173
  import { keepEqual, type HomeAttentionRow } from '../screens/homeModel';
173
174
  import { HomeAppsSection, HomeAttentionScreen, HomeScreen, type HomeView } from '../screens/HomeScreen';
174
175
  import { HostDrawer, HostMenuButton } from '../screens/HostDrawer';
@@ -1198,6 +1199,7 @@ function SettingsRoute(
1198
1199
  const appearance = useStore(appearanceStore, (state) => state);
1199
1200
  return (
1200
1201
  <SettingsScreen
1202
+ globalSection={<GlobalSettings />}
1201
1203
  {...props}
1202
1204
  {...(providers ? { providers } : {})}
1203
1205
  {...(mcpServers ? { mcpServers } : {})}
@@ -7,6 +7,7 @@ import { StyleSheet } from 'react-native-unistyles';
7
7
  import * as deviceKey from '../../modules/po-device-key';
8
8
  import { ConnectCard, type ConnectCardProps } from '../components/ConnectCard';
9
9
  import {
10
+ AccountHostsView,
10
11
  ComputerDetailView,
11
12
  ComputerRemovalView,
12
13
  AddHostView,
@@ -20,6 +21,10 @@ import {
20
21
  consumeAccountEvictions,
21
22
  discoverAccountComputer,
22
23
  readAccountRosters,
24
+ readVisibleAccountHosts,
25
+ pairedAccountHost,
26
+ setAccountHostVisibility,
27
+ type AccountHost,
23
28
  removeAccountHub,
24
29
  } from '../services/accountRoster';
25
30
  import { createHostLinkBroker, HostLinkConfirmationNeeded, type HostLinks } from '../services/hostLinkBroker';
@@ -120,11 +125,24 @@ export function HostsRoute({
120
125
  phase: 'confirm' | 'forgotten';
121
126
  pendingQuorum?: boolean;
122
127
  }>();
123
- const [account, setAccount] = useState<{ issuer: string; subject: string }>();
128
+ const [account, setAccount] = useState<Awaited<ReturnType<typeof loadLocalAccount>>>();
129
+ const [accountHosts, setAccountHosts] = useState<AccountHost[]>([]);
124
130
  const [busy, setBusy] = useState(false);
125
131
  const [renameError, setRenameError] = useState<string>();
132
+ const accountRead = useRef(0);
126
133
  const refreshAccount = useCallback(async () => {
127
- setAccount(await loadLocalAccount(await selectedIdentityIssuer()));
134
+ const revision = ++accountRead.current;
135
+ const issuer = await selectedIdentityIssuer();
136
+ const record = await loadLocalAccount(issuer);
137
+ let visible: AccountHost[] = [];
138
+ if (record) {
139
+ const auth = await createAccountClient(issuer);
140
+ if ((await auth.session())?.id === record.subject)
141
+ visible = await readVisibleAccountHosts((path) => auth.request(path), record.subject);
142
+ }
143
+ if (revision !== accountRead.current) return;
144
+ setAccount(record);
145
+ setAccountHosts(visible);
128
146
  await applyAccountEvictions(manager());
129
147
  }, [manager]);
130
148
  useFocusEffect(
@@ -136,7 +154,10 @@ export function HostsRoute({
136
154
  const subscription = AppState.addEventListener('change', (state) => {
137
155
  if (state === 'active') refresh();
138
156
  });
139
- return () => subscription.remove();
157
+ return () => {
158
+ accountRead.current++;
159
+ subscription.remove();
160
+ };
140
161
  }, [refreshAccount]),
141
162
  );
142
163
  const remove = () => {
@@ -284,6 +305,66 @@ export function HostsRoute({
284
305
  {error}
285
306
  </Text>
286
307
  ) : null}
308
+ {account ? (
309
+ <AccountHostsView
310
+ hosts={accountHosts.map((host) => {
311
+ const pairedId = pairedAccountHost(
312
+ host,
313
+ states.flatMap(({ host }) => ('signer' in host ? [host] : [])),
314
+ );
315
+ const paired = states.find(({ host }) => host.id === pairedId)?.host;
316
+ return {
317
+ ...host,
318
+ label: paired?.displayName ?? host.label,
319
+ pairedId,
320
+ canShare:
321
+ host.canShare &&
322
+ !!paired &&
323
+ 'signer' in paired &&
324
+ paired.person?.issuer === account.issuer &&
325
+ paired.person.subject === account.subject &&
326
+ paired.accountDeviceKeyId === account.deviceId,
327
+ };
328
+ })}
329
+ busy={busy}
330
+ onConnect={onAdd}
331
+ onDetail={onComputerDetail ?? setDetail}
332
+ onShare={(networkId, hostId, shared) => {
333
+ if (busy) return;
334
+ const host = accountHosts.find((host) => host.networkId === networkId && host.hostId === hostId);
335
+ const pairedId =
336
+ host &&
337
+ pairedAccountHost(
338
+ host,
339
+ states.flatMap(({ host }) => ('signer' in host ? [host] : [])),
340
+ );
341
+ const paired = states.find(({ host }) => host.id === pairedId)?.host;
342
+ if (!host || !paired || !('signer' in paired)) return;
343
+ setBusy(true);
344
+ setError(undefined);
345
+ void (async () => {
346
+ const auth = await createAccountClient(await selectedIdentityIssuer());
347
+ if (auth.issuer !== account.issuer || (await auth.session())?.id !== account.subject)
348
+ throw new Error('Sign in again before changing sharing.');
349
+ await setAccountHostVisibility(
350
+ {
351
+ keys: deviceKey,
352
+ put: (path, body) => auth.put(path, body),
353
+ now,
354
+ nonce: () => crypto.randomUUID(),
355
+ },
356
+ account,
357
+ host,
358
+ paired,
359
+ shared ? 'org' : 'member',
360
+ );
361
+ await refreshAccount();
362
+ })()
363
+ .catch((error: unknown) => setError(message(error)))
364
+ .finally(() => setBusy(false));
365
+ }}
366
+ />
367
+ ) : null}
287
368
  <HostsView
288
369
  hosts={hosts}
289
370
  onDetail={onComputerDetail ?? setDetail}
@@ -1,4 +1,4 @@
1
- import { qualifyHostId, splitHostId } from '@agimon-ai/po-web-dashboard/core';
1
+ export { homeAppEntries, homePageRoute } from '@agimon-ai/po-web-dashboard/core';
2
2
 
3
3
  export type HomeTileSize = 'small' | 'wide' | 'tall' | 'large';
4
4
 
@@ -30,61 +30,3 @@ export function placeTiles(sizes: readonly HomeTileSize[], columns: number) {
30
30
  return { column: start % columns, row: Math.floor(start / columns), columnSpan, rowSpan };
31
31
  });
32
32
  }
33
-
34
- interface HomeHost {
35
- id: string;
36
- person?: { issuer: string; subject: string };
37
- connected?: boolean;
38
- }
39
-
40
- type FillScope = { combinesComputers?: unknown; dataScope?: unknown } | undefined;
41
-
42
- /**
43
- * One card per computer, except for a plugin whose page joins every computer (its fill sets
44
- * `data.combinesComputers`, as the calendar does): that one shows once per person. Unlinked
45
- * computers join the phone's one account, or share a card of their own when it holds several.
46
- * A fill with `data.dataScope: 'global'` reads a shared backend, so it also shows once per person,
47
- * from that person's first connected computer, and is marked `global` so it reads only that one.
48
- */
49
- export function homeAppEntries<T extends { pluginId: string; id: string; data?: unknown }>(
50
- hosts: readonly HomeHost[],
51
- read: (hostId: string) => readonly T[],
52
- ) {
53
- const people = new Set(hosts.flatMap((host) => (host.person ? [JSON.stringify(host.person)] : [])));
54
- const unlinked = people.size === 1 ? [...people][0]! : 'unlinked';
55
- const fills = hosts.map((host) => ({ host, fills: read(host.id) }));
56
- const keyOf = (host: HomeHost, fill: T) => {
57
- const scope = fill.data as FillScope;
58
- const perPerson = scope?.combinesComputers === true || scope?.dataScope === 'global';
59
- const owner = perPerson ? (host.person ? JSON.stringify(host.person) : unlinked) : host.id;
60
- return JSON.stringify([owner, splitHostId(fill.pluginId)?.localId ?? fill.pluginId, fill.id]);
61
- };
62
- // A global fill is served by the first connected computer that has it, else the first one.
63
- const globalHost = new Map<string, string>();
64
- for (const connectedPass of [true, false])
65
- for (const { host, fills: hostFills } of fills)
66
- if ((host.connected !== false) === connectedPass)
67
- for (const fill of hostFills)
68
- if ((fill.data as FillScope)?.dataScope === 'global') {
69
- const key = keyOf(host, fill);
70
- if (!globalHost.has(key)) globalHost.set(key, host.id);
71
- }
72
- const seen = new Set<string>();
73
- return fills.flatMap(({ host, fills: hostFills }) =>
74
- hostFills.flatMap((fill) => {
75
- const key = keyOf(host, fill);
76
- const chosen = globalHost.get(key);
77
- if (seen.has(key) || (chosen !== undefined && chosen !== host.id)) return [];
78
- seen.add(key);
79
- return [{ hostId: host.id, fill, key, global: chosen !== undefined }];
80
- }),
81
- );
82
- }
83
-
84
- /** Page ids retain the supplying host, independent of focus and connection order. */
85
- export function homePageRoute(hostId: string, pageId: string) {
86
- return {
87
- pageId: qualifyHostId(hostId, pageId),
88
- title: pageId.charAt(0).toUpperCase() + pageId.slice(1).replace(/-/g, ' '),
89
- };
90
- }
@@ -0,0 +1,51 @@
1
+ import { View } from 'react-native';
2
+
3
+ import { PhoneFrame } from './designFrame';
4
+ import { AccountHostsView } from './HostsView';
5
+
6
+ const noop = () => undefined;
7
+ function Target({
8
+ scheme = 'light',
9
+ shared = false,
10
+ manager = true,
11
+ empty = false,
12
+ }: {
13
+ scheme?: 'light' | 'dark';
14
+ shared?: boolean;
15
+ manager?: boolean;
16
+ empty?: boolean;
17
+ }) {
18
+ return (
19
+ <PhoneFrame scheme={scheme}>
20
+ <View style={{ padding: 16, gap: 16 }}>
21
+ <AccountHostsView
22
+ hosts={
23
+ empty
24
+ ? []
25
+ : [
26
+ {
27
+ networkId: 'personal',
28
+ hostId: 'studio',
29
+ label: 'Studio Mac',
30
+ pairedId: 'studio',
31
+ visibility: shared ? 'org' : 'member',
32
+ canShare: manager,
33
+ },
34
+ { networkId: 'team', hostId: 'office', label: 'Office Mac', visibility: 'org', canShare: false },
35
+ ]
36
+ }
37
+ onConnect={noop}
38
+ onDetail={noop}
39
+ onShare={noop}
40
+ />
41
+ </View>
42
+ </PhoneFrame>
43
+ );
44
+ }
45
+ export const Playground = { render: () => <Target /> };
46
+ export const Dark = { render: () => <Target scheme="dark" /> };
47
+ export const Shared = { render: () => <Target shared /> };
48
+ export const Member = { render: () => <Target manager={false} /> };
49
+ export const Empty = { render: () => <Target empty /> };
50
+ const meta = { title: 'Native/Design/Hosts in your account', tags: ['style-system', 'mockup', 'native'] };
51
+ export default meta;
@@ -0,0 +1,36 @@
1
+ import { View } from 'react-native';
2
+
3
+ import { PhoneFrame } from './designFrame';
4
+ import { GlobalSettingsView, Group, Row } from './SettingsScreen';
5
+
6
+ const noop = () => undefined;
7
+ function Target({ scheme = 'light', notice, error }: { scheme?: 'light' | 'dark'; notice?: string; error?: string }) {
8
+ return (
9
+ <PhoneFrame scheme={scheme}>
10
+ <View style={{ padding: 16, gap: 16 }}>
11
+ <Group label="Studio Mac">
12
+ <Row title="Host settings" description="Settings on this computer override Global." last />
13
+ </Group>
14
+ <Group label="Global" hint="Your portable preferences across hosts in Personal.">
15
+ <GlobalSettingsView
16
+ yaml={'native:\n theme: dark\nvoice:\n language: en\n'}
17
+ onChange={noop}
18
+ onSave={noop}
19
+ notice={notice}
20
+ error={error}
21
+ />
22
+ </Group>
23
+ </View>
24
+ </PhoneFrame>
25
+ );
26
+ }
27
+ export const Playground = { render: () => <Target /> };
28
+ export const Dark = { render: () => <Target scheme="dark" /> };
29
+ export const DeliveryDeferred = {
30
+ render: () => (
31
+ <Target notice="Global settings are saved. Permission could not reach every host yet. Work here can continue." />
32
+ ),
33
+ };
34
+ export const Conflict = { render: () => <Target error="Settings changed. Reload before saving again." /> };
35
+ const meta = { title: 'Native/Design/Settings: by host + Global', tags: ['style-system', 'mockup', 'native'] };
36
+ export default meta;
@@ -0,0 +1,144 @@
1
+ import { nonPortableConfigYaml } from '@agimon-ai/po-core/native';
2
+ import { Select } from '@agimon-ai/po-native-components';
3
+ import { useFocusEffect } from '@react-navigation/native';
4
+ import { useCallback, useRef, useState } from 'react';
5
+
6
+ import { createAccountClient, grantGlobalSettings, selectedIdentityIssuer } from '../services/accountClient';
7
+ import { GlobalSettingsView, Group, Row } from './SettingsScreen';
8
+
9
+ /** Reads the member tier directly from the signed-in issuer, not the selected computer. */
10
+ export function GlobalSettings() {
11
+ const epoch = useRef(0);
12
+ const [client, setClient] = useState<Awaited<ReturnType<typeof createAccountClient>>>();
13
+ const [organizations, setOrganizations] = useState<{ id: string; name: string }[]>([]);
14
+ const [org, setOrg] = useState('');
15
+ const [document, setDocument] = useState<{ yaml: string; hash: string }>();
16
+ const [yaml, setYaml] = useState('');
17
+ const [busy, setBusy] = useState(false);
18
+ const [error, setError] = useState<string>();
19
+ const [notice, setNotice] = useState<string>();
20
+ useFocusEffect(
21
+ useCallback(() => {
22
+ let active = true;
23
+ setClient(undefined);
24
+ setBusy(false);
25
+ setDocument(undefined);
26
+ setOrganizations([]);
27
+ setError(undefined);
28
+ setNotice(undefined);
29
+ void (async () => {
30
+ const auth = await createAccountClient(await selectedIdentityIssuer());
31
+ if (!(await auth.session())) return;
32
+ const orgs = await auth.request<{ id: string; name: string }[]>('/organization/list');
33
+ if (!Array.isArray(orgs) || orgs.some((item) => typeof item.id !== 'string' || typeof item.name !== 'string'))
34
+ throw new Error('Invalid account networks.');
35
+ if (active) {
36
+ setClient(auth);
37
+ setOrganizations(orgs);
38
+ setOrg(orgs[0]?.id ?? '');
39
+ }
40
+ })().catch((error: unknown) => {
41
+ if (active) setError(error instanceof Error ? error.message : 'Could not load Global settings.');
42
+ });
43
+ return () => {
44
+ active = false;
45
+ };
46
+ }, []),
47
+ );
48
+ useFocusEffect(
49
+ useCallback(() => {
50
+ let active = true;
51
+ const revision = ++epoch.current;
52
+ setDocument(undefined);
53
+ setError(undefined);
54
+ setNotice(undefined);
55
+ if (client && org) {
56
+ setBusy(true);
57
+ void client
58
+ .request<{ yaml: string; hash: string }>(`/api/account/settings?org=${encodeURIComponent(org)}`)
59
+ .then((value) => {
60
+ if (typeof value?.yaml !== 'string' || typeof value.hash !== 'string')
61
+ throw new Error('Invalid Global settings.');
62
+ if (active) {
63
+ setDocument(value);
64
+ setYaml(value.yaml);
65
+ }
66
+ })
67
+ .catch((error: unknown) => {
68
+ if (active) setError(error instanceof Error ? error.message : 'Could not read Global settings.');
69
+ })
70
+ .finally(() => {
71
+ if (active) setBusy(false);
72
+ });
73
+ }
74
+ return () => {
75
+ active = false;
76
+ if (epoch.current === revision) epoch.current++;
77
+ };
78
+ }, [client, org]),
79
+ );
80
+ const save = () => {
81
+ if (!client || !document || busy) return;
82
+ setError(undefined);
83
+ setNotice(undefined);
84
+ try {
85
+ const rejected = nonPortableConfigYaml(yaml);
86
+ if (rejected.length) throw new Error(`Keep these settings on a host: ${rejected.join(', ')}`);
87
+ } catch (error) {
88
+ setError(error instanceof Error ? error.message : 'Invalid settings YAML.');
89
+ return;
90
+ }
91
+ const revision = epoch.current;
92
+ setBusy(true);
93
+ void client
94
+ .put<{ hash: string }>(
95
+ `/api/account/settings?org=${encodeURIComponent(org)}&expectedHash=${encodeURIComponent(document.hash)}`,
96
+ yaml,
97
+ )
98
+ .then(async (result) => {
99
+ if (typeof result?.hash !== 'string') throw new Error('The identity home did not confirm saving.');
100
+ if (epoch.current === revision) setDocument({ yaml, hash: result.hash });
101
+ try {
102
+ await grantGlobalSettings(client.issuer, org);
103
+ if (epoch.current === revision) setNotice('Global settings saved.');
104
+ } catch {
105
+ if (epoch.current === revision)
106
+ setNotice('Global settings are saved. Permission could not reach every host yet. Work here can continue.');
107
+ }
108
+ })
109
+ .catch((error: unknown) => {
110
+ if (epoch.current === revision)
111
+ setError(error instanceof Error ? error.message : 'Could not save Global settings.');
112
+ })
113
+ .finally(() => {
114
+ if (epoch.current === revision) setBusy(false);
115
+ });
116
+ };
117
+ return (
118
+ <Group
119
+ label="Global"
120
+ hint={
121
+ client ? 'Your portable preferences across hosts.' : 'Sign in to edit your portable preferences across hosts.'
122
+ }
123
+ >
124
+ {organizations.length ? (
125
+ <Select
126
+ title="Account network"
127
+ value={org}
128
+ options={organizations.map((item) => ({ value: item.id, label: item.name }))}
129
+ onValueChange={setOrg}
130
+ disabled={busy}
131
+ />
132
+ ) : null}
133
+ {document ? (
134
+ <GlobalSettingsView yaml={yaml} onChange={setYaml} onSave={save} busy={busy} error={error} notice={notice} />
135
+ ) : (
136
+ <Row
137
+ title={busy ? 'Loading Global settings' : 'Global settings unavailable'}
138
+ description={error ?? 'Choose an account network after signing in.'}
139
+ last
140
+ />
141
+ )}
142
+ </Group>
143
+ );
144
+ }
@@ -13,11 +13,75 @@ import {
13
13
  ListRow,
14
14
  Panel,
15
15
  SectionLabel,
16
+ Switch,
16
17
  } from '@agimon-ai/po-native-components';
17
18
  import { type ReactNode, useState } from 'react';
18
19
  import { Text, View } from 'react-native';
19
20
  import { StyleSheet } from 'react-native-unistyles';
20
21
 
22
+ import { Group, Row } from './SettingsScreen';
23
+
24
+ export function AccountHostsView({
25
+ hosts,
26
+ onConnect,
27
+ onDetail,
28
+ onShare,
29
+ busy = false,
30
+ }: {
31
+ hosts: readonly {
32
+ networkId: string;
33
+ hostId: string;
34
+ label: string;
35
+ pairedId?: string;
36
+ visibility: 'org' | 'member';
37
+ canShare: boolean;
38
+ }[];
39
+ onConnect: () => void;
40
+ onDetail: (id: string) => void;
41
+ onShare: (networkId: string, hostId: string, shared: boolean) => void;
42
+ busy?: boolean;
43
+ }) {
44
+ return (
45
+ <Group label="Hosts in your account" hint="Connecting still needs a scanned QR code or pairing link.">
46
+ {hosts.length ? (
47
+ hosts.map((host) => (
48
+ <View key={`${host.networkId}/${host.hostId}`}>
49
+ <Row
50
+ title={host.label}
51
+ description={`${host.pairedId ? 'Paired · ' : ''}${host.visibility === 'org' ? 'Shared with org' : 'Only you'}`}
52
+ last={!host.canShare}
53
+ >
54
+ <Button
55
+ variant="outline"
56
+ disabled={busy}
57
+ onPress={() => (host.pairedId ? onDetail(host.pairedId) : onConnect())}
58
+ >
59
+ {host.pairedId ? 'Details' : 'Scan to connect'}
60
+ </Button>
61
+ </Row>
62
+ {host.canShare ? (
63
+ <Row
64
+ title="Share with org"
65
+ description="Other members can discover this host. Pairing is still required."
66
+ last
67
+ >
68
+ <Switch
69
+ accessibilityLabel={`Share ${host.label} with org`}
70
+ value={host.visibility === 'org'}
71
+ disabled={busy}
72
+ onValueChange={(shared) => onShare(host.networkId, host.hostId, shared)}
73
+ />
74
+ </Row>
75
+ ) : null}
76
+ </View>
77
+ ))
78
+ ) : (
79
+ <Row title="No hosts in this account" last />
80
+ )}
81
+ </Group>
82
+ );
83
+ }
84
+
21
85
  export interface HostViewRecord {
22
86
  id: string;
23
87
  label: string;
@@ -15,6 +15,7 @@ import {
15
15
  SectionLabel,
16
16
  SparklesIcon,
17
17
  TaskIcon,
18
+ Textarea,
18
19
  UserIcon,
19
20
  WrenchIcon,
20
21
  } from '@agimon-ai/po-native-components';
@@ -179,6 +180,7 @@ export interface SettingsScreenProps {
179
180
  computer?: string;
180
181
  /** All hosts is chosen: hide computer-specific built-in settings, but keep each host's plugin pages. */
181
182
  phoneOnly?: boolean;
183
+ globalSection?: ReactNode;
182
184
  }
183
185
 
184
186
  /** The frame around a settings page a package draws: the menu's detail as the lede, as this screen leads with its own. */
@@ -226,6 +228,7 @@ export function SettingsScreen({
226
228
  computers = [],
227
229
  computer,
228
230
  phoneOnly = false,
231
+ globalSection,
229
232
  }: SettingsScreenProps) {
230
233
  const summary = remote ? remoteSummary(remote) : undefined;
231
234
  const several = computers.length > 1;
@@ -351,6 +354,7 @@ export function SettingsScreen({
351
354
  </Group>
352
355
  ) : null,
353
356
  )}
357
+ {globalSection}
354
358
  <Group label="This phone">
355
359
  <NavRow
356
360
  Icon={UserIcon}
@@ -419,6 +423,56 @@ const styles = StyleSheet.create((theme) => {
419
423
  marginTop: -theme.spacing(2),
420
424
  },
421
425
  onComputerText: { ...text('sm', theme.colors.dim), flex: 1 },
426
+ gentleNotice: {
427
+ padding: theme.spacing(3),
428
+ backgroundColor: theme.colors['tint-magenta'],
429
+ borderColor: theme.colors['edge-magenta'],
430
+ },
431
+ noticeText: { ...text('sm', theme.colors.text) },
422
432
  error: { ...text('base', theme.colors.red), paddingHorizontal: theme.spacing(1) },
423
433
  };
424
434
  });
435
+
436
+ export function GlobalSettingsView({
437
+ yaml,
438
+ onChange,
439
+ onSave,
440
+ busy = false,
441
+ error,
442
+ notice,
443
+ }: {
444
+ yaml: string;
445
+ onChange: (yaml: string) => void;
446
+ onSave: () => void;
447
+ busy?: boolean;
448
+ error?: string;
449
+ notice?: string;
450
+ }) {
451
+ return (
452
+ <>
453
+ <Row
454
+ title="Portable settings"
455
+ description="Modes, subagents, web, native, and voice language only. Host settings override Global."
456
+ last
457
+ />
458
+ <Textarea
459
+ accessibilityLabel="Global settings YAML"
460
+ value={yaml}
461
+ onChangeText={onChange}
462
+ rows={8}
463
+ disabled={busy}
464
+ />
465
+ <ErrorLine>{error}</ErrorLine>
466
+ {notice ? (
467
+ <Panel style={styles.gentleNotice}>
468
+ <Text accessibilityLiveRegion="polite" style={styles.noticeText}>
469
+ {notice}
470
+ </Text>
471
+ </Panel>
472
+ ) : null}
473
+ <Button onPress={onSave} disabled={busy}>
474
+ Save Global settings
475
+ </Button>
476
+ </>
477
+ );
478
+ }
@@ -74,7 +74,97 @@ export const accountGrants = createAccountGrants({
74
74
  },
75
75
  sign: (record, payload) => accountTrust.grant(record, payload),
76
76
  now: Date.now,
77
+ deliver: async (workId, envelope) => {
78
+ if (workId === 'settings.global.read') await deliverGlobalSettingsGrant(envelope);
79
+ },
77
80
  });
81
+
82
+ async function deliverGlobalSettingsGrant(envelope: SavedGrant['envelope']): Promise<void> {
83
+ const { loadHosts } = await import('../deviceTrust');
84
+ const { apiTransportForHost } = await import('../apiTransport');
85
+ const g = envelope.payload;
86
+ const host = (await loadHosts()).find(
87
+ (entry) =>
88
+ entry.federationHostId === g.callingHostId &&
89
+ entry.person?.issuer === g.issuer &&
90
+ entry.person.subject === g.subject,
91
+ );
92
+ if (!host) throw new Error('Connect to the owned computer to share these settings.');
93
+ const auth = await createAccountClient(g.issuer);
94
+ const record = await accountTrust.hydrate(g.issuer, await auth.request('/devices'));
95
+ if (!record || record.subject !== g.subject) throw new Error('Sign in to the settings owner account.');
96
+ const minted = await auth.request<string | { token: string }>(
97
+ '/identity-token',
98
+ await accountTrust.proof(record, 'mint', { org: g.networkId }),
99
+ );
100
+ const token = typeof minted === 'string' ? minted : minted.token;
101
+ const path = '/api/network/settings-consent';
102
+ const body = JSON.stringify(envelope);
103
+ const proof = await accountTrust.request(record, token, {
104
+ destinationHostId: g.callingHostId,
105
+ networkId: g.networkId,
106
+ workspaceId: '',
107
+ method: 'POST',
108
+ canonicalTarget: path,
109
+ body,
110
+ });
111
+ const response = await apiTransportForHost(host.id)(path, {
112
+ method: 'POST',
113
+ body,
114
+ headers: {
115
+ 'content-type': 'application/json',
116
+ 'x-po-identity-token': token,
117
+ 'x-po-federation-envelope': JSON.stringify(proof),
118
+ },
119
+ });
120
+ if (!response.ok) throw new Error('Settings saved, but this computer could not receive permission.');
121
+ }
122
+
123
+ /** Call after the owner explicitly saves Global settings. Pairing remains required for delivery. */
124
+ export async function grantGlobalSettings(issuer: string, org: string): Promise<void> {
125
+ const { loadHosts } = await import('../deviceTrust');
126
+ const { apiTransportForHost } = await import('../apiTransport');
127
+ const auth = await createAccountClient(issuer);
128
+ const user = await auth.session();
129
+ const record = await loadLocalAccount(issuer);
130
+ if (!user || !record || user.id !== record.subject) throw new Error('Sign in before sharing settings.');
131
+ const roster = await auth.request<{
132
+ payload: { hosts: { payload: { hostId: string; endpoints: string[]; enrollmentGeneration?: number } }[] };
133
+ }>(`/api/networks/${encodeURIComponent(org)}/roster`);
134
+ const targetEntry = roster.payload.hosts.find(({ payload }) =>
135
+ payload.endpoints.some((endpoint) => URL.canParse(endpoint) && new URL(endpoint).origin === new URL(issuer).origin),
136
+ )?.payload;
137
+ const target = targetEntry?.hostId ?? 'po-cloud';
138
+ const failures: unknown[] = [];
139
+ for (const host of await loadHosts()) {
140
+ if (host.person?.issuer !== issuer || host.person.subject !== record.subject || !host.federationHostId) continue;
141
+ try {
142
+ const response = await apiTransportForHost(host.id)('/api/compositions');
143
+ if (!response.ok) throw new Error('Computer unavailable');
144
+ const metadata = (await response.json()) as {
145
+ network?: { hostId: string; networkId: string; enrollmentGeneration?: number };
146
+ };
147
+ if (metadata.network?.networkId !== org || metadata.network.hostId !== host.federationHostId) continue;
148
+ await accountGrants.start(issuer, 'settings.global.read', {
149
+ networkId: org,
150
+ workspaceId: 'account',
151
+ callingHostId: host.federationHostId,
152
+ targetHostId: target,
153
+ ...(metadata.network.enrollmentGeneration === undefined
154
+ ? {}
155
+ : { callingEnrollmentGeneration: metadata.network.enrollmentGeneration }),
156
+ ...(targetEntry?.enrollmentGeneration === undefined
157
+ ? {}
158
+ : { targetEnrollmentGeneration: targetEntry.enrollmentGeneration }),
159
+ operations: ['settings.global.read'],
160
+ constraints: {},
161
+ });
162
+ } catch (error) {
163
+ failures.push(error);
164
+ }
165
+ }
166
+ if (failures.length) throw new Error('Settings saved. Connect to your computers and save again to share them.');
167
+ }
78
168
  export const pausedGrants = new Store<SavedGrant[]>([]);
79
169
  /** Called only with the reporting host's authenticated connection identity. */
80
170
  export async function receiveGrantPause(event: FederationWorkPaused, callingHostId: string): Promise<void> {
@@ -176,6 +266,20 @@ export async function createAccountClient(value: string) {
176
266
  return {
177
267
  issuer,
178
268
  request,
269
+ /** Issuer mutations use the same selected-issuer cookie transport, never host pairing credentials. */
270
+ async put<T>(path: string, body: object | string): Promise<T> {
271
+ const result = await client.$fetch<T>(`${issuer}${path}`, {
272
+ method: 'PUT',
273
+ body,
274
+ headers: {
275
+ origin: 'po://',
276
+ 'x-po-csrf': '1',
277
+ 'content-type': typeof body === 'string' ? 'text/yaml' : 'application/json',
278
+ },
279
+ });
280
+ if (result.error) throw new Error(result.error.message ?? 'Your identity home could not save this change.');
281
+ return result.data as T;
282
+ },
179
283
  async providers(): Promise<IdentityProviders> {
180
284
  const result = await request<unknown>('/providers');
181
285
  if (
@@ -7,7 +7,14 @@ import type { AccountRecord } from '../accountTrust';
7
7
  export type SignedGrant = FederationEnvelope<'po/grant/v1'>;
8
8
  export type GrantScope = Pick<
9
9
  FederationGrant,
10
- 'networkId' | 'workspaceId' | 'callingHostId' | 'targetHostId' | 'operations' | 'constraints'
10
+ | 'networkId'
11
+ | 'workspaceId'
12
+ | 'callingHostId'
13
+ | 'targetHostId'
14
+ | 'callingEnrollmentGeneration'
15
+ | 'targetEnrollmentGeneration'
16
+ | 'operations'
17
+ | 'constraints'
11
18
  >;
12
19
  export interface SavedGrant {
13
20
  workId: string;
@@ -23,6 +30,7 @@ export interface GrantPorts {
23
30
  account(issuer: string): Promise<AccountRecord>;
24
31
  sign(record: AccountRecord, payload: FederationGrant): Promise<SignedGrant>;
25
32
  now(): number;
33
+ deliver?(workId: string, envelope: SignedGrant): Promise<void>;
26
34
  }
27
35
 
28
36
  /** Native consent lifecycle. Session and calendar callers receive the envelope to hand to their host. */
@@ -63,7 +71,13 @@ export function createAccountGrants(ports: GrantPorts) {
63
71
  if (record.issuer !== issuer) throw new Error('The account belongs to another identity home.');
64
72
  const envelope = await sign(record, scope);
65
73
  const saved = await ports.storage.read(issuer);
66
- await ports.storage.write(issuer, [...saved, { workId, envelope }]);
74
+ await ports.storage.write(issuer, [
75
+ ...saved.filter(
76
+ (item) => item.workId !== workId || item.envelope.payload.callingHostId !== scope.callingHostId,
77
+ ),
78
+ { workId, envelope },
79
+ ]);
80
+ await ports.deliver?.(workId, envelope);
67
81
  return envelope;
68
82
  });
69
83
  return {
@@ -86,6 +100,7 @@ export function createAccountGrants(ports: GrantPorts) {
86
100
  return grants;
87
101
  });
88
102
  },
103
+ start,
89
104
  onSessionStart: start,
90
105
  onJobCreated: start,
91
106
  /** Expired grants need an explicit renew action, never silent consent on open. */
@@ -112,6 +127,7 @@ export function createAccountGrants(ports: GrantPorts) {
112
127
  continue;
113
128
  const envelope = await sign(record, item.envelope.payload, item.envelope.payload.grantId);
114
129
  item.envelope = envelope;
130
+ await ports.deliver?.(item.workId, envelope);
115
131
  renewed.push(envelope);
116
132
  }
117
133
  await ports.storage.write(issuer, saved);
@@ -129,6 +145,7 @@ export function createAccountGrants(ports: GrantPorts) {
129
145
  if (record.issuer !== issuer || record.subject !== item.envelope.payload.subject)
130
146
  throw new Error('Sign in to the account that shared this work.');
131
147
  item.envelope = await sign(record, item.envelope.payload, grantId);
148
+ await ports.deliver?.(item.workId, item.envelope);
132
149
  await ports.storage.write(issuer, saved);
133
150
  return item.envelope;
134
151
  });
@@ -52,7 +52,7 @@ export async function registerHostInRoster(
52
52
  payload,
53
53
  signature: await ports.keys.sign(record.alias, attestationBytes('po/roster/v1', federationEnvelopeFields(payload))),
54
54
  };
55
- await ports.post(`/api/networks/${encodeURIComponent(networkId)}/hosts`, { entry });
55
+ await ports.post(`/api/networks/${encodeURIComponent(networkId)}/hosts`, { entry, visibility: 'member' });
56
56
  return entry;
57
57
  }
58
58
 
@@ -388,3 +388,124 @@ export async function consumeAccountEvictions(
388
388
  if (evicted) await purge(host.id);
389
389
  }
390
390
  }
391
+
392
+ export interface AccountHost {
393
+ networkId: string;
394
+ hostId: string;
395
+ publicKey: string;
396
+ label: string;
397
+ visibility: 'member' | 'org';
398
+ canShare: boolean;
399
+ }
400
+
401
+ /** Discovery is metadata only. Never connect to an issuer-advertised endpoint or replace a QR pin. */
402
+ export async function readVisibleAccountHosts(
403
+ get: (path: string) => Promise<unknown>,
404
+ subject: string,
405
+ ): Promise<AccountHost[]> {
406
+ const organizations = await get('/organization/list');
407
+ if (!Array.isArray(organizations)) throw new Error('The identity home returned invalid networks.');
408
+ const hosts: AccountHost[] = [];
409
+ for (const organization of organizations) {
410
+ if (!organization || typeof organization.id !== 'string') throw new Error('Invalid account network.');
411
+ const networkId = organization.id;
412
+ const org = encodeURIComponent(networkId);
413
+ const membership = (await get(`/organization/get-full-organization?organizationId=${org}`)) as {
414
+ members?: { userId: string; role: string }[];
415
+ };
416
+ const role = membership?.members?.find((member) => member.userId === subject)?.role;
417
+ const result = (await get(`/api/networks/${org}/hosts/visible`)) as {
418
+ networkId?: string;
419
+ hosts?: { entry?: { payload?: FederationRosterHost }; visibility?: unknown }[];
420
+ };
421
+ if (result?.networkId !== networkId || !Array.isArray(result.hosts)) throw new Error('Invalid account hosts.');
422
+ for (const item of result.hosts) {
423
+ const host = item.entry?.payload;
424
+ if (
425
+ !host ||
426
+ host.networkId !== networkId ||
427
+ typeof host.hostId !== 'string' ||
428
+ typeof host.publicKey !== 'string' ||
429
+ (item.visibility !== 'member' && item.visibility !== 'org')
430
+ )
431
+ throw new Error('Invalid account host.');
432
+ hosts.push({
433
+ networkId,
434
+ hostId: host.hostId,
435
+ publicKey: host.publicKey,
436
+ label: host.hostId,
437
+ visibility: item.visibility,
438
+ canShare: role === 'owner' || role === 'admin',
439
+ });
440
+ }
441
+ }
442
+ return hosts;
443
+ }
444
+
445
+ /** Both identities must match. A changed key requires scanning again, not silently updating trust. */
446
+ export function pairedAccountHost(
447
+ host: AccountHost,
448
+ paired: readonly { id: string; federationHostId?: string; signer: { publicKey: string } }[],
449
+ ): string | undefined {
450
+ return paired.find(
451
+ (candidate) => candidate.federationHostId === host.hostId && candidate.signer.publicKey === host.publicKey,
452
+ )?.id;
453
+ }
454
+
455
+ /** An org role alone cannot share a host: the signing device must also be pinned at this hub. */
456
+ export async function setAccountHostVisibility(
457
+ ports: {
458
+ keys: AccountKeyPort;
459
+ put(path: string, body: object): Promise<unknown>;
460
+ now(): number;
461
+ nonce(): string;
462
+ },
463
+ record: AccountRecord,
464
+ host: AccountHost,
465
+ pairing: {
466
+ federationHostId?: string;
467
+ signer: { publicKey: string };
468
+ person?: { issuer: string; subject: string };
469
+ accountDeviceKeyId?: string;
470
+ enrollmentGeneration?: number;
471
+ },
472
+ visibility: 'org' | 'member',
473
+ ) {
474
+ if (
475
+ !host.canShare ||
476
+ pairing.federationHostId !== host.hostId ||
477
+ pairing.signer.publicKey !== host.publicKey ||
478
+ pairing.person?.issuer !== record.issuer ||
479
+ pairing.person.subject !== record.subject ||
480
+ pairing.accountDeviceKeyId !== record.deviceId
481
+ )
482
+ throw new Error('Use the phone pinned to this claimed host to change sharing.');
483
+ const key = await ports.keys.getPublicKey(record.alias);
484
+ if (key.publicKey !== record.publicKey || key.assurance !== record.assurance)
485
+ throw new Error('Approve this phone before changing sharing.');
486
+ const issuedAt = ports.now();
487
+ const payload = {
488
+ issuer: record.issuer,
489
+ subject: record.subject,
490
+ networkId: host.networkId,
491
+ hostId: host.hostId,
492
+ enrollmentGeneration: pairing.enrollmentGeneration ?? 1,
493
+ deviceKeyId: record.deviceId,
494
+ visibility,
495
+ nonce: ports.nonce(),
496
+ issuedAt,
497
+ expiresAt: issuedAt + 60_000,
498
+ };
499
+ const tag = 'po/host-visibility/v1' as const;
500
+ const authorization = {
501
+ tag,
502
+ payload,
503
+ signature: await ports.keys.sign(record.alias, attestationBytes(tag, federationEnvelopeFields(payload))),
504
+ };
505
+ const result = (await ports.put(
506
+ `/api/networks/${encodeURIComponent(host.networkId)}/hosts/${encodeURIComponent(host.hostId)}/visibility`,
507
+ { visibility, authorization },
508
+ )) as { hostId?: string; visibility?: string };
509
+ if (result?.hostId !== host.hostId || result.visibility !== visibility)
510
+ throw new Error('The identity home did not confirm sharing. Refresh before trying again.');
511
+ }
@@ -361,10 +361,9 @@ export function addMcpServer(
361
361
  trusted: boolean,
362
362
  hostId?: string,
363
363
  ): Promise<Result<{ ok: true }>> {
364
- // ponytail: the MCP settings wire spells the host tier 'global' until Phase 10, so older hosts still accept it.
365
364
  return request(
366
365
  MCP_SERVERS_ROUTE,
367
- { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ scope: 'global', name, entry, trusted }) },
366
+ { method: 'POST', headers: JSON_HEADERS, body: JSON.stringify({ scope: 'host', name, entry, trusted }) },
368
367
  ok,
369
368
  hostId,
370
369
  );