@aixnn/aixautots 0.6.3 → 0.6.5

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.
Files changed (51) hide show
  1. package/dist/{automation-queue-BxrSIkG3.d.ts → automation-queue-aYRO9JLj.d.ts} +2 -2
  2. package/dist/chunk-7CN37G3W.js +102 -0
  3. package/dist/{chunk-JTFZSFFA.js → chunk-7H4CYM42.js} +414 -5
  4. package/dist/{chunk-FW23FLAF.js → chunk-D7J4EQTA.js} +1 -1
  5. package/dist/{chunk-B2BOVLI6.js → chunk-F76N3GOA.js} +1077 -313
  6. package/dist/{chunk-P2Y655SL.js → chunk-FBWJUW4X.js} +578 -141
  7. package/dist/{chunk-T3QVYTOT.js → chunk-IFARWPMU.js} +364 -0
  8. package/dist/{chunk-LTZCKFAZ.js → chunk-LMSN6Z3N.js} +668 -103
  9. package/dist/{chunk-Q63FQ7B5.js → chunk-LWTL4AIC.js} +254 -13
  10. package/dist/{chunk-EVHTAXQG.js → chunk-SKTL6ACT.js} +5 -1
  11. package/dist/{chunk-6S3XLY5O.js → chunk-X5KVYWUK.js} +4 -5
  12. package/dist/chunk-YWA47ARA.js +1148 -0
  13. package/dist/{config-CLi5IhmO.d.ts → config-B7t1Ln3w.d.ts} +177 -8
  14. package/dist/core/index.d.ts +21 -16
  15. package/dist/core/index.js +2 -4
  16. package/dist/{device-normalize-BaThgnH7.d.ts → device-normalize-CuGflfZA.d.ts} +1 -1
  17. package/dist/device-session-OFGN4KUD.js +1 -0
  18. package/dist/i18n/index.js +1 -1
  19. package/dist/{mirror-session-BP7Rd3Jk.d.ts → mirror-session-DK0OQvA3.d.ts} +11 -3
  20. package/dist/react/index.d.ts +10 -8
  21. package/dist/react/index.js +3 -6
  22. package/dist/{script-debugger-DtUGxK9i.d.ts → script-debugger-6hoLEwEz.d.ts} +1 -1
  23. package/dist/{task-agent-runner-DzV_OUZ7.d.ts → task-agent-runner-BwRW88rl.d.ts} +5 -3
  24. package/dist/{types-C2WXVcam.d.ts → types-BbtVr3QM.d.ts} +34 -3
  25. package/dist/ui/billing.d.ts +1 -1
  26. package/dist/ui/billing.js +5 -8
  27. package/dist/ui/device-create.d.ts +4 -3
  28. package/dist/ui/device-create.js +7 -8
  29. package/dist/ui/device-mirror.d.ts +16 -2
  30. package/dist/ui/device-mirror.js +6 -7
  31. package/dist/ui/devices.d.ts +5 -5
  32. package/dist/ui/devices.js +10 -12
  33. package/dist/ui/editor.d.ts +2 -2
  34. package/dist/ui/editor.js +7 -10
  35. package/dist/ui/index.d.ts +4 -4
  36. package/dist/ui/index.js +9 -14
  37. package/dist/ui/inspector.js +5 -8
  38. package/dist/ui/market.js +4 -7
  39. package/dist/ui/mirror.d.ts +3 -3
  40. package/dist/ui/primitives/index.d.ts +1 -1
  41. package/dist/ui/primitives/index.js +1 -1
  42. package/dist/ui/script-studio.js +6 -9
  43. package/dist/ui/scripts.d.ts +1 -1
  44. package/dist/ui/scripts.js +5 -8
  45. package/dist/ui/tasks.js +10 -12
  46. package/package.json +1 -1
  47. package/dist/chunk-A5VNENHD.js +0 -229
  48. package/dist/chunk-BUW45GM2.js +0 -341
  49. package/dist/chunk-LAZ3RQ7X.js +0 -668
  50. package/dist/chunk-VVJ4TK6D.js +0 -583
  51. package/dist/device-session-CVT7OY4H.js +0 -2
