@aixnn/aixautots 0.6.1 → 0.6.4

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,845 @@
1
+ import { MirrorView, ControlBar } from './chunk-E7WMHM63.js';
2
+ import { useMirror, useDevices } from './chunk-Q63FQ7B5.js';
3
+ import { Popover } from './chunk-H37NHOYU.js';
4
+ import { useClient } from './chunk-A5VNENHD.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
+ function useClipboardSync(deviceId, active) {
306
+ const client = useClient();
307
+ const [error, setError] = useState(null);
308
+ const [conflict, setConflict] = useState(false);
309
+ const resolveRef = useRef(() => {
310
+ });
311
+ useEffect(() => {
312
+ setError(null);
313
+ setConflict(false);
314
+ if (!active) return;
315
+ let stopped = false;
316
+ let busy = false;
317
+ let pending = false;
318
+ let generation = 0;
319
+ let preferred;
320
+ let copyVersion = 0;
321
+ let observedCopyVersion = 0;
322
+ let timer;
323
+ let local;
324
+ let remote;
325
+ const visible = () => !stopped && document.hasFocus() && document.visibilityState !== "hidden";
326
+ const poll = async () => {
327
+ if (busy) {
328
+ pending = true;
329
+ return;
330
+ }
331
+ busy = true;
332
+ const choice = preferred;
333
+ const observedVersion = copyVersion;
334
+ preferred = void 0;
335
+ clearTimeout(timer);
336
+ try {
337
+ if (!visible()) return;
338
+ 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");
339
+ const version = generation;
340
+ const host = await navigator.clipboard.readText();
341
+ if (!visible() || version !== generation) return;
342
+ const device = await client.devices.op(deviceId, { op: "get_clipboard" });
343
+ if (!visible() || version !== generation) return;
344
+ const latest = await navigator.clipboard.readText();
345
+ if (!visible() || version !== generation || latest !== host) {
346
+ pending = true;
347
+ return;
348
+ }
349
+ if (local === void 0 || remote === void 0) {
350
+ local = host;
351
+ remote = device.text;
352
+ observedCopyVersion = observedVersion;
353
+ return;
354
+ }
355
+ const selected = choice && choice.local === host && choice.remote === device.text && choice.copyVersion === copyVersion ? choice.side : void 0;
356
+ const ambiguousCopy = copyVersion !== observedCopyVersion && host === local && selected === void 0;
357
+ const hostChanged = selected === "local" || selected !== "device" && host !== local;
358
+ const deviceChanged = selected === "device" || selected !== "local" && device.text !== remote;
359
+ if (host === device.text) {
360
+ local = remote = host;
361
+ } else if (hostChanged && deviceChanged || ambiguousCopy) {
362
+ local = host;
363
+ remote = device.text;
364
+ observedCopyVersion = observedVersion;
365
+ setConflict(true);
366
+ 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");
367
+ } else if (hostChanged) {
368
+ await client.devices.op(deviceId, { op: "set_clipboard", text: host, expected_text: device.text });
369
+ if (!visible()) return;
370
+ local = remote = host;
371
+ } else if (deviceChanged) {
372
+ await navigator.clipboard.writeText(device.text);
373
+ if (!visible()) return;
374
+ local = remote = device.text;
375
+ }
376
+ if (host === device.text || hostChanged || deviceChanged) {
377
+ observedCopyVersion = observedVersion;
378
+ if (!stopped) {
379
+ setError(null);
380
+ setConflict(false);
381
+ }
382
+ }
383
+ } catch (e) {
384
+ if (!stopped) setError(e instanceof Error ? e.message : String(e));
385
+ } finally {
386
+ busy = false;
387
+ if (!stopped) {
388
+ timer = setTimeout(poll, pending ? 0 : 700);
389
+ pending = false;
390
+ }
391
+ }
392
+ };
393
+ resolveRef.current = (side) => {
394
+ if (local === void 0 || remote === void 0) return;
395
+ preferred = { side, local, remote, copyVersion: observedCopyVersion };
396
+ void poll();
397
+ };
398
+ const changed = () => {
399
+ generation++;
400
+ void poll();
401
+ };
402
+ const copied = () => {
403
+ copyVersion++;
404
+ changed();
405
+ };
406
+ const focus = () => {
407
+ if (visible()) changed();
408
+ };
409
+ navigator.clipboard?.addEventListener?.("clipboardchange", copied);
410
+ window.addEventListener("focus", focus);
411
+ document.addEventListener("visibilitychange", focus);
412
+ void poll();
413
+ return () => {
414
+ stopped = true;
415
+ resolveRef.current = () => {
416
+ };
417
+ clearTimeout(timer);
418
+ navigator.clipboard?.removeEventListener?.("clipboardchange", copied);
419
+ window.removeEventListener("focus", focus);
420
+ document.removeEventListener("visibilitychange", focus);
421
+ };
422
+ }, [deviceId, active, client]);
423
+ return { error, conflict, resolveConflict: (side) => resolveRef.current(side) };
424
+ }
425
+
426
+ // src/core/quality-auto.ts
427
+ var RTT_HIGH = 0.15;
428
+ var RTT_LOW = 0.04;
429
+ var HYSTERESIS = 0.03;
430
+ function pickAutoProfile(rtt, current) {
431
+ if (current === "low_latency") {
432
+ if (rtt >= RTT_HIGH - HYSTERESIS) return "low_latency";
433
+ return rtt < RTT_LOW ? "high_quality" : "balanced";
434
+ }
435
+ if (current === "high_quality") {
436
+ if (rtt <= RTT_LOW + HYSTERESIS) return "high_quality";
437
+ return rtt > RTT_HIGH ? "low_latency" : "balanced";
438
+ }
439
+ if (rtt > RTT_HIGH) return "low_latency";
440
+ if (rtt < RTT_LOW) return "high_quality";
441
+ return "balanced";
442
+ }
443
+ var PROFILE_LABELS = {
444
+ balanced: "\u5E73\u8861",
445
+ low_latency: "\u4F4E\u5EF6\u8FDF",
446
+ high_quality: "\u9AD8\u753B\u8D28"
447
+ };
448
+ var DEFAULT_SIZE = { width: 1080, height: 2340 };
449
+ var AUTO_QUALITY_FIRST_CHECK_MS = 2e3;
450
+ var AUTO_QUALITY_INTERVAL_MS = 8e3;
451
+ var AUTO_QUALITY_MIN_SWITCH_INTERVAL_MS = 15e3;
452
+ function MirrorSurface({ deviceId, platform = "android", onSize, videoAspect, shortcutBar, className }) {
453
+ const { stream, error, sendInput, setQuality, session } = useMirror(deviceId);
454
+ const [pasteContent, setPasteContent] = useState("");
455
+ const { error: clipboardError, conflict: clipboardConflict, resolveConflict } = useClipboardSync(deviceId, !!stream);
456
+ const [size, setSize] = useState(DEFAULT_SIZE);
457
+ const [hasFrame, setHasFrame] = useState(false);
458
+ useEffect(() => {
459
+ setHasFrame(false);
460
+ setVolume(0);
461
+ }, [deviceId, stream]);
462
+ useEffect(() => {
463
+ setPasteContent("");
464
+ setSize(DEFAULT_SIZE);
465
+ onSize?.(DEFAULT_SIZE);
466
+ }, [deviceId, onSize]);
467
+ const [profile, setProfile] = useState("balanced");
468
+ const manualRef = useRef(false);
469
+ const changeProfile = useCallback(
470
+ (p, manual) => {
471
+ if (manual) manualRef.current = true;
472
+ setProfile(p);
473
+ setQuality(p);
474
+ },
475
+ [setQuality]
476
+ );
477
+ const landscape = size.width > size.height;
478
+ const [volume, setVolume] = useState(0);
479
+ const audioEnabledRef = useRef(false);
480
+ useEffect(() => () => {
481
+ if (audioEnabledRef.current) sendInput({ t: "audio", enabled: false });
482
+ audioEnabledRef.current = false;
483
+ }, [stream, sendInput]);
484
+ const [hasAudio, setHasAudio] = useState(false);
485
+ useEffect(() => {
486
+ const update = () => setHasAudio(!!stream?.getAudioTracks().some((t) => t.readyState === "live"));
487
+ update();
488
+ stream?.addEventListener("addtrack", update);
489
+ stream?.addEventListener("removetrack", update);
490
+ return () => {
491
+ stream?.removeEventListener("addtrack", update);
492
+ stream?.removeEventListener("removetrack", update);
493
+ };
494
+ }, [stream]);
495
+ const toggleOrientation = useCallback(() => {
496
+ sendInput({ t: "rotate", orientation: landscape ? "portrait" : "landscape" });
497
+ }, [sendInput, landscape]);
498
+ useEffect(() => {
499
+ manualRef.current = false;
500
+ setProfile("balanced");
501
+ setVolume(0);
502
+ }, [deviceId]);
503
+ const profileRef = useRef(profile);
504
+ useEffect(() => {
505
+ profileRef.current = profile;
506
+ }, [profile]);
507
+ useEffect(() => {
508
+ if (!stream || !session) return;
509
+ let cancelled = false;
510
+ let lastSwitchAt = 0;
511
+ const check = async () => {
512
+ if (cancelled || manualRef.current) return;
513
+ const rtt = await session.currentRtt();
514
+ if (cancelled || rtt === null || manualRef.current) return;
515
+ const next = pickAutoProfile(rtt, profileRef.current);
516
+ if (next === profileRef.current) return;
517
+ const now = Date.now();
518
+ if (now - lastSwitchAt < AUTO_QUALITY_MIN_SWITCH_INTERVAL_MS) return;
519
+ lastSwitchAt = now;
520
+ changeProfile(next, false);
521
+ };
522
+ const first = setTimeout(check, AUTO_QUALITY_FIRST_CHECK_MS);
523
+ const interval = setInterval(check, AUTO_QUALITY_INTERVAL_MS);
524
+ return () => {
525
+ cancelled = true;
526
+ clearTimeout(first);
527
+ clearInterval(interval);
528
+ };
529
+ }, [stream, session, changeProfile]);
530
+ const reportSize = useCallback(
531
+ (real) => {
532
+ if (real.width > 0 && real.height > 0) {
533
+ setSize(real);
534
+ onSize?.(real);
535
+ }
536
+ },
537
+ [onSize]
538
+ );
539
+ const handleFirstFrame = useCallback(
540
+ (real) => {
541
+ setHasFrame(true);
542
+ reportSize(real);
543
+ },
544
+ [reportSize]
545
+ );
546
+ return /* @__PURE__ */ jsxs("div", { className: `flex min-h-0 flex-col items-center gap-2 ${className ?? ""}`, children: [
547
+ /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 w-full flex-1 items-stretch justify-center gap-2", children: [
548
+ /* @__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: [
549
+ /* @__PURE__ */ jsx(MirrorActions, { deviceId, stream, ready: hasFrame, platform }),
550
+ shortcutBar,
551
+ /* @__PURE__ */ jsxs("form", { className: "flex flex-col gap-2", onSubmit: (e) => {
552
+ e.preventDefault();
553
+ if (stream && pasteContent.trim()) sendInput({ t: "text", value: pasteContent });
554
+ }, children: [
555
+ /* @__PURE__ */ jsxs("label", { className: "text-xs font-medium", children: [
556
+ "\u547D\u4EE4 / \u7C98\u8D34\u5185\u5BB9",
557
+ /* @__PURE__ */ jsx(
558
+ "textarea",
559
+ {
560
+ "aria-label": "\u547D\u4EE4 / \u7C98\u8D34\u5185\u5BB9",
561
+ value: pasteContent,
562
+ onChange: (e) => setPasteContent(e.target.value),
563
+ placeholder: "\u8F93\u5165\u6216\u7C98\u8D34\u5185\u5BB9",
564
+ rows: 5,
565
+ className: "mt-2 w-full resize-y rounded border border-border bg-secondary p-2 text-xs"
566
+ }
567
+ )
568
+ ] }),
569
+ /* @__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" })
570
+ ] })
571
+ ] }),
572
+ /* @__PURE__ */ jsxs(
573
+ "div",
574
+ {
575
+ className: `relative min-h-0 overflow-hidden rounded-lg ${videoAspect ? "h-full" : "h-full flex-1"}`,
576
+ style: videoAspect ? { aspectRatio: String(videoAspect) } : void 0,
577
+ children: [
578
+ stream && /* @__PURE__ */ jsx(
579
+ MirrorView,
580
+ {
581
+ stream,
582
+ volume: volume / 100,
583
+ deviceSize: size,
584
+ onInput: sendInput,
585
+ onFirstFrame: handleFirstFrame,
586
+ onResize: reportSize,
587
+ continuousTouch: platform === "android",
588
+ className: "h-full w-full"
589
+ }
590
+ ),
591
+ (!stream || !hasFrame) && /* @__PURE__ */ jsx("div", { className: "absolute inset-0", children: /* @__PURE__ */ jsx(
592
+ DeviceBootSplash,
593
+ {
594
+ error: error ? error.message : null,
595
+ platform,
596
+ className: "rounded-lg"
597
+ }
598
+ ) })
599
+ ]
600
+ }
601
+ )
602
+ ] }),
603
+ /* @__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: [
604
+ /* @__PURE__ */ jsx(
605
+ ControlBar,
606
+ {
607
+ platform,
608
+ onBack: () => sendInput({ t: "back" }),
609
+ onHome: () => sendInput({ t: "home" }),
610
+ onMenu: () => sendInput({ t: "key", code: "app_switch" })
611
+ }
612
+ ),
613
+ /* @__PURE__ */ jsx(Popover, { className: "bottom-full mb-2 !mt-0 !min-w-[140px]", trigger: ({ open, toggle }) => /* @__PURE__ */ jsxs(
614
+ "button",
615
+ {
616
+ type: "button",
617
+ "aria-label": "\u753B\u8D28\u6863\u4F4D",
618
+ "aria-expanded": open,
619
+ "aria-haspopup": "menu",
620
+ onClick: toggle,
621
+ className: "flex h-9 items-center gap-1.5 rounded-md px-2 text-xs text-foreground hover:bg-secondary",
622
+ title: "\u753B\u8D28\u6863\u4F4D",
623
+ children: [
624
+ /* @__PURE__ */ jsx(Settings2, { className: "h-4 w-4" }),
625
+ PROFILE_LABELS[profile]
626
+ ]
627
+ }
628
+ ), children: (close) => /* @__PURE__ */ jsx("div", { role: "menu", "aria-label": "\u9009\u62E9\u753B\u8D28", children: Object.keys(PROFILE_LABELS).map((p) => /* @__PURE__ */ jsxs(
629
+ "button",
630
+ {
631
+ type: "button",
632
+ role: "menuitemradio",
633
+ "aria-checked": profile === p,
634
+ onClick: () => {
635
+ changeProfile(p, true);
636
+ close();
637
+ },
638
+ className: "flex w-full items-center justify-between gap-4 rounded px-2 py-2 text-xs text-foreground hover:bg-secondary",
639
+ children: [
640
+ PROFILE_LABELS[p],
641
+ profile === p && /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" })
642
+ ]
643
+ },
644
+ p
645
+ )) }) }),
646
+ /* @__PURE__ */ jsx(Popover, { className: "bottom-full mb-2 !mt-0 !min-w-0", trigger: ({ open, toggle }) => /* @__PURE__ */ jsx(
647
+ "button",
648
+ {
649
+ type: "button",
650
+ "aria-label": "\u97F3\u91CF",
651
+ "aria-expanded": open,
652
+ "aria-haspopup": "dialog",
653
+ onClick: toggle,
654
+ title: `\u97F3\u91CF ${volume}%`,
655
+ className: "flex h-9 w-9 items-center justify-center rounded-md text-foreground hover:bg-secondary",
656
+ children: volume === 0 ? /* @__PURE__ */ jsx(VolumeX, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Volume2, { className: "h-4 w-4" })
657
+ }
658
+ ), children: () => /* @__PURE__ */ jsxs("div", { role: "dialog", "aria-label": "\u97F3\u91CF\u8C03\u8282", className: "flex flex-col items-center gap-2", children: [
659
+ /* @__PURE__ */ jsx(
660
+ "input",
661
+ {
662
+ type: "range",
663
+ "aria-label": "\u64AD\u653E\u97F3\u91CF",
664
+ min: 0,
665
+ max: 100,
666
+ value: volume,
667
+ style: { writingMode: "vertical-lr", direction: "rtl", width: 24, height: 112 },
668
+ disabled: !stream,
669
+ onChange: (e) => {
670
+ const next = Number(e.target.value);
671
+ if (audioEnabledRef.current !== next > 0) sendInput({ t: "audio", enabled: next > 0 });
672
+ audioEnabledRef.current = next > 0;
673
+ setVolume(next);
674
+ }
675
+ }
676
+ ),
677
+ /* @__PURE__ */ jsxs("span", { className: "whitespace-nowrap text-xs text-foreground", children: [
678
+ volume,
679
+ "%"
680
+ ] }),
681
+ volume > 0 && !hasAudio && /* @__PURE__ */ jsx("span", { role: "status", className: "whitespace-nowrap text-xs text-muted-foreground", children: "\u7B49\u5F85\u97F3\u9891\u6D41" })
682
+ ] }) }),
683
+ clipboardConflict && /* @__PURE__ */ jsxs(Fragment, { children: [
684
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => resolveConflict("local"), className: "text-xs underline", children: "\u4FDD\u7559\u672C\u673A\u526A\u8D34\u677F" }),
685
+ /* @__PURE__ */ jsx("button", { type: "button", onClick: () => resolveConflict("device"), className: "text-xs underline", children: "\u4FDD\u7559\u8BBE\u5907\u526A\u8D34\u677F" })
686
+ ] }),
687
+ clipboardError && /* @__PURE__ */ jsxs("span", { role: "status", className: "text-xs text-destructive", children: [
688
+ "\u526A\u8D34\u677F\u540C\u6B65\u5931\u8D25\uFF1A",
689
+ clipboardError
690
+ ] }),
691
+ platform === "android" && /* @__PURE__ */ jsx(
692
+ "button",
693
+ {
694
+ type: "button",
695
+ onClick: toggleOrientation,
696
+ "aria-label": landscape ? "\u5207\u56DE\u7AD6\u5C4F" : "\u5207\u6362\u6A2A\u5C4F",
697
+ title: landscape ? "\u5207\u56DE\u7AD6\u5C4F" : "\u5207\u6362\u6A2A\u5C4F",
698
+ "aria-pressed": landscape,
699
+ 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"}`,
700
+ children: /* @__PURE__ */ jsx(RotateCw, { className: "h-3.5 w-3.5" })
701
+ }
702
+ )
703
+ ] })
704
+ ] });
705
+ }
706
+ function DeviceMirror({ deviceId, deviceName, platform = "android", shortcutBar, onClose }) {
707
+ const open = deviceId !== null;
708
+ const client = useClient();
709
+ const { data: devices } = useDevices();
710
+ const [size, setSize] = useState({ width: 1080, height: 2340 });
711
+ const overlayRef = useRef(null);
712
+ const [fullscreen, setFullscreen] = useState(false);
713
+ const sleepTimeoutMin = useMemo(() => {
714
+ if (!deviceId) return 30;
715
+ const d = devices?.find((dv) => dv.external_id === deviceId);
716
+ const v = d?.meta?.sleep_timeout_min;
717
+ return typeof v === "number" ? v : 30;
718
+ }, [devices, deviceId]);
719
+ const lastActivityRef = useRef(Date.now());
720
+ const resetActivity = useCallback(() => {
721
+ lastActivityRef.current = Date.now();
722
+ }, []);
723
+ useEffect(() => {
724
+ if (!open || !deviceId || sleepTimeoutMin === 0) return;
725
+ const ms = sleepTimeoutMin * 60 * 1e3;
726
+ const id = setInterval(() => {
727
+ if (Date.now() - lastActivityRef.current >= ms) {
728
+ void client.devices.sleep(deviceId).then(() => onClose()).catch(() => {
729
+ });
730
+ clearInterval(id);
731
+ }
732
+ }, 1e4);
733
+ return () => clearInterval(id);
734
+ }, [open, deviceId, sleepTimeoutMin, onClose, client]);
735
+ const enterFullscreen = useCallback(async () => {
736
+ const el = overlayRef.current;
737
+ if (!el) return;
738
+ try {
739
+ if (el.requestFullscreen) await el.requestFullscreen();
740
+ else if (el.webkitRequestFullscreen) await el.webkitRequestFullscreen();
741
+ } catch {
742
+ }
743
+ }, []);
744
+ const exitFullscreen = useCallback(async () => {
745
+ const doc = document;
746
+ try {
747
+ if (doc.fullscreenElement && doc.exitFullscreen) await doc.exitFullscreen();
748
+ else if (doc.webkitFullscreenElement && doc.webkitExitFullscreen) await doc.webkitExitFullscreen();
749
+ } catch {
750
+ }
751
+ }, []);
752
+ const toggleFullscreen = useCallback(() => {
753
+ if (fullscreen) void exitFullscreen();
754
+ else void enterFullscreen();
755
+ }, [fullscreen, enterFullscreen, exitFullscreen]);
756
+ useEffect(() => {
757
+ const onFsChange = () => {
758
+ const doc = document;
759
+ const fsEl = doc.fullscreenElement || doc.webkitFullscreenElement || null;
760
+ setFullscreen(fsEl === overlayRef.current);
761
+ };
762
+ document.addEventListener("fullscreenchange", onFsChange);
763
+ document.addEventListener("webkitfullscreenchange", onFsChange);
764
+ return () => {
765
+ document.removeEventListener("fullscreenchange", onFsChange);
766
+ document.removeEventListener("webkitfullscreenchange", onFsChange);
767
+ };
768
+ }, []);
769
+ useEffect(() => {
770
+ if (!open) return;
771
+ const onKey = (e) => {
772
+ resetActivity();
773
+ if (e.key === "Escape" && !fullscreen) onClose();
774
+ };
775
+ window.addEventListener("keydown", onKey);
776
+ return () => window.removeEventListener("keydown", onKey);
777
+ }, [open, onClose, resetActivity, fullscreen]);
778
+ useEffect(() => {
779
+ if (!open) void exitFullscreen();
780
+ }, [open, exitFullscreen]);
781
+ const stop = useCallback((e) => e.stopPropagation(), []);
782
+ if (!open) return null;
783
+ const aspect = size.width > 0 && size.height > 0 ? size.width / size.height : 9 / 16;
784
+ return /* @__PURE__ */ jsx(
785
+ "div",
786
+ {
787
+ ref: overlayRef,
788
+ className: "fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm",
789
+ onClick: onClose,
790
+ onMouseMove: resetActivity,
791
+ onPointerDown: resetActivity,
792
+ children: /* @__PURE__ */ jsxs(
793
+ "div",
794
+ {
795
+ className: `flex flex-col items-center ${fullscreen ? "h-full w-full gap-1 py-2" : "gap-3"}`,
796
+ onClick: stop,
797
+ children: [
798
+ /* @__PURE__ */ jsxs("div", { className: "flex w-full items-center justify-between gap-3 px-2 text-white/90", children: [
799
+ /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium truncate max-w-[50vw]", children: [
800
+ deviceName || deviceId,
801
+ " \xB7 \u5B9E\u65F6\u955C\u50CF"
802
+ ] }),
803
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
804
+ /* @__PURE__ */ jsx(
805
+ "button",
806
+ {
807
+ type: "button",
808
+ "aria-label": fullscreen ? "\u9000\u51FA\u5168\u5C4F" : "\u5168\u5C4F",
809
+ title: fullscreen ? "\u9000\u51FA\u5168\u5C4F" : "\u5168\u5C4F",
810
+ onClick: toggleFullscreen,
811
+ className: "rounded p-1 hover:bg-white/10",
812
+ children: fullscreen ? /* @__PURE__ */ jsx(Minimize2, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize2, { className: "h-5 w-5" })
813
+ }
814
+ ),
815
+ /* @__PURE__ */ jsx(
816
+ "button",
817
+ {
818
+ type: "button",
819
+ "aria-label": "\u5173\u95ED",
820
+ onClick: onClose,
821
+ className: "rounded p-1 hover:bg-white/10",
822
+ children: /* @__PURE__ */ jsx(X, { className: "h-5 w-5" })
823
+ }
824
+ )
825
+ ] })
826
+ ] }),
827
+ /* @__PURE__ */ jsx("div", { className: `min-h-0 ${fullscreen ? "flex-1" : ""}`, style: fullscreen ? void 0 : { height: "80vh" }, children: /* @__PURE__ */ jsx(
828
+ MirrorSurface,
829
+ {
830
+ deviceId,
831
+ platform,
832
+ onSize: setSize,
833
+ videoAspect: aspect,
834
+ shortcutBar,
835
+ className: "h-full"
836
+ }
837
+ ) })
838
+ ]
839
+ }
840
+ )
841
+ }
842
+ );
843
+ }
844
+
845
+ export { DeviceBootSplash, DeviceMirror, MirrorSurface };