跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

WindowsPhoneBrowser.cs

103 行 · 5.7 KB历史下载
1using System.Diagnostics;
2using System.Text.Json.Nodes;
3using System.Text.RegularExpressions;
4using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease;
5
6namespace Cage.GuestClipboard;
7
8// This subtree is separate from desktop Chrome. One enrollment owns the active
9// phone ID; a disconnected connection never closes another ID or desktop tab.
10internal static class WindowsPhoneBrowser
11{
12 private static readonly SemaphoreSlim Gate = new(1, 1);
13 private static readonly Dictionary<InputLease, string> Owners = new();
14 private static readonly Regex ID = new("^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", RegexOptions.CultureInvariant);
15 private static Process? process;
16 private static GuestProcessJob? job;
17 private static Stream? replies;
18 private static string current = "";
19 internal static bool Installed() => BrowserRpc.BrowserExecutableInstalled() && new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "windows-phone-browser.mjs", "playwright/index.mjs", "modules/browser-phone.mjs", "modules/browser-phone-network.mjs" }
20 .All(file => File.Exists(Path.Combine(AppContext.BaseDirectory, file)));
21
22 private static JsonObject Error(int status) => new() { ["error"] = "phone_browser_unavailable", ["code"] = "phone_browser_error", ["status"] = status };
23 internal static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, InputLease owner)
24 {
25 await Gate.WaitAsync(connection);
26 try
27 {
28 var route = request["path"]?.GetValue<string>() ?? "";
29 var input = request["input"] as JsonObject ?? new JsonObject();
30 var id = input["id"]?.GetValue<string>() ?? "";
31 if (!ID.IsMatch(id)) return Error(400);
32 if (route != "/phone-browser/open" && current != id) return Error(410);
33 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35));
34 if (route == "/phone-browser/open")
35 {
36 if (!Installed()) return Error(501);
37 var settings = await BrowserRpc.ReadConfiguration(timeout.Token, packetOnly: true);
38 await Start(settings, timeout.Token);
39 }
40 if (process is not { HasExited: false }) return Error(410);
41 var result = await Control(request, timeout.Token);
42 if (result["error"] is null && route == "/phone-browser/open") { current = id; Owners[owner] = id; }
43 if (result["error"] is null && route == "/phone-browser/close") { current = ""; foreach (var key in Owners.Where(p => p.Value == id).Select(p => p.Key).ToArray()) Owners.Remove(key); }
44 return result;
45 }
46 catch (InvalidDataException) { return Error(503); }
47 catch (Exception error) when (error is OperationCanceledException or EndOfStreamException or IOException)
48 { Close(); return Error(503); }
49 finally { Gate.Release(); }
50 }
51 internal static async Task Release(InputLease owner)
52 {
53 await Gate.WaitAsync();
54 try
55 {
56 if (!Owners.Remove(owner, out var id) || Owners.Values.Contains(id) || current != id) return;
57 try
58 {
59 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
60 await Control(new JsonObject { ["method"] = "POST", ["path"] = "/phone-browser/close", ["input"] = new JsonObject { ["id"] = id } }, timeout.Token);
61 current = "";
62 }
63 catch { Close(); }
64 }
65 finally { Gate.Release(); }
66 }
67 private static async Task Start(JsonObject settings, CancellationToken token)
68 {
69 if (process is { HasExited: false }) return;
70 Close();
71 var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "node.exe"))
72 {
73 UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = AppContext.BaseDirectory,
74 RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
75 StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8,
76 };
77 start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "windows-phone-browser.mjs"));
78 process = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable");
79 try
80 {
81 job = new GuestProcessJob(process);
82 replies = new ReadAheadStream(process.StandardOutput.BaseStream);
83 var source = process.StandardError;
84 _ = Task.Run(async () => { try { var buffer = new char[4096]; while (await source.ReadAsync(buffer) != 0) { } } catch (ObjectDisposedException) { } });
85 var result = await Control(new JsonObject { ["operation"] = "configure", ["input"] = settings }, token);
86 if (result["ok"]?.GetValue<bool>() != true) throw new InvalidDataException("browser_unavailable");
87 }
88 catch { Close(); throw; }
89 }
90 private static async Task<JsonObject> Control(JsonObject input, CancellationToken token)
91 {
92 await Protocol.Write(process!.StandardInput.BaseStream, input, token);
93 return await Protocol.Read(replies!, 3 << 20, token) ?? throw new EndOfStreamException();
94 }
95 internal static void Close()
96 {
97 var owned = Interlocked.Exchange(ref process, null); current = ""; Owners.Clear();
98 try { if (owned is not null) { owned.StandardInput.Close(); if (!owned.WaitForExit(3000)) owned.Kill(true); owned.WaitForExit(2000); } }
99 catch (InvalidOperationException) { }
100 finally { job?.Dispose(); job = null; replies?.Dispose(); replies = null; owned?.Dispose(); }
101 // Enrollment profile directories remain intact.
102 }
103}