@@ -0,0 +1,1148 @@
1
+ import { MirrorView, ControlBar } from './chunk-E7WMHM63.js';
2
+ import { useAixT } from './chunk-IFARWPMU.js';
3
+ import { Popover, Button } from './chunk-SKTL6ACT.js';
4
+ import { useMirror, useClient, useDevices } from './chunk-LWTL4AIC.js';
5
+ import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
6
+ import { Check, Settings2, VolumeX, Volume2, RotateCw, Minimize2, Maximize2, X, Rocket, Loader2, Square, Video, Download } from 'lucide-react';
7
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
8
+
9
+ var button = "flex w-full items-center justify-center gap-2 rounded-md border border-border px-2 py-2 text-xs hover:bg-secondary disabled:opacity-40";
10
+ function MirrorActions({ deviceId, stream, ready, platform = "android" }) {
11
+ const client = useClient();
12
+ const [showApps, setShowApps] = useState(false);
13
+ const [apps, setApps] = useState([]);
14
+ const [query, setQuery] = useState("");
15
+ const [loading, setLoading] = useState(false);
16
+ const [launching, setLaunching] = useState(false);
17
+ const [message, setMessage] = useState("");
18
+ const generation = useRef(0);
19
+ const busy = useRef(false);
20
+ useEffect(() => {
21
+ generation.current++;
22
+ busy.current = false;
23
+ setShowApps(false);
24
+ setApps([]);
25
+ setQuery("");
26
+ setMessage("");
27
+ setLoading(false);
28
+ setLaunching(false);
29
+ return () => {
30
+ generation.current++;
31
+ };
32
+ }, [deviceId]);
33
+ const loadApps = async () => {
34
+ const version = generation.current;
35
+ setLoading(true);
36
+ setMessage("");
37
+ try {
38
+ const result = await client.devices.op(deviceId, { op: "app_list" });
39
+ if (generation.current === version) setApps(result);
40
+ } catch (e) {
41
+ if (generation.current === version) setMessage(`\u5E94\u7528\u5217\u8868\u52A0\u8F7D\u5931\u8D25\uFF1A${String(e)}`);
42
+ } finally {
43
+ if (generation.current === version) setLoading(false);
44
+ }
45
+ };
46
+ const launch = async (pkg) => {
47
+ if (busy.current || !pkg.trim()) return;
48
+ busy.current = true;
49
+ const version = generation.current;
50
+ setLaunching(true);
51
+ setMessage("\u6B63\u5728\u542F\u52A8\u5E94\u7528\u2026");
52
+ try {
53
+ const { run_id } = await client.fleet.start({
54
+ script: { name: "\u955C\u50CF\u542F\u52A8\u5E94\u7528", platform: platform === "ios" ? "iOS" : "Android", language: "ts", code: `await device.launchApp(${JSON.stringify(pkg.trim())});` },
55
+ device_ids: [deviceId]
56
+ });
57
+ const detail = await client.fleet.waitForRun(run_id);
58
+ if (generation.current !== version) return;
59
+ const row = detail.devices?.[0];
60
+ if (row?.status === "done") setMessage("\u5E94\u7528\u5DF2\u542F\u52A8");
61
+ else if (row && ["failed", "cancelled", "canceled"].includes(row.status)) throw new Error(row.last_error || "\u5E94\u7528\u542F\u52A8\u5931\u8D25");
62
+ else setMessage("\u542F\u52A8\u4EFB\u52A1\u4ECD\u5728\u6267\u884C\uFF0C\u53EF\u5728\u4EFB\u52A1\u9875\u67E5\u770B\u7ED3\u679C");
63
+ } catch (e) {
64
+ if (generation.current === version) setMessage(`\u542F\u52A8\u5931\u8D25\uFF1A${String(e)}`);
65
+ } finally {
66
+ if (generation.current === version) {
67
+ busy.current = false;
68
+ setLaunching(false);
69
+ }
70
+ }
71
+ };
72
+ const filtered = apps.filter((app) => `${app.label} ${app.package}`.toLowerCase().includes(query.toLowerCase()));
73
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
74
+ /* @__PURE__ */ jsxs("button", { type: "button", className: button, "aria-expanded": showApps, onClick: () => {
75
+ setShowApps(!showApps);
76
+ if (!showApps) void loadApps();
77
+ }, children: [
78
+ /* @__PURE__ */ jsx(Rocket, { className: "h-3.5 w-3.5" }),
79
+ "\u542F\u52A8\u5E94\u7528"
80
+ ] }),
81
+ showApps && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 rounded-md border border-border p-2", children: [
82
+ /* @__PURE__ */ jsxs("form", { onSubmit: (e) => {
83
+ e.preventDefault();
84
+ void launch(query);
85
+ }, className: "flex flex-col gap-2", children: [
86
+ /* @__PURE__ */ jsx("input", { "aria-label": "\u641C\u7D22\u5E94\u7528\u6216\u8F93\u5165\u5305\u540D", placeholder: "\u641C\u7D22\u5E94\u7528 / \u8F93\u5165\u5305\u540D", value: query, onChange: (e) => setQuery(e.target.value), className: "w-full rounded border border-border bg-secondary p-1.5 text-xs" }),
87
+ /* @__PURE__ */ jsx("button", { type: "submit", className: button, disabled: launching || !query.trim(), children: "\u6309\u5305\u540D\u542F\u52A8" })
88
+ ] }),
89
+ /* @__PURE__ */ jsx("button", { type: "button", className: "text-xs text-muted-foreground", disabled: loading, onClick: () => void loadApps(), children: loading ? "\u52A0\u8F7D\u5E94\u7528\u4E2D\u2026" : "\u5237\u65B0\u5E94\u7528\u5217\u8868" }),
90
+ /* @__PURE__ */ jsxs("div", { className: "max-h-48 overflow-y-auto", "aria-label": "\u5E94\u7528\u5217\u8868", children: [
91
+ filtered.map((app) => /* @__PURE__ */ jsxs("button", { type: "button", disabled: launching, onClick: () => void launch(app.package), title: app.package, className: "block w-full rounded p-1.5 text-left hover:bg-secondary disabled:opacity-40", children: [
92
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-xs", children: app.label || app.package }),
93
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-[10px] text-muted-foreground", children: app.package })
94
+ ] }, app.package)),
95
+ !loading && !filtered.length && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "\u6CA1\u6709\u5339\u914D\u5E94\u7528\uFF0C\u53EF\u8F93\u5165\u5B8C\u6574\u5305\u540D\u542F\u52A8" })
96
+ ] })
97
+ ] }),
98
+ message && /* @__PURE__ */ jsx("p", { role: "status", className: "break-words text-xs text-muted-foreground", children: message }),
99
+ /* @__PURE__ */ jsx(MirrorRecording, { deviceId, stream, ready }, deviceId)
100
+ ] });
101
+ }
102
+ function saveRecording(blob, deviceId) {
103
+ const url = URL.createObjectURL(blob);
104
+ const link = document.createElement("a");
105
+ link.href = url;
106
+ link.download = `mirror-${deviceId.replace(/[^a-zA-Z0-9_-]/g, "_")}-${Date.now()}.${blob.type.includes("mp4") ? "mp4" : "webm"}`;
107
+ document.body.appendChild(link);
108
+ link.click();
109
+ link.remove();
110
+ setTimeout(() => URL.revokeObjectURL(url), 6e4);
111
+ }
112
+ function MirrorRecording({ deviceId, stream, ready }) {
113
+ const recorder = useRef(null);
114
+ const startRef = useRef(() => {
115
+ });
116
+ const stopRef = useRef(() => {
117
+ });
118
+ const [recording, setRecording] = useState(false);
119
+ const [finishing, setFinishing] = useState(false);
120
+ const [seconds, setSeconds] = useState(0);
121
+ const [error, setError] = useState("");
122
+ const [result, setResult] = useState(null);
123
+ const supported = typeof MediaRecorder !== "undefined";
124
+ useEffect(() => {
125
+ let active = true;
126
+ setRecording(false);
127
+ setFinishing(false);
128
+ let timer;
129
+ const stop = () => {
130
+ const rec = recorder.current;
131
+ if (rec && rec.state !== "inactive") {
132
+ if (active) setFinishing(true);
133
+ rec.stop();
134
+ }
135
+ };
136
+ const start = () => {
137
+ if (!stream || recorder.current) return;
138
+ const tracks = stream.getVideoTracks().filter((t) => t.readyState === "live").map((t) => t.clone());
139
+ if (!tracks.length) {
140
+ setError("\u955C\u50CF\u89C6\u9891\u5C1A\u672A\u5C31\u7EEA");
141
+ return;
142
+ }
143
+ const source = new MediaStream(tracks);
144
+ try {
145
+ const mimeType = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm", "video/mp4"].find((t) => MediaRecorder.isTypeSupported(t));
146
+ const rec = mimeType ? new MediaRecorder(source, { mimeType }) : new MediaRecorder(source);
147
+ const chunks = [];
148
+ recorder.current = rec;
149
+ rec.ondataavailable = (e) => {
150
+ if (e.data.size) chunks.push(e.data);
151
+ };
152
+ rec.onerror = () => {
153
+ if (active) setError("\u5F55\u5236\u4E2D\u65AD\uFF0C\u5DF2\u4FDD\u5B58\u7684\u7247\u6BB5\u53EF\u4E0B\u8F7D");
154
+ stop();
155
+ };
156
+ rec.onstop = () => {
157
+ clearInterval(timer);
158
+ source.getTracks().forEach((t) => t.stop());
159
+ if (recorder.current === rec) recorder.current = null;
160
+ const blob = new Blob(chunks, { type: rec.mimeType || chunks[0]?.type || "video/webm" });
161
+ if (active) {
162
+ setRecording(false);
163
+ setFinishing(false);
164
+ if (blob.size) setResult(blob);
165
+ else setError("\u6CA1\u6709\u6536\u5230\u5F55\u5236\u6570\u636E\uFF0C\u8BF7\u91CD\u8BD5");
166
+ } else if (blob.size) saveRecording(blob, deviceId);
167
+ };
168
+ rec.start(1e3);
169
+ const startedAt = Date.now();
170
+ setSeconds(0);
171
+ setError("");
172
+ setResult(null);
173
+ setRecording(true);
174
+ timer = setInterval(() => {
175
+ if (active) setSeconds(Math.floor((Date.now() - startedAt) / 1e3));
176
+ }, 1e3);
177
+ } catch (e) {
178
+ source.getTracks().forEach((t) => t.stop());
179
+ recorder.current = null;
180
+ setError(`\u65E0\u6CD5\u5F00\u59CB\u5F55\u5236\uFF1A${String(e)}`);
181
+ }
182
+ };
183
+ startRef.current = start;
184
+ stopRef.current = stop;
185
+ stream?.addEventListener("removetrack", stop);
186
+ const ended = () => stop();
187
+ stream?.getVideoTracks().forEach((t) => t.addEventListener("ended", ended));
188
+ return () => {
189
+ active = false;
190
+ clearInterval(timer);
191
+ stop();
192
+ stream?.removeEventListener("removetrack", stop);
193
+ stream?.getVideoTracks().forEach((t) => t.removeEventListener("ended", ended));
194
+ };
195
+ }, [deviceId, stream]);
196
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2", children: [
197
+ /* @__PURE__ */ jsxs("button", { type: "button", className: button, disabled: finishing || !recording && (!supported || !ready), onClick: () => recording ? stopRef.current() : startRef.current(), children: [
198
+ finishing ? /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }) : recording ? /* @__PURE__ */ jsx(Square, { className: "h-3.5 w-3.5 text-red-500" }) : /* @__PURE__ */ jsx(Video, { className: "h-3.5 w-3.5" }),
199
+ finishing ? "\u6B63\u5728\u4FDD\u5B58\u2026" : recording ? "\u505C\u6B62\u5F55\u5C4F" : "\u5F00\u59CB\u5F55\u5C4F"
200
+ ] }),
201
+ recording && /* @__PURE__ */ jsxs("span", { role: "status", className: "text-center text-xs text-red-500", children: [
202
+ "\u5F55\u5236\u4E2D ",
203
+ Math.floor(seconds / 60).toString().padStart(2, "0"),
204
+ ":",
205
+ (seconds % 60).toString().padStart(2, "0")
206
+ ] }),
207
+ result && /* @__PURE__ */ jsxs("button", { type: "button", className: button, onClick: () => saveRecording(result, deviceId), children: [
208
+ /* @__PURE__ */ jsx(Download, { className: "h-3.5 w-3.5" }),
209
+ "\u4E0B\u8F7D\u5F55\u5C4F"
210
+ ] }),
211
+ /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: supported ? "\u5F55\u5236\u5F53\u524D\u955C\u50CF\u753B\u9762\uFF08\u65E0\u58F0\uFF09\uFF0C\u6E05\u6670\u5EA6\u968F\u753B\u8D28\u8BBE\u7F6E\u3002\u5F55\u5236\u4E2D\u5173\u95ED\u65F6\u81EA\u52A8\u4FDD\u5B58\u3002" : "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u5F55\u5C4F" }),
212
+ error && /* @__PURE__ */ jsx("p", { role: "alert", className: "text-xs text-destructive", children: error })
213
+ ] });
214
+ }
215
+ var PHASES = {
216
+ android: [
217
+ [25, "\u6B63\u5728\u8FDE\u63A5\u8BBE\u5907\u2026"],
218
+ [55, "\u5EFA\u7ACB\u52A0\u5BC6\u901A\u9053\u2026"],
219
+ [80, "\u62C9\u53D6\u5B9E\u65F6\u753B\u9762\u2026"],
220
+ [95, "\u5373\u5C06\u5448\u73B0\u2026"]
221
+ ],
222
+ ios: [
223
+ [25, "\u6B63\u5728\u8FDE\u63A5\u8BBE\u5907\u2026"],
224
+ [55, "\u5EFA\u7ACB\u52A0\u5BC6\u901A\u9053\u2026"],
225
+ [80, "\u62C9\u53D6\u5B9E\u65F6\u753B\u9762\u2026"],
226
+ [95, "\u5373\u5C06\u5448\u73B0\u2026"]
227
+ ]
228
+ };
229
+ function phaseLabel(phases, p) {
230
+ for (const [ceil, label] of phases) if (p <= ceil) return label;
231
+ return "\u5373\u5C06\u5448\u73B0\u2026";
232
+ }
233
+ function DeviceBootSplash({ error, expectedMs = 3e3, platform = "android", className }) {
234
+ const [pct, setPct] = useState(4);
235
+ const startRef = useRef(Date.now());
236
+ const phases = PHASES[platform];
237
+ useEffect(() => {
238
+ if (error) return;
239
+ startRef.current = Date.now();
240
+ setPct(4);
241
+ const id = setInterval(() => {
242
+ const elapsed = Date.now() - startRef.current;
243
+ const target = 95 * (1 - Math.exp(-elapsed / (expectedMs * 0.55)));
244
+ setPct((prev) => Math.max(prev, Math.min(95, Math.round(target))));
245
+ }, 250);
246
+ return () => clearInterval(id);
247
+ }, [error, expectedMs]);
248
+ if (error) {
249
+ return /* @__PURE__ */ jsxs(
250
+ "div",
251
+ {
252
+ className: `flex h-full w-full flex-col items-center justify-center gap-3 bg-black/80 px-6 text-center ${className ?? ""}`,
253
+ children: [
254
+ /* @__PURE__ */ jsx("div", { className: "text-2xl", children: "\u26A0\uFE0F" }),
255
+ /* @__PURE__ */ jsxs("div", { className: "text-sm text-white/80", children: [
256
+ "\u8FDE\u63A5\u5931\u8D25\uFF1A",
257
+ error
258
+ ] }),
259
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-white/40", children: "\u8BBE\u5907\u9700\u5728\u7EBF\uFF1B\u82E5\u521A\u521B\u5EFA\uFF0C\u8BF7\u7B49\u5F85\u542F\u52A8\u5B8C\u6210\u540E\u91CD\u8BD5" })
260
+ ]
261
+ }
262
+ );
263
+ }
264
+ return /* @__PURE__ */ jsxs(
265
+ "div",
266
+ {
267
+ className: `flex h-full w-full flex-col items-center justify-center gap-5 bg-gradient-to-b from-zinc-900 to-black px-8 ${className ?? ""}`,
268
+ children: [
269
+ /* @__PURE__ */ jsxs("div", { className: "relative flex items-center justify-center", children: [
270
+ /* @__PURE__ */ jsx(
271
+ "span",
272
+ {
273
+ className: `absolute h-20 w-20 animate-ping rounded-full ${platform === "ios" ? "bg-sky-300/20" : "bg-emerald-400/20"}`
274
+ }
275
+ ),
276
+ /* @__PURE__ */ jsx(
277
+ "span",
278
+ {
279
+ className: `absolute h-16 w-16 animate-pulse rounded-full ${platform === "ios" ? "bg-sky-300/10" : "bg-emerald-400/10"}`
280
+ }
281
+ ),
282
+ platform === "ios" ? /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", className: "h-12 w-12 text-sky-200", fill: "currentColor", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M16.37 12.78c-.02-2.05 1.67-3.03 1.75-3.08-.95-1.39-2.43-1.58-2.96-1.6-1.26-.13-2.46.74-3.1.74-.64 0-1.62-.72-2.66-.7-1.37.02-2.63.8-3.33 2.02-1.42 2.47-.36 6.12 1.02 8.13.67.98 1.48 2.08 2.53 2.04 1.02-.04 1.4-.66 2.63-.66 1.22 0 1.57.66 2.65.64 1.09-.02 1.79-1 2.46-1.98.77-1.13 1.09-2.23 1.11-2.29-.02-.01-2.13-.82-2.15-3.25ZM14.4 6.45c.56-.68.94-1.62.84-2.56-.81.03-1.79.54-2.37 1.21-.52.6-.97 1.56-.85 2.48.9.07 1.82-.46 2.38-1.13Z" }) }) : /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", className: "h-12 w-12 text-emerald-400", fill: "currentColor", "aria-hidden": true, children: /* @__PURE__ */ jsx("path", { d: "M6 9a6 6 0 0 1 12 0v6a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V9Zm2.5-3.2 -1-1.6a.4.4 0 0 1 .7-.4l1.05 1.7a6.7 6.7 0 0 1 3.5 0l1.05-1.7a.4.4 0 1 1 .7.4l-1 1.6A6 6 0 0 0 8.5 5.8ZM9.5 9.2a.9.9 0 1 0 0 1.8.9.9 0 0 0 0-1.8Zm5 0a.9.9 0 1 0 0 1.8.9.9 0 0 0 0-1.8ZM5 11a1 1 0 0 1 1 1v4a1 1 0 1 1-2 0v-4a1 1 0 0 1 1-1Zm14 0a1 1 0 0 1 1 1v4a1 1 0 1 1-2 0v-4a1 1 0 0 1 1-1ZM9 17h6a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1 1 1 0 1 1-2 0h-2a1 1 0 1 1-2 0 1 1 0 0 1-1-1v-2a1 1 0 0 1 1-1Z" }) })
283
+ ] }),
284
+ /* @__PURE__ */ jsxs("div", { className: "w-full max-w-[220px] space-y-2", children: [
285
+ /* @__PURE__ */ jsx("div", { className: "h-1.5 w-full overflow-hidden rounded-full bg-white/10", children: /* @__PURE__ */ jsx(
286
+ "div",
287
+ {
288
+ className: `h-full rounded-full transition-[width] duration-300 ease-out ${platform === "ios" ? "bg-sky-300" : "bg-emerald-400"}`,
289
+ style: { width: `${pct}%` }
290
+ }
291
+ ) }),
292
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs", children: [
293
+ /* @__PURE__ */ jsx("span", { className: "text-white/70", children: phaseLabel(phases, pct) }),
294
+ /* @__PURE__ */ jsxs("span", { className: "tabular-nums text-white/40", children: [
295
+ pct,
296
+ "%"
297
+ ] })
298
+ ] })
299
+ ] }),
300
+ /* @__PURE__ */ jsx("div", { className: "text-[11px] text-white/30", children: "\u6B63\u5728\u8FDE\u63A5\u5B9E\u65F6\u753B\u9762\uFF0C\u5C31\u7EEA\u540E\u81EA\u52A8\u663E\u793A" })
301
+ ]
302
+ }
303
+ );
304
+ }
305
+
306
+ // src/ui/device-mirror/screenshot-request.ts
307
+ var pending = /* @__PURE__ */ new WeakMap();
308
+ function requestPreviewFrame(client, deviceId) {
309
+ const scope = client.cfg ?? client;
310
+ let devices = pending.get(scope);
311
+ if (!devices) {
312
+ devices = /* @__PURE__ */ new Map();
313
+ pending.set(scope, devices);
314
+ }
315
+ const existing = devices.get(deviceId);
316
+ if (existing) return existing;
317
+ const controller = new AbortController();
318
+ const timeout = setTimeout(() => controller.abort(), 2e4);
319
+ const request = Promise.resolve().then(() => client.devices.op(deviceId, { op: "screenshot", thumb: true }, { signal: controller.signal })).finally(() => {
320
+ clearTimeout(timeout);
321
+ if (devices.get(deviceId) === request) devices.delete(deviceId);
322
+ });
323
+ devices.set(deviceId, request);
324
+ return request;
325
+ }
326
+ function IosScreenshotPreview({ deviceId, onSize, videoAspect, className }) {
327
+ const client = useClient();
328
+ const t = useAixT();
329
+ const [running, setRunning] = useState(false);
330
+ const [visible, setVisible] = useState(() => typeof document === "undefined" || !document.hidden);
331
+ const [inView, setInView] = useState(true);
332
+ const [frame, setFrame] = useState(null);
333
+ const [busy, setBusy] = useState(false);
334
+ const [error, setError] = useState("");
335
+ const [now, setNow] = useState(Date.now());
336
+ const [refresh, setRefresh] = useState(0);
337
+ const consumedRefresh = useRef(0);
338
+ const element = useRef(null);
339
+ useEffect(() => {
340
+ const update = () => setVisible(!document.hidden);
341
+ document.addEventListener("visibilitychange", update);
342
+ const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => setInView(entries.some((e) => e.isIntersecting)));
343
+ if (element.current) observer?.observe(element.current);
344
+ return () => {
345
+ document.removeEventListener("visibilitychange", update);
346
+ observer?.disconnect();
347
+ };
348
+ }, []);
349
+ useEffect(() => {
350
+ if (!visible || !inView || !frame) return;
351
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
352
+ return () => clearInterval(timer);
353
+ }, [visible, inView, !!frame]);
354
+ useEffect(() => {
355
+ if (!visible || !inView || !running && refresh === consumedRefresh.current) {
356
+ setBusy(false);
357
+ return;
358
+ }
359
+ consumedRefresh.current = refresh;
360
+ let active = true;
361
+ let timer;
362
+ const capture = async () => {
363
+ setBusy(true);
364
+ try {
365
+ const result = await requestPreviewFrame(client, deviceId);
366
+ if (!active) return;
367
+ const url = result.jpeg_base64 ? `data:image/jpeg;base64,${result.jpeg_base64}` : result.png_base64 ? `data:image/png;base64,${result.png_base64}` : null;
368
+ if (!url) throw new Error(t("preview.empty"));
369
+ const received = Date.now();
370
+ const capturedAt = result.captured_at ? Date.parse(result.captured_at) : NaN;
371
+ setFrame({ url, at: Number.isFinite(capturedAt) ? Math.min(received, capturedAt) : received, captured: Number.isFinite(capturedAt), source: result.source });
372
+ setNow(received);
373
+ setError("");
374
+ if (running) timer = setTimeout(() => void capture(), 1e3);
375
+ } catch (e) {
376
+ if (active) {
377
+ setError(e instanceof Error ? e.message : String(e));
378
+ setRunning(false);
379
+ }
380
+ } finally {
381
+ if (active) setBusy(false);
382
+ }
383
+ };
384
+ void capture();
385
+ return () => {
386
+ active = false;
387
+ clearTimeout(timer);
388
+ };
389
+ }, [client, deviceId, running, refresh, visible, inView]);
390
+ return /* @__PURE__ */ jsxs("div", { ref: element, className: `flex min-h-0 flex-1 flex-col gap-3 ${className ?? ""}`, children: [
391
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
392
+ /* @__PURE__ */ jsx(Button, { size: "sm", className: "min-h-11", onClick: () => {
393
+ setRefresh(0);
394
+ setRunning((value) => !value);
395
+ }, children: t(running ? "preview.stop" : "preview.start") }),
396
+ /* @__PURE__ */ jsx(Button, { size: "sm", className: "min-h-11", variant: "secondary", disabled: busy || running || !visible || !inView, onClick: () => setRefresh((value) => value + 1), children: t("preview.refresh") })
397
+ ] }),
398
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("preview.explanation") }),
399
+ /* @__PURE__ */ jsx("div", { "aria-busy": busy, className: "flex min-h-0 flex-1 items-center justify-center overflow-hidden rounded-md bg-secondary", style: videoAspect ? { aspectRatio: videoAspect } : { minHeight: 160 }, children: frame ? /* @__PURE__ */ jsx("img", { src: frame.url, alt: t("preview.image"), className: "max-h-full max-w-full object-contain", onLoad: (event) => {
400
+ const image = event.currentTarget;
401
+ if (image.naturalWidth && image.naturalHeight) onSize?.({ width: image.naturalWidth, height: image.naturalHeight });
402
+ }, onError: () => {
403
+ setError(t("preview.decodeFailed"));
404
+ setRunning(false);
405
+ } }) : /* @__PURE__ */ jsx("p", { className: "p-4 text-center text-sm text-muted-foreground", children: t(busy ? "preview.loading" : "preview.emptyState") }) }),
406
+ /* @__PURE__ */ jsxs("p", { role: "status", className: "text-xs text-muted-foreground", children: [
407
+ !visible || !inView ? t("preview.hidden") : busy ? t("preview.loading") : running ? t("preview.running") : t("preview.stopped"),
408
+ frame && ` \xB7 ${t(frame.captured ? "preview.age" : "preview.receivedAge", { seconds: Math.max(0, Math.floor((now - frame.at) / 1e3)) })}`,
409
+ frame?.source && ` \xB7 ${t("preview.source", { source: frame.source })}`
410
+ ] }),
411
+ error && /* @__PURE__ */ jsx("p", { role: "alert", className: "text-sm text-destructive", children: t("preview.failed", { error }) })
412
+ ] });
413
+ }
414
+ function parseIosMediaCapabilities(value) {
415
+ if (!value || typeof value !== "object") return null;
416
+ const row = value;
417
+ if (row.webrtc_video !== true || typeof row.generation !== "string" || !row.generation.trim()) return null;
418
+ return {
419
+ webrtc_video: true,
420
+ generation: row.generation,
421
+ control: row.control === true,
422
+ audio: row.audio === true,
423
+ control_commands: Array.isArray(row.control_commands) ? row.control_commands.filter((v) => typeof v === "string") : []
424
+ };
425
+ }
426
+ function useIosMediaCapabilities(deviceId, supplied, visible) {
427
+ const client = useClient();
428
+ const [observed, setObserved] = useState(null);
429
+ useEffect(() => {
430
+ if (supplied !== void 0) return;
431
+ if (!visible) {
432
+ setObserved(null);
433
+ return;
434
+ }
435
+ let active = true;
436
+ let timer;
437
+ let controller;
438
+ const check = async () => {
439
+ controller = new AbortController();
440
+ const deadline = setTimeout(() => controller?.abort(), 15e3);
441
+ try {
442
+ const rows = await client.devices.list({ signal: controller.signal });
443
+ const device = rows.find((row) => row.external_id === deviceId || row.id === deviceId);
444
+ if (active) setObserved(device?.online === true ? parseIosMediaCapabilities(device.meta?.ios_media) : null);
445
+ } catch {
446
+ if (active) setObserved(null);
447
+ } finally {
448
+ clearTimeout(deadline);
449
+ if (active) timer = setTimeout(() => void check(), 1e4);
450
+ }
451
+ };
452
+ void check();
453
+ return () => {
454
+ active = false;
455
+ clearTimeout(timer);
456
+ controller?.abort();
457
+ };
458
+ }, [client, deviceId, supplied, visible]);
459
+ return supplied === void 0 ? observed : parseIosMediaCapabilities(supplied);
460
+ }
461
+ function IosMediaSurface(props) {
462
+ const t = useAixT();
463
+ const [mode, setMode] = useState(props.iosMedia === "screenshot" ? "screenshot" : "video");
464
+ const [visible, setVisible] = useState(() => typeof document === "undefined" || !document.hidden);
465
+ const [inView, setInView] = useState(true);
466
+ const [failure, setFailure] = useState(null);
467
+ const [attempt, setAttempt] = useState(0);
468
+ const container = useRef(null);
469
+ const caps = useIosMediaCapabilities(props.deviceId, props.iosMediaCapabilities, visible && inView);
470
+ useEffect(() => {
471
+ setMode(props.iosMedia === "screenshot" ? "screenshot" : "video");
472
+ }, [props.iosMedia]);
473
+ useEffect(() => {
474
+ const update = () => setVisible(!document.hidden);
475
+ document.addEventListener("visibilitychange", update);
476
+ const observer = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => setInView(entries.some((e) => e.isIntersecting)));
477
+ if (container.current) observer?.observe(container.current);
478
+ return () => {
479
+ document.removeEventListener("visibilitychange", update);
480
+ observer?.disconnect();
481
+ };
482
+ }, []);
483
+ const video = mode === "video" && caps && failure?.generation !== caps.generation;
484
+ const fail = useCallback((reason) => {
485
+ if (caps) setFailure({ generation: caps.generation, reason });
486
+ }, [caps?.generation]);
487
+ return /* @__PURE__ */ jsxs("div", { ref: container, className: `flex min-h-0 flex-1 flex-col gap-2 ${props.className ?? ""}`, children: [
488
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-2", role: "group", "aria-label": t("iosVideo.mode"), children: [
489
+ /* @__PURE__ */ jsx(
490
+ Button,
491
+ {
492
+ size: "sm",
493
+ className: "min-h-11",
494
+ variant: video ? "primary" : "secondary",
495
+ disabled: !caps,
496
+ "aria-pressed": !!video,
497
+ onClick: () => {
498
+ setMode("video");
499
+ setFailure(null);
500
+ setAttempt((value) => value + 1);
501
+ },
502
+ children: t(failure && caps && failure.generation === caps.generation ? "iosVideo.retry" : "iosVideo.video")
503
+ }
504
+ ),
505
+ /* @__PURE__ */ jsx(Button, { size: "sm", className: "min-h-11", variant: !video ? "primary" : "secondary", "aria-pressed": !video, onClick: () => setMode("screenshot"), children: t("iosVideo.screenshot") })
506
+ ] }),
507
+ video ? visible && inView ? /* @__PURE__ */ jsx(IosVideoViewer, { ...props, caps, onFailure: fail }, `${props.deviceId}:${caps.generation}:${attempt}`) : /* @__PURE__ */ jsx("p", { role: "status", className: "text-sm text-muted-foreground", children: t("iosVideo.hidden") }) : /* @__PURE__ */ jsxs(Fragment, { children: [
508
+ /* @__PURE__ */ jsx("p", { role: "status", className: "text-xs text-muted-foreground", children: failure && caps && failure.generation === caps.generation ? t("iosVideo.fallback", { reason: t(`iosVideo.reason.${failure.reason}`) }) : !caps ? t("iosVideo.unavailable") : t("iosVideo.selectedScreenshot") }),
509
+ /* @__PURE__ */ jsx(IosScreenshotPreview, { ...props })
510
+ ] })
511
+ ] });
512
+ }
513
+ var IOS_KEYS = /* @__PURE__ */ new Set(["enter", "backspace", "delete", "tab", "escape", "up", "down", "left", "right", "space", "home"]);
514
+ var IOS_COMMANDS = /* @__PURE__ */ new Set(["tap", "swipe", "text", "home", "key"]);
515
+ function IosVideoViewer({ deviceId, onSize, videoAspect, caps, onFailure }) {
516
+ const t = useAixT();
517
+ const { stream, error, connectionState, controlReady, session } = useMirror(deviceId);
518
+ const [size, setSize] = useState({ width: 1080, height: 2340 });
519
+ const [hasFrame, setHasFrame] = useState(false);
520
+ const [text, setText] = useState("");
521
+ const [inputError, setInputError] = useState(false);
522
+ const failureRef = useRef(onFailure);
523
+ failureRef.current = onFailure;
524
+ useEffect(() => {
525
+ setHasFrame(false);
526
+ }, [stream]);
527
+ useEffect(() => {
528
+ if (hasFrame) return;
529
+ const timeout = setTimeout(() => failureRef.current("first_frame_timeout"), 2e4);
530
+ return () => clearTimeout(timeout);
531
+ }, [hasFrame]);
532
+ useEffect(() => {
533
+ if (error) failureRef.current("connection_error");
534
+ else if (["disconnected", "failed", "closed"].includes(connectionState)) failureRef.current("connection_lost");
535
+ }, [error, connectionState]);
536
+ useEffect(() => {
537
+ const tracks = stream?.getVideoTracks() ?? [];
538
+ const ended = () => failureRef.current("video_ended");
539
+ if (tracks.some((track) => track.readyState === "ended")) ended();
540
+ tracks.forEach((track) => track.addEventListener?.("ended", ended));
541
+ return () => tracks.forEach((track) => track.removeEventListener?.("ended", ended));
542
+ }, [stream]);
543
+ const canControl = hasFrame && caps.control && caps.control_commands.some((command) => IOS_COMMANDS.has(command)) && controlReady && connectionState === "connected";
544
+ const input = useCallback((message) => {
545
+ if (!canControl || !session?.controlReady || !IOS_COMMANDS.has(message.t) || !caps.control_commands.includes(message.t)) return;
546
+ if (message.t === "key" && !IOS_KEYS.has(message.code)) return;
547
+ try {
548
+ session.sendInput(message);
549
+ setInputError(false);
550
+ } catch {
551
+ setInputError(true);
552
+ }
553
+ }, [canControl, session, caps.control_commands]);
554
+ const report = (value) => {
555
+ setSize(value);
556
+ onSize?.(value);
557
+ };
558
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
559
+ /* @__PURE__ */ jsxs("p", { role: "status", className: "text-xs text-muted-foreground", children: [
560
+ t(!hasFrame ? "iosVideo.connecting" : canControl ? "iosVideo.controlReady" : "iosVideo.readOnly"),
561
+ " \xB7 ",
562
+ t("iosVideo.silent")
563
+ ] }),
564
+ /* @__PURE__ */ jsxs("div", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden rounded-md bg-secondary", style: videoAspect ? { aspectRatio: videoAspect } : { minHeight: 160 }, children: [
565
+ /* @__PURE__ */ jsx(
566
+ MirrorView,
567
+ {
568
+ stream,
569
+ deviceSize: size,
570
+ onInput: canControl ? input : void 0,
571
+ keyboard: canControl && (caps.control_commands.includes("key") || caps.control_commands.includes("text")),
572
+ autoFocus: false,
573
+ continuousTouch: false,
574
+ volume: 0,
575
+ onFirstFrame: (value) => {
576
+ report(value);
577
+ setHasFrame(true);
578
+ },
579
+ onResize: report,
580
+ className: "h-full w-full"
581
+ },
582
+ canControl ? "control" : "view"
583
+ ),
584
+ !hasFrame && /* @__PURE__ */ jsx("p", { className: "pointer-events-none absolute inset-0 flex items-center justify-center p-4 text-center text-sm text-muted-foreground", children: t("iosVideo.connecting") })
585
+ ] }),
586
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
587
+ /* @__PURE__ */ jsx(Button, { size: "sm", className: "min-h-11", disabled: !canControl || !caps.control_commands.includes("home"), onClick: () => input({ t: "home" }), children: "Home" }),
588
+ /* @__PURE__ */ jsxs("label", { className: "flex min-w-0 flex-1 items-center gap-2 text-xs", children: [
589
+ t("iosVideo.text"),
590
+ /* @__PURE__ */ jsx("input", { className: "min-h-11 min-w-0 flex-1 rounded border border-border bg-background px-2 text-sm", value: text, disabled: !canControl || !caps.control_commands.includes("text"), onChange: (event) => setText(event.target.value) })
591
+ ] }),
592
+ /* @__PURE__ */ jsx(Button, { size: "sm", className: "min-h-11", disabled: !canControl || !caps.control_commands.includes("text") || !text, onClick: () => input({ t: "text", value: text }), children: t("iosVideo.send") })
593
+ ] }),
594
+ inputError && /* @__PURE__ */ jsx("p", { role: "alert", className: "text-sm text-destructive", children: t("iosVideo.inputUnknown") })
595
+ ] });
596
+ }
597
+ function useClipboardSync(deviceId, active) {
598
+ const client = useClient();
599
+ const [error, setError] = useState(null);
600
+ const [conflict, setConflict] = useState(false);
601
+ const resolveRef = useRef(() => {
602
+ });
603
+ useEffect(() => {
604
+ setError(null);
605
+ setConflict(false);
606
+ if (!active) return;
607
+ let stopped = false;
608
+ let busy = false;
609
+ let pending2 = false;
610
+ let generation = 0;
611
+ let preferred;
612
+ let copyVersion = 0;
613
+ let observedCopyVersion = 0;
614
+ let timer;
615
+ let local;
616
+ let remote;
617
+ const visible = () => !stopped && document.hasFocus() && document.visibilityState !== "hidden";
618
+ const poll = async () => {
619
+ if (busy) {
620
+ pending2 = true;
621
+ return;
622
+ }
623
+ busy = true;
624
+ const choice = preferred;
625
+ const observedVersion = copyVersion;
626
+ preferred = void 0;
627
+ clearTimeout(timer);
628
+ try {
629
+ if (!visible()) return;
630
+ if (!navigator.clipboard?.readText) throw new Error("\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u526A\u8D34\u677F\uFF0C\u8BF7\u4F7F\u7528 HTTPS \u5E76\u5141\u8BB8\u526A\u8D34\u677F\u6743\u9650");
631
+ const version = generation;
632
+ const host = await navigator.clipboard.readText();
633
+ if (!visible() || version !== generation) return;
634
+ const device = await client.devices.op(deviceId, { op: "get_clipboard" });
635
+ if (!visible() || version !== generation) return;
636
+ const latest = await navigator.clipboard.readText();
637
+ if (!visible() || version !== generation || latest !== host) {
638
+ pending2 = true;
639
+ return;
640
+ }
641
+ if (local === void 0 || remote === void 0) {
642
+ local = host;
643
+ remote = device.text;
644
+ observedCopyVersion = observedVersion;
645
+ return;
646
+ }
647
+ const selected = choice && choice.local === host && choice.remote === device.text && choice.copyVersion === copyVersion ? choice.side : void 0;
648
+ const ambiguousCopy = copyVersion !== observedCopyVersion && host === local && selected === void 0;
649
+ const hostChanged = selected === "local" || selected !== "device" && host !== local;
650
+ const deviceChanged = selected === "device" || selected !== "local" && device.text !== remote;
651
+ if (host === device.text) {
652
+ local = remote = host;
653
+ } else if (hostChanged && deviceChanged || ambiguousCopy) {
654
+ local = host;
655
+ remote = device.text;
656
+ observedCopyVersion = observedVersion;
657
+ setConflict(true);
658
+ throw new Error("\u4E24\u7AEF\u540C\u65F6\u590D\u5236\uFF0C\u65E0\u6CD5\u5224\u5B9A\u5148\u540E\uFF1B\u8BF7\u9009\u62E9\u9700\u8981\u4FDD\u7559\u7684\u5185\u5BB9");
659
+ } else if (hostChanged) {
660
+ await client.devices.op(deviceId, { op: "set_clipboard", text: host, expected_text: device.text });
661
+ if (!visible()) return;
662
+ local = remote = host;
663
+ } else if (deviceChanged) {
664
+ await navigator.clipboard.writeText(device.text);
665
+ if (!visible()) return;
666
+ local = remote = device.text;
667
+ }
668
+ if (host === device.text || hostChanged || deviceChanged) {
669
+ observedCopyVersion = observedVersion;
670
+ if (!stopped) {
671
+ setError(null);
672
+ setConflict(false);
673
+ }
674
+ }
675
+ } catch (e) {
676
+ if (!stopped) setError(e instanceof Error ? e.message : String(e));
677
+ } finally {
678
+ busy = false;
679
+ if (!stopped) {
680
+ timer = setTimeout(poll, pending2 ? 0 : 700);
681
+ pending2 = false;
682
+ }
683
+ }
684
+ };
685
+ resolveRef.current = (side) => {
686
+ if (local === void 0 || remote === void 0) return;
687
+ preferred = { side, local, remote, copyVersion: observedCopyVersion };
688
+ void poll();
689
+ };
690
+ const changed = () => {
691
+ generation++;
692
+ void poll();
693
+ };
694
+ const copied = () => {
695
+ copyVersion++;
696
+ changed();
697
+ };
698
+ const focus = () => {
699
+ if (visible()) changed();
700
+ };
701
+ navigator.clipboard?.addEventListener?.("clipboardchange", copied);
702
+ window.addEventListener("focus", focus);
703
+ document.addEventListener("visibilitychange", focus);
704
+ void poll();
705
+ return () => {
706
+ stopped = true;
707
+ resolveRef.current = () => {
708
+ };
709
+ clearTimeout(timer);
710
+ navigator.clipboard?.removeEventListener?.("clipboardchange", copied);
711
+ window.removeEventListener("focus", focus);
712
+ document.removeEventListener("visibilitychange", focus);
713
+ };
714
+ }, [deviceId, active, client]);
715
+ return { error, conflict, resolveConflict: (side) => resolveRef.current(side) };
716
+ }
717
+
718
+ // src/core/quality-auto.ts
719
+ var RTT_HIGH = 0.15;
720
+ var RTT_LOW = 0.04;
721
+ var HYSTERESIS = 0.03;
722
+ function pickAutoProfile(rtt, current) {
723
+ if (current === "low_latency") {
724
+ if (rtt >= RTT_HIGH - HYSTERESIS) return "low_latency";
725
+ return rtt < RTT_LOW ? "high_quality" : "balanced";
726
+ }
727
+ if (current === "high_quality") {
728
+ if (rtt <= RTT_LOW + HYSTERESIS) return "high_quality";
729
+ return rtt > RTT_HIGH ? "low_latency" : "balanced";
730
+ }
731
+ if (rtt > RTT_HIGH) return "low_latency";
732
+ if (rtt < RTT_LOW) return "high_quality";
733
+ return "balanced";
734
+ }
735
+ var PROFILE_LABELS = {
736
+ balanced: "\u5E73\u8861",
737
+ low_latency: "\u4F4E\u5EF6\u8FDF",
738
+ high_quality: "\u9AD8\u753B\u8D28"
739
+ };
740
+ var DEFAULT_SIZE = { width: 1080, height: 2340 };
741
+ var AUTO_QUALITY_FIRST_CHECK_MS = 2e3;
742
+ var AUTO_QUALITY_INTERVAL_MS = 8e3;
743
+ var AUTO_QUALITY_MIN_SWITCH_INTERVAL_MS = 15e3;
744
+ function MirrorSurface(props) {
745
+ if (props.platform === "ios") return /* @__PURE__ */ jsx(IosMediaSurface, { ...props }, props.deviceId);
746
+ return /* @__PURE__ */ jsx(WebRtcMirrorSurface, { ...props });
747
+ }
748
+ function WebRtcMirrorSurface({ deviceId, platform = "android", onSize, videoAspect, shortcutBar, className }) {
749
+ const { stream, error, sendInput, setQuality, session } = useMirror(deviceId);
750
+ const [pasteContent, setPasteContent] = useState("");
751
+ const { error: clipboardError, conflict: clipboardConflict, resolveConflict } = useClipboardSync(deviceId, !!stream);
752
+ const [size, setSize] = useState(DEFAULT_SIZE);
753
+ const [hasFrame, setHasFrame] = useState(false);
754
+ useEffect(() => {
755
+ setHasFrame(false);
756
+ }, [deviceId, stream]);
757
+ useEffect(() => {
758
+ setPasteContent("");
759
+ setSize(DEFAULT_SIZE);
760
+ onSize?.(DEFAULT_SIZE);
761
+ }, [deviceId, onSize]);
762
+ const [profile, setProfile] = useState("balanced");
763
+ const manualRef = useRef(false);
764
+ const changeProfile = useCallback(
765
+ (p, manual) => {
766
+ if (manual) manualRef.current = true;
767
+ setProfile(p);
768
+ setQuality(p);
769
+ },
770
+ [setQuality]
771
+ );
772
+ const landscape = size.width > size.height;
773
+ const [volume, setVolume] = useState(0);
774
+ const audioEnabled = volume > 0;
775
+ const audioEnabledRef = useRef(false);
776
+ useEffect(() => {
777
+ if (stream && audioEnabled) {
778
+ sendInput({ t: "audio", enabled: true });
779
+ audioEnabledRef.current = true;
780
+ } else if (!audioEnabled && audioEnabledRef.current) {
781
+ sendInput({ t: "audio", enabled: false });
782
+ audioEnabledRef.current = false;
783
+ }
784
+ }, [stream, audioEnabled, sendInput]);
785
+ useEffect(() => () => {
786
+ if (audioEnabledRef.current) sendInput({ t: "audio", enabled: false });
787
+ audioEnabledRef.current = false;
788
+ }, [sendInput]);
789
+ const [hasAudio, setHasAudio] = useState(false);
790
+ useEffect(() => {
791
+ const update = () => setHasAudio(!!stream?.getAudioTracks().some((t) => t.readyState === "live"));
792
+ update();
793
+ stream?.addEventListener("addtrack", update);
794
+ stream?.addEventListener("removetrack", update);
795
+ return () => {
796
+ stream?.removeEventListener("addtrack", update);
797
+ stream?.removeEventListener("removetrack", update);
798
+ };
799
+ }, [stream]);
800
+ const toggleOrientation = useCallback(() => {
801
+ sendInput({ t: "rotate", orientation: landscape ? "portrait" : "landscape" });
802
+ }, [sendInput, landscape]);
803
+ useEffect(() => {
804
+ manualRef.current = false;
805
+ setProfile("balanced");
806
+ setVolume(0);
807
+ }, [deviceId]);
808
+ const profileRef = useRef(profile);
809
+ useEffect(() => {
810
+ profileRef.current = profile;
811
+ }, [profile]);
812
+ useEffect(() => {
813
+ if (!stream || !session) return;
814
+ let cancelled = false;
815
+ let lastSwitchAt = 0;
816
+ const check = async () => {
817
+ if (cancelled || manualRef.current) return;
818
+ const rtt = await session.currentRtt();
819
+ if (cancelled || rtt === null || manualRef.current) return;
820
+ const next = pickAutoProfile(rtt, profileRef.current);
821
+ if (next === profileRef.current) return;
822
+ const now = Date.now();
823
+ if (now - lastSwitchAt < AUTO_QUALITY_MIN_SWITCH_INTERVAL_MS) return;
824
+ lastSwitchAt = now;
825
+ changeProfile(next, false);
826
+ };
827
+ const first = setTimeout(check, AUTO_QUALITY_FIRST_CHECK_MS);
828
+ const interval = setInterval(check, AUTO_QUALITY_INTERVAL_MS);
829
+ return () => {
830
+ cancelled = true;
831
+ clearTimeout(first);
832
+ clearInterval(interval);
833
+ };
834
+ }, [stream, session, changeProfile]);
835
+ const reportSize = useCallback(
836
+ (real) => {
837
+ if (real.width > 0 && real.height > 0) {
838
+ setSize(real);
839
+ onSize?.(real);
840
+ }
841
+ },
842
+ [onSize]
843
+ );
844
+ const handleFirstFrame = useCallback(
845
+ (real) => {
846
+ setHasFrame(true);
847
+ reportSize(real);
848
+ },
849
+ [reportSize]
850
+ );
851
+ return /* @__PURE__ */ jsxs("div", { className: `flex min-h-0 flex-col items-center gap-2 ${className ?? ""}`, children: [
852
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 w-full flex-1 items-stretch justify-center gap-2", children: [
853
+ /* @__PURE__ */ jsxs("aside", { "aria-label": "\u955C\u50CF\u547D\u4EE4\u680F", className: "flex w-40 shrink-0 flex-col gap-3 overflow-y-auto rounded-lg border border-border bg-background p-2 text-foreground", children: [
854
+ /* @__PURE__ */ jsx(MirrorActions, { deviceId, stream, ready: hasFrame, platform }),
855
+ shortcutBar,
856
+ /* @__PURE__ */ jsxs("form", { className: "flex flex-col gap-2", onSubmit: (e) => {
857
+ e.preventDefault();
858
+ if (stream && pasteContent.trim()) sendInput({ t: "text", value: pasteContent });
859
+ }, children: [
860
+ /* @__PURE__ */ jsxs("label", { className: "text-xs font-medium", children: [
861
+ "\u547D\u4EE4 / \u7C98\u8D34\u5185\u5BB9",
862
+ /* @__PURE__ */ jsx(
863
+ "textarea",
864
+ {
865
+ "aria-label": "\u547D\u4EE4 / \u7C98\u8D34\u5185\u5BB9",
866
+ value: pasteContent,
867
+ onChange: (e) => setPasteContent(e.target.value),
868
+ placeholder: "\u8F93\u5165\u6216\u7C98\u8D34\u5185\u5BB9",
869
+ rows: 5,
870
+ className: "mt-2 w-full resize-y rounded border border-border bg-secondary p-2 text-xs"
871
+ }
872
+ )
873
+ ] }),
874
+ /* @__PURE__ */ jsx("button", { type: "submit", disabled: !stream || !pasteContent.trim(), className: "rounded bg-primary px-2 py-2 text-xs text-primary-foreground disabled:opacity-40", children: "\u7C98\u8D34\u5230\u8BBE\u5907" })
875
+ ] })
876
+ ] }),
877
+ /* @__PURE__ */ jsxs(
878
+ "div",
879
+ {
880
+ className: `relative min-h-0 overflow-hidden rounded-lg ${videoAspect ? "h-full" : "h-full flex-1"}`,
881
+ style: videoAspect ? { aspectRatio: String(videoAspect) } : void 0,
882
+ children: [
883
+ stream && /* @__PURE__ */ jsx(
884
+ MirrorView,
885
+ {
886
+ stream,
887
+ volume: volume / 100,
888
+ deviceSize: size,
889
+ onInput: sendInput,
890
+ onFirstFrame: handleFirstFrame,
891
+ onResize: reportSize,
892
+ continuousTouch: platform === "android",
893
+ className: "h-full w-full"
894
+ }
895
+ ),
896
+ (!stream || !hasFrame) && /* @__PURE__ */ jsx("div", { className: "absolute inset-0", children: /* @__PURE__ */ jsx(
897
+ DeviceBootSplash,
898
+ {
899
+ error: error ? error.message : null,
900
+ platform,
901
+ className: "rounded-lg"
902
+ }
903
+ ) })
904
+ ]
905
+ }
906
+ )
907
+ ] }),
908
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-center gap-1 rounded-xl border border-border bg-background px-2 py-1 shadow-lg", children: [
909
+ /* @__PURE__ */ jsx(
910
+ ControlBar,
911
+ {
912
+ platform,
913
+ onBack: platform === "android" ? () => sendInput({ t: "back" }) : void 0,
914
+ onHome: () => sendInput({ t: "home" }),
915
+ onMenu: () => sendInput({ t: "key", code: "app_switch" })
916
+ }
917
+ ),
918
+ /* @__PURE__ */ jsx(Popover, { className: "bottom-full mb-2 !mt-0 !min-w-[140px]", trigger: ({ open, toggle }) => /* @__PURE__ */ jsxs(
919
+ "button",
920
+ {
921
+ type: "button",
922
+ "aria-label": "\u753B\u8D28\u6863\u4F4D",
923
+ "aria-expanded": open,
924
+ "aria-haspopup": "menu",
925
+ onClick: toggle,
926
+ className: "flex h-9 items-center gap-1.5 rounded-md px-2 text-xs text-foreground hover:bg-secondary",
927
+ title: "\u753B\u8D28\u6863\u4F4D",
928
+ children: [
929
+ /* @__PURE__ */ jsx(Settings2, { className: "h-4 w-4" }),
930
+ PROFILE_LABELS[profile]
931
+ ]
932
+ }
933
+ ), children: (close) => /* @__PURE__ */ jsx("div", { role: "menu", "aria-label": "\u9009\u62E9\u753B\u8D28", children: Object.keys(PROFILE_LABELS).map((p) => /* @__PURE__ */ jsxs(
934
+ "button",
935
+ {
936
+ type: "button",
937
+ role: "menuitemradio",
938
+ "aria-checked": profile === p,
939
+ onClick: () => {
940
+ changeProfile(p, true);
941
+ close();
942
+ },
943
+ className: "flex w-full items-center justify-between gap-4 rounded px-2 py-2 text-xs text-foreground hover:bg-secondary",
944
+ children: [
945
+ PROFILE_LABELS[p],
946
+ profile === p && /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" })
947
+ ]
948
+ },
949
+ p
950
+ )) }) }),
951
+ /* @__PURE__ */ jsx(Popover, { className: "bottom-full mb-2 !mt-0 !min-w-0", trigger: ({ open, toggle }) => /* @__PURE__ */ jsx(
952
+ "button",
953
+ {
954
+ type: "button",
955
+ "aria-label": "\u97F3\u91CF",
956
+ "aria-expanded": open,
957
+ "aria-haspopup": "dialog",
958
+ onClick: toggle,
959
+ title: `\u97F3\u91CF ${volume}%`,
960
+ className: "flex h-9 w-9 items-center justify-center rounded-md text-foreground hover:bg-secondary",
961
+ children: volume === 0 ? /* @__PURE__ */ jsx(VolumeX, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Volume2, { className: "h-4 w-4" })
962
+ }
963
+ ), children: () => /* @__PURE__ */ jsxs("div", { role: "dialog", "aria-label": "\u97F3\u91CF\u8C03\u8282", className: "flex flex-col items-center gap-2", children: [
964
+ /* @__PURE__ */ jsx(
965
+ "input",
966
+ {
967
+ type: "range",
968
+ "aria-label": "\u64AD\u653E\u97F3\u91CF",
969
+ min: 0,
970
+ max: 100,
971
+ value: volume,
972
+ style: { writingMode: "vertical-lr", direction: "rtl", width: 24, height: 112 },
973
+ disabled: !stream,
974
+ onChange: (e) => {
975
+ const next = Number(e.target.value);
976
+ setVolume(next);
977
+ }
978
+ }
979
+ ),
980
+ /* @__PURE__ */ jsxs("span", { className: "whitespace-nowrap text-xs text-foreground", children: [
981
+ volume,
982
+ "%"
983
+ ] }),
984
+ volume > 0 && !hasAudio && /* @__PURE__ */ jsx("span", { role: "status", className: "whitespace-nowrap text-xs text-muted-foreground", children: "\u7B49\u5F85\u97F3\u9891\u6D41" })
985
+ ] }) }),
986
+ clipboardConflict && /* @__PURE__ */ jsxs(Fragment, { children: [
987
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => resolveConflict("local"), className: "text-xs underline", children: "\u4FDD\u7559\u672C\u673A\u526A\u8D34\u677F" }),
988
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => resolveConflict("device"), className: "text-xs underline", children: "\u4FDD\u7559\u8BBE\u5907\u526A\u8D34\u677F" })
989
+ ] }),
990
+ clipboardError && /* @__PURE__ */ jsxs("span", { role: "status", className: "text-xs text-destructive", children: [
991
+ "\u526A\u8D34\u677F\u540C\u6B65\u5931\u8D25\uFF1A",
992
+ clipboardError
993
+ ] }),
994
+ platform === "android" && /* @__PURE__ */ jsx(
995
+ "button",
996
+ {
997
+ type: "button",
998
+ onClick: toggleOrientation,
999
+ "aria-label": landscape ? "\u5207\u56DE\u7AD6\u5C4F" : "\u5207\u6362\u6A2A\u5C4F",
1000
+ title: landscape ? "\u5207\u56DE\u7AD6\u5C4F" : "\u5207\u6362\u6A2A\u5C4F",
1001
+ "aria-pressed": landscape,
1002
+ className: `flex h-9 w-9 items-center justify-center rounded-md text-xs outline-none hover:bg-card ${landscape ? "bg-primary/15 text-primary" : "bg-secondary text-foreground"}`,
1003
+ children: /* @__PURE__ */ jsx(RotateCw, { className: "h-3.5 w-3.5" })
1004
+ }
1005
+ )
1006
+ ] })
1007
+ ] });
1008
+ }
1009
+ function DeviceMirror({ deviceId, deviceName, platform = "android", shortcutBar, onClose }) {
1010
+ const open = deviceId !== null;
1011
+ const client = useClient();
1012
+ const { data: devices } = useDevices();
1013
+ const [size, setSize] = useState({ width: 1080, height: 2340 });
1014
+ const overlayRef = useRef(null);
1015
+ const [fullscreen, setFullscreen] = useState(false);
1016
+ const sleepTimeoutMin = useMemo(() => {
1017
+ if (!deviceId) return 30;
1018
+ const d = devices?.find((dv) => dv.external_id === deviceId);
1019
+ const v = d?.meta?.sleep_timeout_min;
1020
+ return typeof v === "number" ? v : 30;
1021
+ }, [devices, deviceId]);
1022
+ const lastActivityRef = useRef(Date.now());
1023
+ const resetActivity = useCallback(() => {
1024
+ lastActivityRef.current = Date.now();
1025
+ }, []);
1026
+ useEffect(() => {
1027
+ if (!open || !deviceId || sleepTimeoutMin === 0) return;
1028
+ const ms = sleepTimeoutMin * 60 * 1e3;
1029
+ const id = setInterval(() => {
1030
+ if (Date.now() - lastActivityRef.current >= ms) {
1031
+ void client.devices.sleep(deviceId).then(() => onClose()).catch(() => {
1032
+ });
1033
+ clearInterval(id);
1034
+ }
1035
+ }, 1e4);
1036
+ return () => clearInterval(id);
1037
+ }, [open, deviceId, sleepTimeoutMin, onClose, client]);
1038
+ const enterFullscreen = useCallback(async () => {
1039
+ const el = overlayRef.current;
1040
+ if (!el) return;
1041
+ try {
1042
+ if (el.requestFullscreen) await el.requestFullscreen();
1043
+ else if (el.webkitRequestFullscreen) await el.webkitRequestFullscreen();
1044
+ } catch {
1045
+ }
1046
+ }, []);
1047
+ const exitFullscreen = useCallback(async () => {
1048
+ const doc = document;
1049
+ try {
1050
+ if (doc.fullscreenElement && doc.exitFullscreen) await doc.exitFullscreen();
1051
+ else if (doc.webkitFullscreenElement && doc.webkitExitFullscreen) await doc.webkitExitFullscreen();
1052
+ } catch {
1053
+ }
1054
+ }, []);
1055
+ const toggleFullscreen = useCallback(() => {
1056
+ if (fullscreen) void exitFullscreen();
1057
+ else void enterFullscreen();
1058
+ }, [fullscreen, enterFullscreen, exitFullscreen]);
1059
+ useEffect(() => {
1060
+ const onFsChange = () => {
1061
+ const doc = document;
1062
+ const fsEl = doc.fullscreenElement || doc.webkitFullscreenElement || null;
1063
+ setFullscreen(fsEl === overlayRef.current);
1064
+ };
1065
+ document.addEventListener("fullscreenchange", onFsChange);
1066
+ document.addEventListener("webkitfullscreenchange", onFsChange);
1067
+ return () => {
1068
+ document.removeEventListener("fullscreenchange", onFsChange);
1069
+ document.removeEventListener("webkitfullscreenchange", onFsChange);
1070
+ };
1071
+ }, []);
1072
+ useEffect(() => {
1073
+ if (!open) return;
1074
+ const onKey = (e) => {
1075
+ resetActivity();
1076
+ if (e.key === "Escape" && !fullscreen) onClose();
1077
+ };
1078
+ window.addEventListener("keydown", onKey);
1079
+ return () => window.removeEventListener("keydown", onKey);
1080
+ }, [open, onClose, resetActivity, fullscreen]);
1081
+ useEffect(() => {
1082
+ if (!open) void exitFullscreen();
1083
+ }, [open, exitFullscreen]);
1084
+ const stop = useCallback((e) => e.stopPropagation(), []);
1085
+ if (!open) return null;
1086
+ const aspect = size.width > 0 && size.height > 0 ? size.width / size.height : 9 / 16;
1087
+ return /* @__PURE__ */ jsx(
1088
+ "div",
1089
+ {
1090
+ ref: overlayRef,
1091
+ className: "fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",
1092
+ onClick: onClose,
1093
+ onMouseMove: resetActivity,
1094
+ onPointerDown: resetActivity,
1095
+ children: /* @__PURE__ */ jsxs(
1096
+ "div",
1097
+ {
1098
+ className: `flex flex-col items-center ${fullscreen ? "h-full w-full gap-1 py-2" : "gap-3"}`,
1099
+ onClick: stop,
1100
+ children: [
1101
+ /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center justify-between gap-3 px-2 text-white/90", children: [
1102
+ /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium truncate max-w-[50vw]", children: [
1103
+ deviceName || deviceId,
1104
+ " \xB7 \u5B9E\u65F6\u955C\u50CF"
1105
+ ] }),
1106
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
1107
+ /* @__PURE__ */ jsx(
1108
+ "button",
1109
+ {
1110
+ type: "button",
1111
+ "aria-label": fullscreen ? "\u9000\u51FA\u5168\u5C4F" : "\u5168\u5C4F",
1112
+ title: fullscreen ? "\u9000\u51FA\u5168\u5C4F" : "\u5168\u5C4F",
1113
+ onClick: toggleFullscreen,
1114
+ className: "rounded p-1 hover:bg-white/10",
1115
+ children: fullscreen ? /* @__PURE__ */ jsx(Minimize2, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize2, { className: "h-5 w-5" })
1116
+ }
1117
+ ),
1118
+ /* @__PURE__ */ jsx(
1119
+ "button",
1120
+ {
1121
+ type: "button",
1122
+ "aria-label": "\u5173\u95ED",
1123
+ onClick: onClose,
1124
+ className: "rounded p-1 hover:bg-white/10",
1125
+ children: /* @__PURE__ */ jsx(X, { className: "h-5 w-5" })
1126
+ }
1127
+ )
1128
+ ] })
1129
+ ] }),
1130
+ /* @__PURE__ */ jsx("div", { className: `min-h-0 ${fullscreen ? "flex-1" : ""}`, style: fullscreen ? void 0 : { height: "80vh" }, children: /* @__PURE__ */ jsx(
1131
+ MirrorSurface,
1132
+ {
1133
+ deviceId,
1134
+ platform,
1135
+ onSize: setSize,
1136
+ videoAspect: aspect,
1137
+ shortcutBar,
1138
+ className: "h-full"
1139
+ }
1140
+ ) })
1141
+ ]
1142
+ }
1143
+ )
1144
+ }
1145
+ );
1146
+ }
1147
+
1148
+ export { DeviceBootSplash, DeviceMirror, MirrorSurface, parseIosMediaCapabilities, requestPreviewFrame };