@agimon-ai/po-ios 0.0.1-alpha.2 → 0.0.1-alpha.21

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.
@@ -0,0 +1,1025 @@
1
+ import { defineActivityGroup, defineChannelFile, defineFill, defineGlobalStore, defineSessionStore, defineSettingsPanel, defineWebLifecycle, defineWebPlugin } from "@agimon-ai/po-core/web";
2
+ import { useStore } from "@tanstack/react-store";
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
+ import { ActivityIcon, Button, Checkbox, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SettingsActions, SettingsCard, SettingsField, SettingsHeader, SettingsNote, SettingsPage, SettingsRow, SettingsRowDescription, SettingsRowText, SettingsRowTitle, SettingsSection, SettingsSectionHeader, SettingsSectionTitle } from "@agimon-ai/po-web-components";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ //#region src/extensions/(frontend)/setting/_lib/settingsRuntime.ts
7
+ const settingsRuntime = defineGlobalStore(void 0);
8
+ function startSettingsRuntime(runtime) {
9
+ const invoke = (call) => runtime.invokeServerMethod(call);
10
+ settingsRuntime.update(() => invoke);
11
+ return () => settingsRuntime.update((current) => current === invoke ? void 0 : current);
12
+ }
13
+ //#endregion
14
+ //#region src/extensions/(frontend)/lifecycle/start.web.ts
15
+ var start_web_default$1 = defineWebLifecycle(startSettingsRuntime);
16
+ //#endregion
17
+ //#region src/constants/ios.ts
18
+ const IOS_POOL_DEFAULTS = {
19
+ minBooted: 0,
20
+ maxBooted: 2,
21
+ maxDevices: 4,
22
+ idleShutdownMinutes: 10,
23
+ waitTimeoutSeconds: 120
24
+ };
25
+ //#endregion
26
+ //#region src/extensions/(frontend)/setting/_lib/settingsModel.ts
27
+ const poolFields = [
28
+ {
29
+ key: "maxRunning",
30
+ path: "maxBooted",
31
+ label: "Running limit",
32
+ detail: "Maximum simulators running at once."
33
+ },
34
+ {
35
+ key: "maxStored",
36
+ path: "maxDevices",
37
+ label: "Stored limit",
38
+ detail: "Maximum Po-owned simulators kept on this computer."
39
+ },
40
+ {
41
+ key: "warmCount",
42
+ path: "minBooted",
43
+ label: "Keep warm",
44
+ detail: "Idle simulators to keep ready."
45
+ },
46
+ {
47
+ key: "idleMinutes",
48
+ path: "idleShutdownMinutes",
49
+ label: "Idle timeout (minutes)",
50
+ detail: "Stop an unused Po-owned simulator after this long."
51
+ },
52
+ {
53
+ key: "queueSeconds",
54
+ path: "waitTimeoutSeconds",
55
+ label: "Queue timeout (seconds)",
56
+ detail: "How long a session can wait for a simulator."
57
+ }
58
+ ];
59
+ const physicalAvailabilityNote = "Every acquisition still asks for human approval. Excluding a phone does not revoke an active lease. Phones are never erased.";
60
+ const simulatorOwnershipNote = "Only Po-owned simulators are managed. Your personal simulators are left alone.";
61
+ const safeUdid = (value) => /^(?:[a-fA-F0-9]{8}-[a-fA-F0-9]{16}|[a-fA-F0-9]{40})$/.test(value);
62
+ const settingPaths = {
63
+ teamId: [
64
+ "ios",
65
+ "device",
66
+ "developmentTeam"
67
+ ],
68
+ model: [
69
+ "ios",
70
+ "pool",
71
+ "deviceType"
72
+ ],
73
+ runtime: [
74
+ "ios",
75
+ "pool",
76
+ "runtime"
77
+ ]
78
+ };
79
+ const emptyDraft = () => ({
80
+ teamId: "",
81
+ model: "",
82
+ runtime: "",
83
+ availability: {},
84
+ maxRunning: String(IOS_POOL_DEFAULTS.maxBooted),
85
+ maxStored: String(IOS_POOL_DEFAULTS.maxDevices),
86
+ warmCount: String(IOS_POOL_DEFAULTS.minBooted),
87
+ idleMinutes: String(IOS_POOL_DEFAULTS.idleShutdownMinutes),
88
+ queueSeconds: String(IOS_POOL_DEFAULTS.waitTimeoutSeconds)
89
+ });
90
+ function record(value) {
91
+ return typeof value === "object" && value !== null && !Array.isArray(value);
92
+ }
93
+ async function readSettings(request, udids) {
94
+ const search = new URLSearchParams({ repoRoot: "" });
95
+ const paths = [...Object.entries(settingPaths).map(([key, path]) => ({
96
+ key,
97
+ path
98
+ })), ...poolFields.map((field) => ({
99
+ key: field.key,
100
+ path: [
101
+ "ios",
102
+ "pool",
103
+ field.path
104
+ ]
105
+ }))];
106
+ for (const { path } of paths) search.append("key", path.join("."));
107
+ for (const udid of udids.filter(safeUdid)) search.append("key", `ios.device.availability.${udid}`);
108
+ const response = await request(`/api/settings?${search}`);
109
+ const body = await response.json();
110
+ if (!response.ok || !record(body) || !record(body.values) || !record(body.hashes) || typeof body.hashes.global !== "string") throw new Error("Could not read global iOS settings. Your draft is unchanged.");
111
+ const values = body.values;
112
+ const draft = emptyDraft();
113
+ const valueAt = (path) => {
114
+ const entry = values[path.join(".")];
115
+ return record(entry) && typeof entry.value === "string" ? entry.value : void 0;
116
+ };
117
+ for (const { key, path } of paths) draft[key] = valueAt(path) ?? draft[key];
118
+ for (const udid of udids.filter(safeUdid)) draft.availability[udid] = valueAt([
119
+ "ios",
120
+ "device",
121
+ "availability",
122
+ udid
123
+ ]) === "excluded" ? "excluded" : "available";
124
+ return {
125
+ draft,
126
+ hash: body.hashes.global
127
+ };
128
+ }
129
+ /** Scalar edits only. The host validates and atomically writes the complete document. */
130
+ function settingsEdits(draft, saved) {
131
+ const edits = [];
132
+ if (draft.teamId && !/^[A-Z0-9]{10}$/.test(draft.teamId)) throw new Error("Team ID must contain 10 uppercase letters or digits.");
133
+ for (const [key, keyPath] of Object.entries(settingPaths)) if (draft[key] !== saved[key]) edits.push({
134
+ keyPath,
135
+ value: draft[key] || null
136
+ });
137
+ for (const field of poolFields) {
138
+ const value = Number(draft[field.key]);
139
+ const minimum = field.key === "warmCount" || field.key === "queueSeconds" ? 0 : 1;
140
+ if (!/^\d+$/.test(draft[field.key]) || !Number.isSafeInteger(value) || value < minimum) throw new Error(`${field.label} must be a whole number of at least ${minimum}.`);
141
+ if (draft[field.key] !== saved[field.key]) edits.push({
142
+ keyPath: [
143
+ "ios",
144
+ "pool",
145
+ field.path
146
+ ],
147
+ value
148
+ });
149
+ }
150
+ if (Number(draft.warmCount) > Number(draft.maxRunning) || Number(draft.maxRunning) > Number(draft.maxStored)) throw new Error("Keep warm must not exceed the running limit, and the running limit must not exceed the stored limit.");
151
+ for (const [udid, value] of Object.entries(draft.availability)) {
152
+ if (!safeUdid(udid) || value !== "available" && value !== "excluded") throw new Error("Invalid phone availability.");
153
+ if (value !== (saved.availability[udid] ?? "available")) edits.push({
154
+ keyPath: [
155
+ "ios",
156
+ "device",
157
+ "availability",
158
+ udid
159
+ ],
160
+ value
161
+ });
162
+ }
163
+ if (edits.length > 100) throw new Error("Save at most 100 settings at a time.");
164
+ return edits;
165
+ }
166
+ function pendingActivation(draft, status) {
167
+ if (!status?.active || !status.applied) return true;
168
+ const applied = status.applied;
169
+ return draft.teamId !== (applied.developmentTeam ?? "") || draft.model !== (applied.pool.deviceType ?? "") || draft.runtime !== (applied.pool.runtime ?? "") || poolFields.some((field) => Number(draft[field.key]) !== applied.pool[field.path]) || Object.entries(draft.availability).some(([udid, state]) => state !== (applied.availability[udid] ?? "available"));
170
+ }
171
+ /** The settings host may reconnect to a different version, so reject malformed replies. */
172
+ function parseSettingsStatus(value) {
173
+ if (!record(value) || typeof value.active !== "boolean" || typeof value.configFile !== "string" || !Array.isArray(value.phones) || !Array.isArray(value.runtimes)) return void 0;
174
+ if (value.inventoryError !== void 0 && typeof value.inventoryError !== "string") return void 0;
175
+ if (value.runtimeError !== void 0 && typeof value.runtimeError !== "string") return void 0;
176
+ const choice = (item) => record(item) && typeof item.identifier === "string" && typeof item.name === "string";
177
+ if (value.phones.some((phone) => !record(phone) || typeof phone.udid !== "string" || typeof phone.name !== "string" || typeof phone.paired !== "boolean" || typeof phone.connected !== "boolean" || typeof phone.leased !== "boolean" || phone.availability !== "available" && phone.availability !== "excluded")) return void 0;
178
+ if (value.runtimes.some((runtime) => !record(runtime) || !choice(runtime) || typeof runtime.isAvailable !== "boolean" || !Array.isArray(runtime.models) || runtime.models.some((model) => !choice(model)))) return void 0;
179
+ if (value.applied !== void 0) {
180
+ const applied = value.applied;
181
+ if (!record(applied) || !record(applied.pool) || !record(applied.availability)) return void 0;
182
+ const pool = applied.pool;
183
+ if (poolFields.some((field) => typeof pool[field.path] !== "number" || !Number.isSafeInteger(pool[field.path]))) return void 0;
184
+ if (pool.deviceType !== void 0 && typeof pool.deviceType !== "string" || pool.runtime !== void 0 && typeof pool.runtime !== "string") return void 0;
185
+ if (applied.developmentTeam !== void 0 && typeof applied.developmentTeam !== "string") return void 0;
186
+ if (Object.entries(applied.availability).some(([udid, state]) => !safeUdid(udid) || state !== "available" && state !== "excluded")) return void 0;
187
+ }
188
+ return value;
189
+ }
190
+ //#endregion
191
+ //#region src/extensions/(frontend)/setting/_lib/useIosSettings.ts
192
+ function useIosSettings({ request, requestWithStepUp }, invoke) {
193
+ const [saved, setSaved] = useState();
194
+ const [draft, setDraft] = useState(emptyDraft);
195
+ const [status, setStatus] = useState();
196
+ const [loading, setLoading] = useState(true);
197
+ const [saving, setSaving] = useState(false);
198
+ const [conflict, setConflict] = useState(false);
199
+ const [notice, setNotice] = useState("Loading iOS settings.");
200
+ const generation = useRef(0);
201
+ const mounted = useRef(false);
202
+ const draftRef = useRef(draft);
203
+ draftRef.current = draft;
204
+ const savedRef = useRef(saved);
205
+ savedRef.current = saved;
206
+ const busy = useRef(false);
207
+ const edited = useRef(false);
208
+ const load = useCallback(async () => {
209
+ const run = ++generation.current;
210
+ setLoading(true);
211
+ try {
212
+ let current;
213
+ if (invoke) try {
214
+ current = parseSettingsStatus(await invoke({
215
+ mount: { scope: "global" },
216
+ service: "ios",
217
+ method: "settings",
218
+ input: {}
219
+ }));
220
+ } catch {}
221
+ const fresh = await readSettings(request, [.../* @__PURE__ */ new Set([
222
+ ...Object.keys(draftRef.current.availability),
223
+ ...Object.keys(current?.applied?.availability ?? {}),
224
+ ...current?.phones.map((phone) => phone.udid) ?? []
225
+ ])]);
226
+ if (generation.current !== run) return;
227
+ const hadDraft = edited.current && (savedRef.current === void 0 || JSON.stringify(draftRef.current) !== JSON.stringify(savedRef.current.draft));
228
+ setSaved(fresh);
229
+ setStatus(current);
230
+ if (!hadDraft) setDraft(fresh.draft);
231
+ setConflict(false);
232
+ setNotice(hadDraft ? `Current saved settings: ${JSON.stringify(fresh.draft)}. Your draft is retained. Review before saving again.` : pendingActivation(fresh.draft, current) ? "Saved settings are pending activation. The active service has not been restarted." : "Saved settings match the active iOS service. Signing has not been checked.");
233
+ } catch {
234
+ if (generation.current === run) {
235
+ setStatus(void 0);
236
+ setNotice("Could not reach global iOS settings. Your draft is retained. Try again.");
237
+ }
238
+ } finally {
239
+ if (generation.current === run) setLoading(false);
240
+ }
241
+ }, [request, invoke]);
242
+ useEffect(() => {
243
+ mounted.current = true;
244
+ load();
245
+ return () => {
246
+ mounted.current = false;
247
+ generation.current++;
248
+ };
249
+ }, [load]);
250
+ const dirty = saved !== void 0 && JSON.stringify(draft) !== JSON.stringify(saved.draft);
251
+ const save = async () => {
252
+ if (!saved || busy.current || conflict || loading) return;
253
+ busy.current = true;
254
+ setSaving(true);
255
+ const run = generation.current;
256
+ let wrote = false;
257
+ try {
258
+ const edits = settingsEdits(draft, saved.draft);
259
+ if (!edits.length) return;
260
+ const response = await requestWithStepUp("/api/settings/value", {
261
+ method: "PUT",
262
+ headers: { "content-type": "application/json" },
263
+ body: JSON.stringify({
264
+ repoRoot: "",
265
+ scope: "global",
266
+ expectedHash: saved.hash,
267
+ edits
268
+ })
269
+ });
270
+ if (run !== generation.current) return;
271
+ if (response.status === 409) {
272
+ setConflict(true);
273
+ setNotice("Settings changed on your computer. Review current settings before saving again. Your draft is retained.");
274
+ return;
275
+ }
276
+ if (!response.ok) {
277
+ setNotice(`Settings were not saved (Po answered ${response.status}). Your draft is retained.`);
278
+ return;
279
+ }
280
+ wrote = true;
281
+ const fresh = await readSettings(request, Object.keys(draft.availability));
282
+ if (run !== generation.current) return;
283
+ setSaved(fresh);
284
+ if (settingsEdits(draft, fresh.draft).length) {
285
+ setConflict(true);
286
+ setNotice("Settings changed again after saving. Your draft is retained. Review current settings.");
287
+ } else {
288
+ edited.current = false;
289
+ setDraft(fresh.draft);
290
+ setNotice(pendingActivation(fresh.draft, status) ? "Saved. Pending activation: restart the iOS service explicitly when ready. Saving did not restart it or interrupt leases." : "Saved settings match the active iOS service. Signing has not been checked.");
291
+ }
292
+ } catch (error) {
293
+ if (run === generation.current) {
294
+ if (wrote) setConflict(true);
295
+ setNotice(wrote ? "The write succeeded, but current settings could not be confirmed. Your draft is retained. Review current settings before saving again." : error instanceof Error ? error.message : "Could not save settings. Your draft is retained.");
296
+ }
297
+ } finally {
298
+ busy.current = false;
299
+ if (mounted.current) setSaving(false);
300
+ }
301
+ };
302
+ return {
303
+ draft,
304
+ status,
305
+ loading,
306
+ saving,
307
+ dirty,
308
+ conflict,
309
+ notice,
310
+ onChange: (key, value) => {
311
+ edited.current = true;
312
+ setDraft((current) => ({
313
+ ...current,
314
+ [key]: value
315
+ }));
316
+ setNotice("Unsaved changes.");
317
+ },
318
+ onSave: () => {
319
+ save();
320
+ },
321
+ onDiscard: () => {
322
+ edited.current = false;
323
+ if (saved) setDraft(saved.draft);
324
+ setNotice("Draft discarded. Saved settings are unchanged.");
325
+ },
326
+ onReload: () => {
327
+ if (!busy.current) load();
328
+ }
329
+ };
330
+ }
331
+ //#endregion
332
+ //#region src/extensions/(frontend)/setting/_components/IosSettingsView.tsx
333
+ function IosSettingsView({ children, draft, status, loading, saving, dirty, conflict, notice, onChange: change, onSave, onDiscard, onReload }) {
334
+ const blocked = loading || saving;
335
+ const simulatorFields = poolFields.slice(0, 2);
336
+ const advancedFields = poolFields.slice(2);
337
+ const phones = [...status?.phones ?? [], ...Object.keys(draft.availability).filter((udid) => !status?.phones.some((phone) => phone.udid === udid)).map((udid) => ({
338
+ udid,
339
+ name: udid,
340
+ paired: false,
341
+ connected: false,
342
+ leased: false
343
+ }))];
344
+ const runtimes = status?.runtimes ?? [];
345
+ const models = [...new Map(runtimes.filter((runtime) => runtime.identifier === draft.runtime || !draft.runtime).flatMap((runtime) => runtime.models).map((model) => [model.identifier, model])).values()];
346
+ return /* @__PURE__ */ jsx("div", {
347
+ className: "w-full bg-po-bg font-sans text-po-text",
348
+ children: /* @__PURE__ */ jsxs(SettingsPage, {
349
+ className: "mx-auto max-w-3xl",
350
+ "aria-busy": loading || saving,
351
+ children: [
352
+ /* @__PURE__ */ jsxs(SettingsHeader, { children: [
353
+ children,
354
+ /* @__PURE__ */ jsx(SettingsNote, {
355
+ role: "status",
356
+ children: notice
357
+ }),
358
+ /* @__PURE__ */ jsx(SettingsNote, { children: status?.applied ? `Active: Team ID ${status.applied.developmentTeam || "not set"}, running limit ${status.applied.pool.maxBooted}, stored limit ${status.applied.pool.maxDevices}.` : "Active configuration is unavailable." }),
359
+ /* @__PURE__ */ jsx(Button, {
360
+ variant: "outline",
361
+ className: "self-start",
362
+ onClick: onReload,
363
+ disabled: blocked,
364
+ children: conflict ? "Review current settings" : !status ? "Try again" : "Refresh settings"
365
+ })
366
+ ] }),
367
+ /* @__PURE__ */ jsxs(SettingsSection, { children: [
368
+ /* @__PURE__ */ jsx(SettingsSectionHeader, { children: /* @__PURE__ */ jsx(SettingsSectionTitle, { children: "Development signing" }) }),
369
+ /* @__PURE__ */ jsx(SettingsCard, { children: /* @__PURE__ */ jsx(SettingsField, {
370
+ id: "ios-team-id",
371
+ label: "Apple Development Team ID",
372
+ description: "Used to sign Po’s physical-device runner. Not an Apple account sign-in.",
373
+ children: /* @__PURE__ */ jsx(Input, {
374
+ id: "ios-team-id",
375
+ className: "font-mono",
376
+ value: draft.teamId,
377
+ disabled: blocked,
378
+ onChange: (event) => change("teamId", event.target.value),
379
+ "aria-describedby": "ios-team-status"
380
+ })
381
+ }) }),
382
+ /* @__PURE__ */ jsx(SettingsNote, {
383
+ id: "ios-team-status",
384
+ children: "Signing has not been checked. Saving a Team ID does not check certificates, provisioning or build installation eligibility."
385
+ })
386
+ ] }),
387
+ /* @__PURE__ */ jsxs(SettingsSection, { children: [
388
+ /* @__PURE__ */ jsx(SettingsSectionHeader, { children: /* @__PURE__ */ jsx(SettingsSectionTitle, { children: "Physical iPhones" }) }),
389
+ /* @__PURE__ */ jsxs(SettingsCard, { children: [
390
+ status?.inventoryError ? /* @__PURE__ */ jsx(SettingsNote, { children: status.inventoryError }) : null,
391
+ !status ? /* @__PURE__ */ jsx(SettingsNote, { children: "Phone inventory is unavailable. Try again to reconnect." }) : null,
392
+ status && !status.inventoryError && !phones.length ? /* @__PURE__ */ jsx(SettingsNote, { children: "No physical phones are visible." }) : null,
393
+ phones.map((phone) => /* @__PURE__ */ jsxs(SettingsRow, { children: [/* @__PURE__ */ jsxs(SettingsRowText, { children: [/* @__PURE__ */ jsx(SettingsRowTitle, { children: /* @__PURE__ */ jsxs("label", {
394
+ htmlFor: `ios-phone-${phone.udid}`,
395
+ children: [phone.name || phone.udid, ": available to Po"]
396
+ }) }), /* @__PURE__ */ jsxs(SettingsRowDescription, { children: [
397
+ phone.paired ? "Paired" : "Not paired",
398
+ " · ",
399
+ phone.connected ? "Reachable" : "Offline",
400
+ phone.leased ? " · In use" : "",
401
+ ". Availability applies to this phone only."
402
+ ] })] }), /* @__PURE__ */ jsx(Checkbox, {
403
+ id: `ios-phone-${phone.udid}`,
404
+ checked: (draft.availability[phone.udid] ?? "available") === "available",
405
+ disabled: blocked,
406
+ onCheckedChange: (checked) => change("availability", {
407
+ ...draft.availability,
408
+ [phone.udid]: checked === true ? "available" : "excluded"
409
+ }),
410
+ "aria-describedby": "ios-physical-note"
411
+ })] }, phone.udid))
412
+ ] }),
413
+ /* @__PURE__ */ jsx(SettingsNote, {
414
+ id: "ios-physical-note",
415
+ children: physicalAvailabilityNote
416
+ })
417
+ ] }),
418
+ /* @__PURE__ */ jsxs(SettingsSection, { children: [
419
+ /* @__PURE__ */ jsx(SettingsSectionHeader, { children: /* @__PURE__ */ jsx(SettingsSectionTitle, { children: "Simulator pool" }) }),
420
+ /* @__PURE__ */ jsxs(SettingsCard, { children: [simulatorFields.map((field) => /* @__PURE__ */ jsx(SettingsField, {
421
+ id: `ios-${field.key}`,
422
+ label: field.label,
423
+ description: field.detail,
424
+ children: /* @__PURE__ */ jsx(Input, {
425
+ id: `ios-${field.key}`,
426
+ inputMode: "numeric",
427
+ value: draft[field.key],
428
+ disabled: blocked,
429
+ onChange: (event) => change(field.key, event.target.value)
430
+ })
431
+ }, field.key)), ["model", "runtime"].map((key) => /* @__PURE__ */ jsx(SettingsField, {
432
+ id: `ios-${key}`,
433
+ label: key === "model" ? "Default model" : "Default runtime",
434
+ description: "Used for the next simulator Po creates.",
435
+ children: /* @__PURE__ */ jsxs(Select, {
436
+ value: draft[key] || "__automatic__",
437
+ disabled: blocked,
438
+ onValueChange: (value) => change(key, value === "__automatic__" ? "" : value),
439
+ children: [/* @__PURE__ */ jsx(SelectTrigger, {
440
+ id: `ios-${key}`,
441
+ children: /* @__PURE__ */ jsx(SelectValue, {})
442
+ }), /* @__PURE__ */ jsxs(SelectContent, { children: [
443
+ /* @__PURE__ */ jsx(SelectItem, {
444
+ value: "__automatic__",
445
+ children: "Automatic"
446
+ }),
447
+ draft[key] && !(key === "model" ? models : runtimes).some((item) => item.identifier === draft[key]) ? /* @__PURE__ */ jsxs(SelectItem, {
448
+ value: draft[key],
449
+ children: [draft[key], " (not discovered)"]
450
+ }) : null,
451
+ (key === "model" ? models : runtimes).map((item) => /* @__PURE__ */ jsx(SelectItem, {
452
+ value: item.identifier,
453
+ disabled: "isAvailable" in item && !item.isAvailable,
454
+ children: item.name
455
+ }, item.identifier))
456
+ ] })]
457
+ })
458
+ }, key))] }),
459
+ /* @__PURE__ */ jsxs(SettingsNote, { children: [
460
+ simulatorOwnershipNote,
461
+ " ",
462
+ status?.runtimeError ?? (!status ? "Model and runtime discovery is unavailable." : "Choices use discovered identifiers.")
463
+ ] }),
464
+ /* @__PURE__ */ jsxs("details", {
465
+ className: "group",
466
+ children: [/* @__PURE__ */ jsx("summary", {
467
+ className: "cursor-pointer rounded py-2 text-base font-medium text-po-dim outline-none focus-visible:ring-2 focus-visible:ring-po-green",
468
+ children: "Advanced pool settings"
469
+ }), /* @__PURE__ */ jsx(SettingsCard, {
470
+ className: "mt-3",
471
+ children: advancedFields.map((field) => /* @__PURE__ */ jsx(SettingsField, {
472
+ id: `ios-${field.key}`,
473
+ label: field.label,
474
+ description: field.detail,
475
+ children: /* @__PURE__ */ jsx(Input, {
476
+ id: `ios-${field.key}`,
477
+ inputMode: "numeric",
478
+ value: draft[field.key],
479
+ disabled: blocked,
480
+ onChange: (event) => change(field.key, event.target.value)
481
+ })
482
+ }, field.key))
483
+ })]
484
+ })
485
+ ] }),
486
+ /* @__PURE__ */ jsxs("div", {
487
+ className: "flex flex-col gap-3",
488
+ children: [/* @__PURE__ */ jsxs(SettingsActions, { children: [/* @__PURE__ */ jsx(Button, {
489
+ variant: "primary",
490
+ disabled: blocked || !dirty || conflict,
491
+ onClick: onSave,
492
+ children: saving ? "Saving…" : "Save changes"
493
+ }), /* @__PURE__ */ jsx(Button, {
494
+ variant: "ghost",
495
+ disabled: blocked || !dirty,
496
+ onClick: onDiscard,
497
+ children: "Discard changes"
498
+ })] }), /* @__PURE__ */ jsx(SettingsNote, { children: "Changes require an iOS service restart. Saving never restarts a service or interrupts an active lease." })]
499
+ })
500
+ ]
501
+ })
502
+ });
503
+ }
504
+ //#endregion
505
+ //#region src/extensions/(frontend)/setting/_components/IosSettingsPanel.tsx
506
+ function IosSettingsPanel(props) {
507
+ const invoke = useStore(settingsRuntime.store, (state) => state);
508
+ return /* @__PURE__ */ jsx(IosSettingsView, { ...useIosSettings(props, invoke) });
509
+ }
510
+ //#endregion
511
+ //#region src/extensions/(frontend)/setting/ios.panel.web.tsx
512
+ var ios_panel_web_default = defineSettingsPanel({
513
+ label: "iOS",
514
+ detail: "Global signing, phone availability and simulator pool settings.",
515
+ order: 65,
516
+ component: IosSettingsPanel
517
+ });
518
+ //#endregion
519
+ //#region src/types/iosUi.ts
520
+ /** JSON-only iOS UI contracts. Lease ownership and paths are resolved by the server. */
521
+ const iosActivityChannel$1 = "ios_activity";
522
+ //#endregion
523
+ //#region src/extensions/workspaces/sessions/(frontend)/_lib/iosActivityStore.ts
524
+ const iosActivity = defineSessionStore({
525
+ supported: false,
526
+ devices: []
527
+ });
528
+ function useIosActivity(sessionId) {
529
+ return useStore(iosActivity.store, (state) => iosActivity.select(state, sessionId));
530
+ }
531
+ const iosActivityChannel = iosActivity.channel({
532
+ channel: iosActivityChannel$1,
533
+ parse(input) {
534
+ if (typeof input !== "object" || input === null) return null;
535
+ const value = input;
536
+ if (typeof value.supported !== "boolean" || !Array.isArray(value.devices)) return null;
537
+ if (!value.devices.every((device) => device && typeof device.id === "string" && typeof device.name === "string" && typeof device.detail === "string" && ["simulator", "device"].includes(device.kind) && [
538
+ "owned",
539
+ "other-session",
540
+ "available",
541
+ "disconnected"
542
+ ].includes(device.state) && ["available", "unsupported"].includes(device.capture) && (device.leaseId === void 0 || typeof device.leaseId === "string"))) return null;
543
+ if (value.build && (typeof value.build.id !== "string" || typeof value.build.name !== "string" || typeof value.build.artifactPath !== "string" || typeof value.build.size !== "number" || typeof value.build.registeredAt !== "string")) return null;
544
+ return {
545
+ supported: value.supported,
546
+ devices: value.devices.map(({ id, name, detail, kind, state, capture, leaseId }) => ({
547
+ id,
548
+ name,
549
+ detail,
550
+ kind,
551
+ state,
552
+ capture,
553
+ ...state === "owned" && leaseId ? { leaseId } : {}
554
+ })),
555
+ ...value.build ? { build: {
556
+ id: value.build.id,
557
+ name: value.build.name,
558
+ size: value.build.size,
559
+ artifactPath: value.build.artifactPath,
560
+ registeredAt: value.build.registeredAt
561
+ } } : {},
562
+ ...typeof value.error === "string" ? { error: value.error } : {}
563
+ };
564
+ },
565
+ reduce: (_current, payload) => payload
566
+ });
567
+ const iosActivitySource = {
568
+ subscribe(listener) {
569
+ const subscription = iosActivity.store.subscribe(listener);
570
+ return () => subscription.unsubscribe();
571
+ },
572
+ isActive(sessionId) {
573
+ return iosActivity.select(iosActivity.store.state, sessionId).devices.some((device) => device.state === "owned");
574
+ }
575
+ };
576
+ const invoker = defineGlobalStore(void 0);
577
+ function startIosRuntime(runtime) {
578
+ const invoke = (call) => runtime.invokeServerMethod(call);
579
+ invoker.update(() => invoke);
580
+ return () => invoker.update((current) => current === invoke ? void 0 : current);
581
+ }
582
+ async function call(sessionId, method, input) {
583
+ const invoke = invoker.store.state;
584
+ if (!invoke) throw new Error("iOS is not connected.");
585
+ return invoke({
586
+ mount: {
587
+ scope: "session",
588
+ sessionId
589
+ },
590
+ service: "ios",
591
+ method,
592
+ input
593
+ });
594
+ }
595
+ async function fetchIosFrame(sessionId, leaseId, since) {
596
+ try {
597
+ const reply = await call(sessionId, "frame", {
598
+ leaseId,
599
+ ...since ? { since } : {}
600
+ });
601
+ if (reply?.state === "ok" && typeof reply.src === "string" && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(reply.src) && typeof reply.hash === "string" && typeof reply.capturedAt === "number") return reply;
602
+ if (reply?.state === "unchanged" && since !== void 0 && typeof reply.hash === "string" && typeof reply.capturedAt === "number") return reply;
603
+ if (reply?.state === "released") return { state: "released" };
604
+ if (reply?.state === "capture-unavailable") return {
605
+ state: "capture-unavailable",
606
+ message: "Screen capture is unavailable."
607
+ };
608
+ } catch {}
609
+ return {
610
+ state: "error",
611
+ message: "Could not reach the simulator. Waiting to reconnect."
612
+ };
613
+ }
614
+ /** Action-local only. The ephemeral URL is never written to plugin state or logs. */
615
+ async function shareIosBuild(sessionId, buildId) {
616
+ try {
617
+ const reply = await call(sessionId, "shareBuild", { buildId });
618
+ if (reply?.ok === true && typeof reply.url === "string" && /^https?:\/\//.test(reply.url) && typeof reply.expiresAt === "number" && reply.expiresAt > Date.now()) return reply;
619
+ if (reply?.ok === false && reply.reason === "remote-off") return {
620
+ ok: false,
621
+ reason: "remote-off",
622
+ message: "Remote access is off. Open the build in Po locally."
623
+ };
624
+ } catch {}
625
+ return {
626
+ ok: false,
627
+ reason: "unavailable",
628
+ message: "The build is unavailable or changed. Try again when the current build appears."
629
+ };
630
+ }
631
+ /** Inventory is not permission to capture. Only an owned simulator lease can open. */
632
+ function canViewDevice(device) {
633
+ return device.state === "owned" && !!device.leaseId && device.kind === "simulator" && device.capture === "available";
634
+ }
635
+ function deviceDetail(device) {
636
+ const state = device.state === "owned" ? "This session" : device.state === "other-session" ? "Another session" : device.state === "disconnected" ? "Disconnected" : "Available";
637
+ return `${device.detail} · ${state}${device.capture === "unsupported" ? " · Screen capture unsupported" : ""}`;
638
+ }
639
+ //#endregion
640
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/IosActivityView.tsx
641
+ function IosActivityView({ devices, build, details, install, notice, footer, installExpanded = false, busy = false, canOpen = false, onView, onDownload, onCopy, onOpen, onInstall }) {
642
+ return /* @__PURE__ */ jsxs("section", {
643
+ "aria-label": "iOS Activity",
644
+ className: "w-full max-w-sm space-y-4 text-base text-po-text",
645
+ children: [
646
+ /* @__PURE__ */ jsx("div", {
647
+ className: "space-y-3",
648
+ children: devices.length === 0 ? /* @__PURE__ */ jsx("p", {
649
+ className: "text-sm text-po-dim",
650
+ children: "No device is leased to this session."
651
+ }) : devices.map((device) => /* @__PURE__ */ jsxs("div", {
652
+ className: "flex flex-wrap items-center justify-between gap-2",
653
+ children: [/* @__PURE__ */ jsxs("div", {
654
+ className: "min-w-0",
655
+ children: [/* @__PURE__ */ jsx("p", {
656
+ className: "font-semibold",
657
+ children: device.name
658
+ }), /* @__PURE__ */ jsx("p", {
659
+ className: "text-sm text-po-dim",
660
+ children: device.detail
661
+ })]
662
+ }), device.canView && /* @__PURE__ */ jsx(Button, {
663
+ size: "sm",
664
+ onClick: () => onView(device.id),
665
+ children: "View screen"
666
+ })]
667
+ }, device.id))
668
+ }),
669
+ build && /* @__PURE__ */ jsxs("div", {
670
+ className: "space-y-3 border-t border-po-border pt-4",
671
+ children: [
672
+ /* @__PURE__ */ jsxs("div", { children: [
673
+ /* @__PURE__ */ jsx("h3", {
674
+ className: "font-semibold text-po-hi",
675
+ children: "Latest build"
676
+ }),
677
+ /* @__PURE__ */ jsx("p", {
678
+ className: "mt-2 break-all font-mono",
679
+ children: build.name
680
+ }),
681
+ /* @__PURE__ */ jsx("p", {
682
+ className: "text-sm text-po-dim",
683
+ children: build.detail
684
+ })
685
+ ] }),
686
+ /* @__PURE__ */ jsx("p", {
687
+ className: "text-sm text-po-dim",
688
+ children: details.note
689
+ }),
690
+ !details.blocked && /* @__PURE__ */ jsx("p", {
691
+ className: "text-sm text-po-dim",
692
+ children: "Links expire after 10 minutes. Anyone with the link can download."
693
+ }),
694
+ /* @__PURE__ */ jsx(Button, {
695
+ className: "w-full",
696
+ variant: "primary",
697
+ disabled: details.blocked,
698
+ loading: busy,
699
+ onClick: onDownload,
700
+ children: details.action
701
+ }),
702
+ /* @__PURE__ */ jsxs("div", {
703
+ className: "flex flex-wrap gap-2",
704
+ children: [/* @__PURE__ */ jsx(Button, {
705
+ size: "sm",
706
+ variant: "link",
707
+ disabled: details.blocked,
708
+ onClick: onCopy,
709
+ children: "Copy download link"
710
+ }), /* @__PURE__ */ jsx(Button, {
711
+ size: "sm",
712
+ variant: "link",
713
+ disabled: !canOpen,
714
+ onClick: onOpen,
715
+ children: "Open in Po"
716
+ })]
717
+ }),
718
+ /* @__PURE__ */ jsxs("details", {
719
+ className: "text-sm",
720
+ open: installExpanded,
721
+ children: [/* @__PURE__ */ jsx("summary", {
722
+ className: "cursor-pointer rounded-sm text-po-dim focus-visible:outline-2 focus-visible:outline-po-green",
723
+ children: "Install on iPhone"
724
+ }), /* @__PURE__ */ jsxs("div", {
725
+ className: "mt-3 space-y-2",
726
+ children: [/* @__PURE__ */ jsx("p", {
727
+ className: "text-po-dim",
728
+ children: install.note
729
+ }), /* @__PURE__ */ jsx(Button, {
730
+ size: "sm",
731
+ disabled: install.blocked,
732
+ onClick: onInstall,
733
+ children: install.action
734
+ })]
735
+ })]
736
+ })
737
+ ]
738
+ }),
739
+ notice && /* @__PURE__ */ jsx("p", {
740
+ role: "status",
741
+ className: "text-sm text-po-blue",
742
+ children: notice
743
+ }),
744
+ footer && /* @__PURE__ */ jsx("p", {
745
+ className: "text-sm text-po-dim",
746
+ children: footer
747
+ })
748
+ ]
749
+ });
750
+ }
751
+ //#endregion
752
+ //#region src/extensions/workspaces/sessions/(frontend)/_lib/iosFrames.ts
753
+ /** Serial visible-reader polling. Late replies after cleanup are never delivered. */
754
+ function pollIosFrames(fetchFrame, receive) {
755
+ let stopped = false;
756
+ let timer;
757
+ let hash;
758
+ const tick = async () => {
759
+ let reply;
760
+ try {
761
+ reply = await fetchFrame(hash);
762
+ } catch {
763
+ reply = {
764
+ state: "error",
765
+ message: "Could not reach the simulator."
766
+ };
767
+ }
768
+ if (stopped) return;
769
+ if (reply.state === "ok") hash = reply.hash;
770
+ else if (reply.state === "error") hash = void 0;
771
+ receive(reply);
772
+ if (reply.state !== "released" && reply.state !== "capture-unavailable") timer = setTimeout(() => void tick(), 750);
773
+ };
774
+ tick();
775
+ return () => {
776
+ stopped = true;
777
+ clearTimeout(timer);
778
+ };
779
+ }
780
+ //#endregion
781
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/IosDeviceView.tsx
782
+ function IosDeviceView({ name, status, note, frame, controls, composer, onClose }) {
783
+ return /* @__PURE__ */ jsxs("div", {
784
+ className: "flex h-full min-h-96 w-full flex-col bg-po-bg text-base text-po-text",
785
+ children: [
786
+ /* @__PURE__ */ jsxs("div", {
787
+ className: "flex flex-wrap items-center justify-between gap-2 border-b border-po-border bg-po-panel px-4 py-3",
788
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h2", {
789
+ className: "font-semibold text-po-hi",
790
+ children: name
791
+ }), /* @__PURE__ */ jsxs("p", {
792
+ className: "text-sm text-po-dim",
793
+ children: ["View only · ", status]
794
+ })] }), onClose && /* @__PURE__ */ jsx(Button, {
795
+ size: "sm",
796
+ onClick: onClose,
797
+ children: "Close view"
798
+ })]
799
+ }),
800
+ /* @__PURE__ */ jsxs("div", {
801
+ className: "flex min-h-0 flex-1 flex-col items-center gap-3 overflow-auto bg-po-deep p-4",
802
+ children: [
803
+ /* @__PURE__ */ jsx("p", {
804
+ role: "status",
805
+ className: "max-w-lg text-center text-sm text-po-dim",
806
+ children: note
807
+ }),
808
+ frame,
809
+ controls
810
+ ]
811
+ }),
812
+ composer
813
+ ]
814
+ });
815
+ }
816
+ //#endregion
817
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/IosDevicePanel.tsx
818
+ function iosDeviceTab(device) {
819
+ return {
820
+ id: `ios-device-${device.id}-${device.leaseId}`,
821
+ label: device.name,
822
+ retainComposer: true,
823
+ panel: (props) => /* @__PURE__ */ jsx(IosDevicePanel, {
824
+ ...props,
825
+ opened: device
826
+ }, props.sessionId)
827
+ };
828
+ }
829
+ function useVisible() {
830
+ const [visible, setVisible] = useState(typeof document === "undefined" || !document.hidden);
831
+ useEffect(() => {
832
+ const update = () => setVisible(!document.hidden);
833
+ document.addEventListener("visibilitychange", update);
834
+ return () => document.removeEventListener("visibilitychange", update);
835
+ }, []);
836
+ return visible;
837
+ }
838
+ function IosDevicePanel({ sessionId, opened, closeTransientTab }) {
839
+ const device = useIosActivity(sessionId).devices.find((item) => item.id === opened.id);
840
+ const owned = !!device && canViewDevice(device) && device.leaseId === opened.leaseId;
841
+ const visible = useVisible();
842
+ const [frame, setFrame] = useState();
843
+ const [reply, setReply] = useState();
844
+ const released = reply?.state === "released";
845
+ const unavailable = reply?.state === "capture-unavailable";
846
+ useEffect(() => {
847
+ setFrame(void 0);
848
+ if (!sessionId || !owned || !visible || released || unavailable || !opened.leaseId) return;
849
+ return pollIosFrames((since) => fetchIosFrame(sessionId, opened.leaseId, since), (next) => {
850
+ setReply(next);
851
+ if (next.state === "ok") setFrame(next.src);
852
+ else if (next.state === "released" || next.state === "capture-unavailable" || next.state === "error") setFrame(void 0);
853
+ });
854
+ }, [
855
+ sessionId,
856
+ owned,
857
+ visible,
858
+ released,
859
+ unavailable,
860
+ opened.leaseId
861
+ ]);
862
+ const status = !owned || released ? "Device released or ownership changed" : unavailable ? "Screen capture unavailable" : !visible ? "Capture paused while hidden" : reply?.state === "error" ? "Connection unavailable" : frame ? "Updated just now" : "Waiting for first frame";
863
+ const pixels = owned && visible && !released && !unavailable ? frame : void 0;
864
+ return /* @__PURE__ */ jsx(IosDeviceView, {
865
+ name: `${opened.name}${owned && !released ? " · This session" : ""}`,
866
+ status,
867
+ note: owned && !released ? "View only. Po controls this session’s simulator." : "View only.",
868
+ onClose: () => closeTransientTab(`ios-device-${opened.id}-${opened.leaseId}`),
869
+ frame: pixels ? /* @__PURE__ */ jsx("img", {
870
+ src: pixels,
871
+ alt: "Current simulator screen",
872
+ className: "max-h-full w-60 shrink-0 object-contain"
873
+ }) : /* @__PURE__ */ jsx("div", {
874
+ className: "flex min-h-48 w-full max-w-sm flex-1 items-center justify-center rounded-md border border-po-border p-6 text-center text-po-dim",
875
+ children: status
876
+ })
877
+ });
878
+ }
879
+ //#endregion
880
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/IosActivityPanel.tsx
881
+ function iosActivityTab() {
882
+ return {
883
+ id: "ios-activity",
884
+ label: "iOS",
885
+ panel: IosActivityPanel
886
+ };
887
+ }
888
+ function IosActivityPanel(props) {
889
+ const activity = useIosActivity(props.sessionId);
890
+ const [busy, setBusy] = useState(false);
891
+ const [notice, setNotice] = useState("");
892
+ const mounted = useRef(true);
893
+ const currentBuild = useRef(`${props.sessionId}:${activity.build?.id}`);
894
+ currentBuild.current = `${props.sessionId}:${activity.build?.id}`;
895
+ useEffect(() => {
896
+ mounted.current = true;
897
+ return () => {
898
+ mounted.current = false;
899
+ };
900
+ }, []);
901
+ const build = activity.build;
902
+ const artifactTab = build ? props.fileTabFor(`artifact:${build.artifactPath}`) : void 0;
903
+ const share = async (copy) => {
904
+ if (!props.sessionId || !build || busy) return;
905
+ setBusy(true);
906
+ setNotice("");
907
+ try {
908
+ const reply = await shareIosBuild(props.sessionId, build.id);
909
+ if (!mounted.current || currentBuild.current !== `${props.sessionId}:${build.id}`) return;
910
+ if (!reply.ok) {
911
+ setNotice(reply.message);
912
+ return;
913
+ }
914
+ if (copy) {
915
+ await navigator.clipboard.writeText(reply.url);
916
+ if (mounted.current) setNotice("Download link copied. Anyone with the link can download for 10 minutes.");
917
+ } else {
918
+ const anchor = document.createElement("a");
919
+ anchor.href = reply.url;
920
+ anchor.download = build.name;
921
+ anchor.rel = "noopener";
922
+ document.body.append(anchor);
923
+ anchor.click();
924
+ anchor.remove();
925
+ }
926
+ } catch {
927
+ if (mounted.current) setNotice("The download handoff was unavailable. Try again or open the build in Po.");
928
+ } finally {
929
+ if (mounted.current) setBusy(false);
930
+ }
931
+ };
932
+ return /* @__PURE__ */ jsx(IosActivityView, {
933
+ devices: activity.devices.map((device) => ({
934
+ id: device.id,
935
+ name: device.name,
936
+ detail: deviceDetail(device),
937
+ canView: canViewDevice(device)
938
+ })),
939
+ build: build ? {
940
+ name: build.name,
941
+ detail: `${(build.size / 1024 / 1024).toFixed(1)} MB`
942
+ } : void 0,
943
+ details: {
944
+ note: activity.error ?? (!activity.supported ? "iOS is unavailable on this host." : !build ? "No build is registered for this session." : "Download this build without connecting a device."),
945
+ action: busy ? "Preparing link" : "Download build",
946
+ blocked: !build || busy
947
+ },
948
+ install: {
949
+ note: "Direct install is unavailable. Compatible signing, registered phone eligibility and HTTPS installation have not been verified.",
950
+ action: "Install unavailable",
951
+ blocked: true
952
+ },
953
+ notice,
954
+ busy,
955
+ canOpen: !!artifactTab,
956
+ footer: build && !artifactTab ? "Open in Po is unavailable because this host cannot preview the build artifact." : void 0,
957
+ onView: (id) => {
958
+ const device = activity.devices.find((item) => item.id === id);
959
+ if (device && canViewDevice(device)) props.openTransientTab(iosDeviceTab(device));
960
+ },
961
+ onDownload: () => void share(false),
962
+ onCopy: () => void share(true),
963
+ onOpen: () => {
964
+ if (artifactTab) props.openTransientTab(artifactTab);
965
+ },
966
+ onInstall: () => {}
967
+ });
968
+ }
969
+ //#endregion
970
+ //#region src/extensions/workspaces/sessions/(frontend)/activity-group/ios.web.ts
971
+ var ios_web_default = defineActivityGroup({
972
+ keys: "g i",
973
+ icon: ActivityIcon,
974
+ activeSource: iosActivitySource,
975
+ marksBackgroundWork: false,
976
+ order: 46,
977
+ transientTab: iosActivityTab
978
+ });
979
+ //#endregion
980
+ //#region src/extensions/workspaces/sessions/(frontend)/channel/ios-activity.web.ts
981
+ var ios_activity_web_default = defineChannelFile(iosActivityChannel);
982
+ //#endregion
983
+ //#region src/extensions/workspaces/sessions/(frontend)/fill/Ios.activity.ios.web.tsx
984
+ var Ios_activity_ios_web_default = defineFill({ component: IosActivityPanel });
985
+ //#endregion
986
+ //#region src/extensions/workspaces/sessions/(frontend)/lifecycle/start.web.ts
987
+ var start_web_default = defineWebLifecycle(startIosRuntime);
988
+ //#endregion
989
+ //#region generated/web.ts
990
+ const via = (identity, value) => value === void 0 ? void 0 : {
991
+ ...identity,
992
+ ...value
993
+ };
994
+ const webPlugin = defineWebPlugin({
995
+ id: "ios",
996
+ global: {
997
+ get settingsPanels() {
998
+ return [via({ id: "ios" }, ios_panel_web_default)];
999
+ },
1000
+ get start() {
1001
+ return start_web_default$1;
1002
+ }
1003
+ },
1004
+ session: {
1005
+ get activityGroups() {
1006
+ return [via({ name: "ios" }, ios_web_default)];
1007
+ },
1008
+ get channels() {
1009
+ return [via({ channel: "ios_activity" }, ios_activity_web_default)];
1010
+ },
1011
+ get fills() {
1012
+ return [via({
1013
+ slot: "activity.ios",
1014
+ id: "ios"
1015
+ }, Ios_activity_ios_web_default)];
1016
+ },
1017
+ get start() {
1018
+ return start_web_default;
1019
+ }
1020
+ }
1021
+ });
1022
+ //#endregion
1023
+ export { webPlugin };
1024
+
1025
+ //# sourceMappingURL=web.mjs.map