跳到主要内容

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

提交记录
修改.github/workflows/linux-build.yml+40 −3看文件
@@ -18,7 +18,7 @@ permissions:
1818 contents: read
1919jobs:
2020 debian:
21删除: # Debian 12's bubblewrap requires unprivileged user namespace mappings.
21新增: # Build with glibc 2.35 so the same package can run on Ubuntu 22.04.
2222 # Ubuntu 24.04's host policy restricts them even in an unconfined container.
2323 runs-on: ubuntu-22.04
2424 timeout-minutes: 60
@@ -26,7 +26,7 @@ jobs:
2626 run:
2727 shell: bash
2828 container:
29删除: image: debian:12
29新增: image: ubuntu:22.04
3030 # docker-default AppArmor denies bubblewrap's private mount namespace.
3131 # Relax only this disposable outer container; WebKit keeps its sandbox.
3232 options: --security-opt seccomp=unconfined --security-opt systempaths=unconfined --security-opt apparmor=unconfined
@@ -34,8 +34,9 @@ jobs:
3434 - name: Install build and test dependencies
3535 run: |
3636 apt-get update
37删除: DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libjson-glib-dev dpkg-dev curl ca-certificates git qemu-system-x86 qemu-utils ovmf openssh-client iproute2 dbus-x11 xvfb xauth fonts-noto-cjk zsh
37新增: DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev libjson-glib-dev dpkg-dev curl ca-certificates git qemu-system-x86 qemu-utils ovmf openssh-client iproute2 dbus-x11 xvfb xauth fonts-noto-cjk zsh sudo
3838 useradd -m -s /bin/bash cage
39新增: echo "cage ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/cage
3940 - uses: actions/checkout@v4
4041 with:
4142 ref: ${{ inputs.ref }}
@@ -77,6 +78,8 @@ jobs:
7778 runuser -u cage -- go test ./internal/... ./cmd/...
7879 runuser -u cage -- go vet ./internal/managedproxy ./internal/workbench ./cmd/cage
7980 runuser -u cage -- env UV_CACHE_DIR=/home/cage/.cache/uv uv run --no-project --python 3.11 internal/cage/desktop-downloads.test.py
81新增: - name: Ubuntu guest browser, extensions and noVNC dependencies
82新增: run: runuser -u cage -- bash scripts/test-ubuntu-guest.sh
8083 - name: Install, render native workbench, reinstall and remove
8184 run: |
8285 runuser -u cage -- bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev -- true
@@ -114,3 +117,37 @@ jobs:
114117 overwrite: true
115118 retention-days: 14
116119 # KVM and physical desktop acceptance remain separate real-machine checks.
120新增:
121新增: package-compatibility:
122新增: needs: debian
123新增: runs-on: ubuntu-22.04
124新增: timeout-minutes: 30
125新增: strategy:
126新增: fail-fast: false
127新增: matrix:
128新增: image: [debian:12, ubuntu:24.04]
129新增: container:
130新增: image: ${{ matrix.image }}
131新增: options: --security-opt seccomp=unconfined --security-opt systempaths=unconfined --security-opt apparmor=unconfined
132新增: steps:
133新增: - name: Install package test tools
134新增: run: |
135新增: apt-get update
136新增: DEBIAN_FRONTEND=noninteractive apt-get install -y ca-certificates git dbus-x11 xvfb xauth fonts-noto-cjk
137新增: - uses: actions/checkout@v4
138新增: with:
139新增: ref: ${{ inputs.ref }}
140新增: persist-credentials: false
141新增: - uses: actions/setup-node@v4
142新增: with:
143新增: node-version: 24
144新增: - uses: actions/download-artifact@v4
145新增: with:
146新增: name: ${{ inputs.artifact_name }}
147新增: path: _output/compatibility
148新增: - name: Test the Ubuntu 22.04-built package unchanged
149新增: shell: bash
150新增: run: |
151新增: package=$(find _output/compatibility -name 'Cage-*-linux-amd64.deb' -print -quit)
152新增: test -n "$package"
153新增: bash scripts/test-linux-install.sh "$package"
修改.github/workflows/windows-build.yml+34 −2看文件
@@ -45,13 +45,29 @@ jobs:
4545 with:
4646 dotnet-version: 10.0.403
4747 - uses: astral-sh/[email protected]
48新增: - uses: msys2/setup-msys2@v2
49新增: id: msys2
50新增: with:
51新增: msystem: UCRT64
52新增: update: true
53新增: install: >-
54新增: make patch diffutils
55新增: mingw-w64-ucrt-x86_64-gcc
56新增: mingw-w64-ucrt-x86_64-glib2
57新增: mingw-w64-ucrt-x86_64-pixman
58新增: mingw-w64-ucrt-x86_64-libslirp
59新增: mingw-w64-ucrt-x86_64-dtc
60新增: mingw-w64-ucrt-x86_64-ninja
61新增: mingw-w64-ucrt-x86_64-python
62新增: mingw-w64-ucrt-x86_64-pkgconf
4863 - uses: actions/cache@v4
4964 with:
5065 path: _output/windows-deps
51删除: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json') }}
66新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
5267 - name: Build, test and install the unsigned development package
5368 env:
5469 CAGE_BUILD_REF: ${{ inputs.ref }}
70新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
5571 run: ./scripts/ci-windows-build.ps1
5672 - uses: actions/upload-artifact@v4
5773 with:
@@ -94,10 +110,25 @@ jobs:
94110 with:
95111 dotnet-version: 10.0.403
96112 - uses: astral-sh/[email protected]
113新增: - uses: msys2/setup-msys2@v2
114新增: id: msys2
115新增: with:
116新增: msystem: UCRT64
117新增: update: true
118新增: install: >-
119新增: make patch diffutils
120新增: mingw-w64-ucrt-x86_64-gcc
121新增: mingw-w64-ucrt-x86_64-glib2
122新增: mingw-w64-ucrt-x86_64-pixman
123新增: mingw-w64-ucrt-x86_64-libslirp
124新增: mingw-w64-ucrt-x86_64-dtc
125新增: mingw-w64-ucrt-x86_64-ninja
126新增: mingw-w64-ucrt-x86_64-python
127新增: mingw-w64-ucrt-x86_64-pkgconf
97128 - uses: actions/cache@v4
98129 with:
99130 path: _output/windows-deps
100删除: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json') }}
131新增: key: cage-windows-deps-${{ hashFiles('packaging/windows/dependencies.json', 'patches/qemu/**', 'scripts/build-qemu-windows.*') }}
101132 - uses: actions/setup-java@v4
102133 with:
103134 distribution: temurin
@@ -105,6 +136,7 @@ jobs:
105136 - name: Build, sign, test and install the release candidate
106137 env:
107138 CAGE_BUILD_REF: ${{ inputs.ref }}
139新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }}
108140 CAGE_WINDOWS_SIGNING_PROVIDER: ${{ vars.CAGE_WINDOWS_SIGNING_PROVIDER }}
109141 CAGE_ESIGNER_USERNAME: ${{ secrets.CAGE_ESIGNER_USERNAME }}
110142 CAGE_ESIGNER_PASSWORD: ${{ secrets.CAGE_ESIGNER_PASSWORD }}
修改.gitignore+2 −0看文件
@@ -34,3 +34,5 @@ dist
3434# Rendered promo export; reproducible source and assets are in promo/.
3535/claude-cage-promo.mp4
3636/.vite/
37新增:
38新增:/internal/tailnetassets/assets/*.gz
修改Makefile+17 −2看文件
@@ -49,7 +49,7 @@ GO_BUILD := CGO_ENABLED=$(CGO_ENABLED) $(GO) build -trimpath -tags $(TAGS) -ldfl
4949all: agent-vm
5050
5151# Claude Cage ships a separate entry point with a mandatory proxy profile.
52删除:cage: cage-ui assets
52新增:cage: cage-ui assets tailnet-assets
5353 $(GO_BUILD) -o _output/bin/cage$(EXE) ./cmd/cage
5454ifeq ($(GOOS),darwin)
5555 codesign -f --entitlements third_party/lima/vz.entitlements -s - _output/bin/cage
@@ -96,18 +96,26 @@ ifeq ($(GOOS),darwin)
9696 codesign -f -v --entitlements third_party/lima/vz.entitlements -s - _output/bin/limactl
9797endif
9898
99删除:# The guest agent runs in the Linux guest: built for it, without cgo.
99新增:# Build each guest helper for the OS in which it will run.
100100assets:
101101 CGO_ENABLED=0 GOOS=linux GOARCH=$(GOARCH) $(GO) build -trimpath \
102102 -ldflags "-s -w -X github.com/lima-vm/lima/v2/pkg/version.Version=$(LIMA_VERSION)" \
103103 -o $(ASSETS)/lima-guestagent.Linux-$(GUEST_ARCH) github.com/lima-vm/lima/v2/cmd/lima-guestagent
104104 gzip -9 -n -f $(ASSETS)/lima-guestagent.Linux-$(GUEST_ARCH)
105新增:ifeq ($(GOOS)/$(GOARCH),darwin/arm64)
106新增: mkdir -p $(ASSETS)/Darwin
107新增: CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 $(GO) build -trimpath -tags $(TAGS) \
108新增: -ldflags "-s -w -X github.com/lima-vm/lima/v2/pkg/version.Version=$(LIMA_VERSION)" \
109新增: -o $(ASSETS)/Darwin/lima-guestagent.Darwin-aarch64 github.com/lima-vm/lima/v2/cmd/lima-guestagent
110新增: gzip -9 -n -f $(ASSETS)/Darwin/lima-guestagent.Darwin-aarch64
111新增:endif
105112 rm -rf $(ASSETS)/templates && cp -R third_party/lima/templates $(ASSETS)/templates
106113
107114test: test-go
108115
109116test-go:
110117 $(GO) test -tags $(TAGS) . ./cmd/... ./internal/...
118新增: cd tools/tailnet && GOFLAGS= $(GO) test ./...
111119
112120# The Windows build and its tests compile and vet, from any OS. The Windows
113121# paths' logic is tested everywhere (paths.Windows); the tests themselves
@@ -144,3 +152,10 @@ fuzz:
144152clean:
145153 rm -rf _output
146154 find $(ASSETS) -mindepth 1 ! -name README -exec rm -rf {} +
155新增:
156新增:.PHONY: tailnet-assets
157新增:tailnet-assets:
158新增: bash scripts/build-tailnet.sh linux amd64 "$(CURDIR)/_output/tailnet/cage-tailnet-linux-amd64"
159新增: bash scripts/build-tailnet.sh linux arm64 "$(CURDIR)/_output/tailnet/cage-tailnet-linux-arm64"
160新增: gzip -n -c _output/tailnet/cage-tailnet-linux-amd64 > internal/tailnetassets/assets/cage-tailnet-linux-amd64.gz
161新增: gzip -n -c _output/tailnet/cage-tailnet-linux-arm64 > internal/tailnetassets/assets/cage-tailnet-linux-arm64.gz
修改THIRD_PARTY_LICENSES+91 −0看文件
@@ -8,6 +8,32 @@ plus patches/ (see NOTICE).
88
99Generated by scripts/licenses.
1010
11新增:================================================================================
12新增:gaoyifan/china-operator-ip: mainland exit address list (MIT)
13新增:================================================================================
14新增:
15新增:MIT License
16新增:
17新增:Copyright (c) 2017 Yifan Gao
18新增:
19新增:Permission is hereby granted, free of charge, to any person obtaining a copy
20新增:of this software and associated documentation files (the "Software"), to deal
21新增:in the Software without restriction, including without limitation the rights
22新增:to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
23新增:copies of the Software, and to permit persons to whom the Software is
24新增:furnished to do so, subject to the following conditions:
25新增:
26新增:The above copyright notice and this permission notice shall be included in all
27新增:copies or substantial portions of the Software.
28新增:
29新增:THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30新增:IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31新增:FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32新增:AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33新增:LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
34新增:OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35新增:SOFTWARE.
36新增:
1137================================================================================
1238Go standard library (BSD-3-Clause)
1339================================================================================
@@ -3541,6 +3567,38 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35413567(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35423568OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35433569
3570新增:================================================================================
3571新增:github.com/google/uuid v1.6.0: LICENSE
3572新增:================================================================================
3573新增:
3574新增:Copyright (c) 2009,2014 Google Inc. All rights reserved.
3575新增:
3576新增:Redistribution and use in source and binary forms, with or without
3577新增:modification, are permitted provided that the following conditions are
3578新增:met:
3579新增:
3580新增: * Redistributions of source code must retain the above copyright
3581新增:notice, this list of conditions and the following disclaimer.
3582新增: * Redistributions in binary form must reproduce the above
3583新增:copyright notice, this list of conditions and the following disclaimer
3584新增:in the documentation and/or other materials provided with the
3585新增:distribution.
3586新增: * Neither the name of Google Inc. nor the names of its
3587新增:contributors may be used to endorse or promote products derived from
3588新增:this software without specific prior written permission.
3589新增:
3590新增:THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
3591新增:"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
3592新增:LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
3593新增:A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3594新增:OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3595新增:SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3596新增:LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3597新增:DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3598新增:THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3599新增:(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3600新增:OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3601新增:
35443602================================================================================
35453603github.com/google/yamlfmt v0.21.0: LICENSE
35463604================================================================================
@@ -6081,6 +6139,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
60816139OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
60826140THE SOFTWARE.
60836141
6142新增:================================================================================
6143新增:github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e: LICENSE
6144新增:================================================================================
6145新增:
6146新增:Copyright (c) 2014 Tom Harwood
6147新增:
6148新增:Permission is hereby granted, free of charge, to any person obtaining a copy
6149新增:of this software and associated documentation files (the "Software"), to deal
6150新增:in the Software without restriction, including without limitation the rights
6151新增:to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
6152新增:copies of the Software, and to permit persons to whom the Software is
6153新增:furnished to do so, subject to the following conditions:
6154新增:
6155新增:The above copyright notice and this permission notice shall be included in
6156新增:all copies or substantial portions of the Software.
6157新增:
6158新增:THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
6159新增:IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6160新增:FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
6161新增:AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
6162新增:LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
6163新增:OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
6164新增:THE SOFTWARE.
6165新增:
60846166================================================================================
60856167github.com/spakin/netpbm v1.3.2: LICENSE.md
60866168================================================================================
@@ -8172,3 +8254,12 @@ Some files carry the following license, noted at the top of each file:
81728254 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
81738255 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
81748256 THE SOFTWARE.
8257新增:
8258新增:Cage guest Tailscale component
8259新增:-----------------------------
8260新增:Tailscale 1.104.5 (https://github.com/tailscale/tailscale), BSD-3-Clause.
8261新增:The guest-only executable also uses gliderlabs/ssh (BSD-3-Clause), pkg/sftp
8262新增:(BSD-2-Clause), creack/pty (MIT), UserExistsError/conpty (MIT), and the
8263新增:transitive modules pinned in tools/tailnet/go.mod and tools/tailnet/go.sum.
8264新增:Full license notices for the modules linked on Linux, macOS and Windows
8265新增:are distributed in the application licenses/tailnet-go directory.
修改deploy/cloud/Dockerfile.guest+2 −0看文件
@@ -4,11 +4,13 @@ ARG BASE_IMAGE=debian:13-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b
44FROM ${BASE_IMAGE}
55
66ENV container=docker
7新增:COPY apt-bootstrap.sh /usr/local/lib/cage-apt-bootstrap
78COPY restore-apt-sources.sh /usr/local/lib/cage-image-restore-sources
89ARG DEBIAN_MIRROR=http://deb.debian.org
910RUN sed -i "s#http://deb.debian.org#${DEBIAN_MIRROR}#g" /etc/apt/sources.list.d/debian.sources \
1011 && printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d \
1112 && chmod 0755 /usr/sbin/policy-rc.d \
13新增: && sh /usr/local/lib/cage-apt-bootstrap \
1214 && apt-get update \
1315 && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
1416 systemd systemd-sysv dbus dbus-user-session libpam-systemd sudo \
修改deploy/cloud/README.md+2 −0看文件
@@ -69,6 +69,8 @@ cage_engine="$HOME/.claude-cage/container-engine/tools/docker"
6969
7070通过 `Dockerfile.guest` 构建基础层,再创建独立的镜像构建容器。构建容器不挂载项目、个人主目录、代理配置或账户;安装下载使用单独的构建网络。默认 Debian 镜像已经固定 digest,APT 继续验证发行版签名。若部署网络需要镜像站,只调整构建阶段的 Debian 软件源,保留签名验证;基础层和完整镜像提交前均恢复 `deb.debian.org` 官方源,以符合运行环境的维护下载来源限制。
7171
72新增:基础层在批量安装前使用共同的 `internal/cage/apt-bootstrap.sh` 检查 APT;Debian 13 低于 3.0.4 时先通过官方安全源升级,升级下载禁用重试。`build-guest.sh` 将该脚本与 Dockerfile 复制到本次构建的临时上下文,部署工具包包含同一份脚本。升级失败会保留构建证据并停止后续安装。
73新增:
7274使用[完整镜像构建脚本](build-guest.sh)建立本次构建独占的父 slice、网络和容器。脚本检查实际 rootless 引擎和父层上限,再执行共同安装脚本;命名带唯一后缀,避免覆盖已有环境。
7375
7476```sh
修改deploy/cloud/build-guest.sh+3 −1看文件
@@ -82,8 +82,10 @@ read -r cage_cpu_quota cage_cpu_period < "/sys/fs/cgroup$cage_parent/cpu.max"
8282 echo 'The build parent CPU limit was not applied.' >&2; exit 1;
8383}
8484cage_network_id=$(engine network create --label "cn.cage.image-build=$cage_build_id" "$cage_network")
85新增:mkdir "$cage_stage/context"
86新增:cp deploy/cloud/Dockerfile.guest deploy/cloud/restore-apt-sources.sh internal/cage/apt-bootstrap.sh "$cage_stage/context/"
8587DOCKER_BUILDKIT=0 engine build --cgroup-parent "$cage_slice" --network "$cage_network" \
86删除: "${cage_base_args[@]}" --file deploy/cloud/Dockerfile.guest --tag "$cage_base" deploy/cloud > "$cage_stage/base-build.log" 2>&1
88新增: "${cage_base_args[@]}" --file "$cage_stage/context/Dockerfile.guest" --tag "$cage_base" "$cage_stage/context" > "$cage_stage/base-build.log" 2>&1
8789cage_container_id=$(engine create --name "$cage_builder" --label "cn.cage.image-build=$cage_build_id" \
8890 --hostname cage --add-host cage:127.0.1.1 \
8991 --network "$cage_network" --cgroupns private --cgroup-parent "$cage_slice" --ipc private \
修改desktop/Cage.swift+174 −5看文件
@@ -23,6 +23,13 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
2323 private var allowQuit = false
2424 private var nativeFilePanelOpen = false
2525 private var fileSelections: [String: (paths: [String], expires: Date)] = [:]
26新增: private var clipboardGeneration = 0
27新增: private var clipboardCopies: [String: [String]] = [:]
28新增: private var clipboardReaders: [UUID: [String]] = [:]
29新增: private var clipboardPending = Set<String>()
30新增: private var clipboardReleasing = Set<String>()
31新增: private var clipboardCacheLoaded = false
32新增: private var clipboardCacheTimer: Timer?
2633 private var loading: NSTextField!
2734 private var retry: NSButton!
2835 private var backdrop: NSVisualEffectView!
@@ -40,6 +47,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
4047
4148 static func main() {
4249 CageProfile.pinEnvironment()
50新增: if CommandLine.arguments.dropFirst().elementsEqual(["--store-trial-guest-password"]) {
51新增: do { try MacGuestLoginCredential.importFromPipe(); return }
52新增: catch { FileHandle.standardError.write(Data((error.localizedDescription + "\n").utf8)); exit(1) }
53新增: }
4354 NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") }
4455 let app = NSApplication.shared
4556 let delegate = CageApp()
@@ -53,7 +64,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
5364 NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua)
5465 makeMenus()
5566 window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 850), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
56删除: window.title = "Cage"
67新增: window.title = CageProfile.macGuestTrial ? "Cage macOS" : "Cage"
5768 window.titlebarAppearsTransparent = false
5869 window.backgroundColor = NSColor(srgbRed: 247.0/255, green: 247.0/255, blue: 247.0/255, alpha: 1)
5970 window.minSize = NSSize(width: 820, height: 580)
@@ -129,6 +140,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
129140 completeUpdateMenu = appMenu.addItem(withTitle: "完成待安装更新…", action: #selector(completePendingUpdate), keyEquivalent: "")
130141 completeUpdateMenu.isHidden = true
131142 appMenu.addItem(.separator())
143新增: if CageProfile.macGuestTrial {
144新增: appMenu.addItem(withTitle: "复制试用客机登录密码", action: #selector(copyGuestLoginPassword), keyEquivalent: "")
145新增: }
132146 appMenu.addItem(withTitle: "设置…", action: #selector(settings), keyEquivalent: ",")
133147 appMenu.addItem(.separator())
134148 appMenu.addItem(withTitle: "隐藏 Cage", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h")
@@ -182,6 +196,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
182196 let status = controllerNeedsUpdate ? "\n当前连接旧后台;更新尚未完成。" : ""
183197 NSApp.orderFrontStandardAboutPanel(options: [.applicationName:"Cage", .applicationVersion:version, .credits:NSAttributedString(string:"本机隔离编码工作区\n基于 agent-vm、Lima、Chromium、noVNC 与 xterm.js" + status)])
184198 }
199新增: @objc private func copyGuestLoginPassword() {
200新增: do { try MacGuestLoginCredential.copyForLogin() }
201新增: catch { let alert = NSAlert(error: error); alert.beginSheetModal(for: window) }
202新增: }
185203 @objc private func settings() { action("settings") }
186204 @objc private func openProject() { action("openProject") }
187205 @objc private func newTab() { action("newTab") }
@@ -204,6 +222,12 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
204222 }
205223 private func action(_ name: String) { webView.evaluateJavaScript("window.cageNativeAction?.('\(name)')", completionHandler: nil) }
206224 private func requestEntry(options: [String] = [], _ completion: @escaping (Result<DesktopEntry, Error>) -> Void) {
225新增: if CageProfile.macGuestTrial {
226新增: let binding = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("macos-guest.json")
227新增: guard FileManager.default.fileExists(atPath: binding.path) else {
228新增: completion(.failure(CageUpdateError("这份试用版尚未绑定 macOS 客机,准备完成后请点重试。"))); return
229新增: }
230新增: }
207231 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else {
208232 completion(.failure(NSError(domain: "Cage", code: 1))); return
209233 }
@@ -238,10 +262,15 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
238262 case .success(let entry):
239263 self.controllerNeedsUpdate = entry.status != "ready"
240264 self.completeUpdateMenu.isHidden = !self.controllerNeedsUpdate
241删除: self.window.title = self.controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage"
265新增: let appTitle = CageProfile.macGuestTrial ? "Cage macOS" : "Cage"
266新增: self.window.title = self.controllerNeedsUpdate ? "\(appTitle)(更新待完成)" : appTitle
242267 if let url = entry.url { self.expectedPort = url.port!; self.webView.load(URLRequest(url: url)) }
243268 else { self.showError(entry.message); self.completeUpdateButton.isHidden = false; self.existingEnvironmentButton.isHidden = false }
244删除: case .failure(let error): self.showError(error.localizedDescription)
269新增: case .failure(let error):
270新增: CageDiagnostics.record("Workbench startup failed: \(error)")
271新增: let message = error.localizedDescription
272新增: if message.unicodeScalars.contains(where: { (0x4E00...0x9FFF).contains($0.value) }) { self.showError(message) }
273新增: else { self.showError("启动工作台失败:本机后台未返回可识别的原因(错误码 \((error as NSError).code))。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。") }
245274 }
246275 }
247276 }
@@ -249,6 +278,47 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
249278 guard UUID(uuidString: id) != nil else { reply(nil,"下载标识无效"); return }
250279 fileCommand(["browser-file", "--json", "--connection", connection, operation, id] + (path.map { [$0] } ?? []), reply: reply)
251280 }
281新增: private func clipboardCacheCommand(_ action: String, id: String = "", reply: @escaping (Any?, String?) -> Void) {
282新增: guard let data = try? JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]),
283新增: let request = String(data: data, encoding: .utf8) else { reply(nil,"剪贴板缓存请求无效"); return }
284新增: fileCommand(["clipboard-files", "--json", "cache", request], reply: reply)
285新增: }
286新增: private func watchClipboardCaches() {
287新增: guard clipboardCacheTimer == nil else { return }
288新增: clipboardCacheTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.collectClipboardCaches() }
289新增: clipboardCacheCommand("list") { result, _ in
290新增: self.clipboardCacheLoaded = true
291新增: for selection in (result as? [String:Any])?["selections"] as? [[String:Any]] ?? [] {
292新增: if let id = selection["cache_id"] as? String, let paths = selection["paths"] as? [String], !paths.isEmpty {
293新增: self.clipboardCopies[id] = paths
294新增: }
295新增: }
296新增: self.collectClipboardCaches()
297新增: }
298新增: }
299新增: private func releaseClipboardCache(_ id: String, completion: @escaping () -> Void = {}) {
300新增: guard !id.isEmpty else { completion(); return }
301新增: clipboardReleasing.insert(id)
302新增: clipboardCacheCommand("release", id: id) { _, error in
303新增: self.clipboardReleasing.remove(id)
304新增: if error == nil { self.clipboardCopies.removeValue(forKey: id) }
305新增: completion()
306新增: }
307新增: }
308新增: private func collectClipboardCaches() {
309新增: guard clipboardCacheLoaded else { return }
310新增: let selected = (NSPasteboard.general.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly:true]) as? [URL] ?? []).map(\.path)
311新增: let readers = clipboardReaders.values.flatMap { $0 }
312新增: for (id, paths) in clipboardCopies {
313新增: guard !clipboardPending.contains(id), !clipboardReleasing.contains(id), let first = paths.first else { continue }
314新增: let root = URL(fileURLWithPath: first).deletingLastPathComponent().standardizedFileURL.path
315新增: let referenced = (selected + readers).contains { path in
316新增: let path = URL(fileURLWithPath: path).standardizedFileURL.path
317新增: return path == root || path.hasPrefix(root + "/") || root.hasPrefix(path + "/")
318新增: }
319新增: if !referenced { releaseClipboardCache(id) }
320新增: }
321新增: }
252322 private func fileCommand(_ arguments: [String], reply: @escaping (Any?, String?) -> Void) {
253323 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return }
254324 DispatchQueue.global(qos: .userInitiated).async {
@@ -294,8 +364,21 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
294364 loading.textColor = .labelColor
295365 }
296366 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loading.isHidden = true; retry.isHidden = true; completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true; webView.isHidden = false; window.makeFirstResponder(webView); publishWindowVisibility() }
297删除: func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showError("无法连接工作台。后台任务不会因此自动结束。") }
298删除: func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { CageDiagnostics.record("WebKit content process terminated"); bootstrap() }
367新增: func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
368新增: CageDiagnostics.record("Workbench navigation failed: \(error)")
369新增: let failure = error as NSError
370新增: let reason: String
371新增: switch failure.code {
372新增: case NSURLErrorTimedOut: reason = "等待本机后台响应超时"
373新增: case NSURLErrorCannotConnectToHost: reason = "本机后台没有接受连接,可能尚未启动或已经退出"
374新增: case NSURLErrorNetworkConnectionLost: reason = "本机工作台连接在加载完成前中断"
375新增: default: reason = "内置网页组件未能加载本机工作台(错误码 \(failure.code))"
376新增: }
377新增: showError("打开工作台失败:\(reason)。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。")
378新增: }
379新增: func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
380新增: CageDiagnostics.record("WebKit content process terminated"); bootstrap()
381新增: }
299382 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
300383 guard let url = navigationAction.request.url, url.scheme == "http", url.host == "localhost", url.port == expectedPort else { decisionHandler(.cancel); return }
301384 decisionHandler(.allow)
@@ -349,6 +432,67 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
349432 applyAppearance(value)
350433 replyHandler(true,nil)
351434 case "clipboardRead": replyHandler(NSPasteboard.general.string(forType:.string) ?? "",nil)
435新增: case "clipboardRevision": watchClipboardCaches(); replyHandler(NSPasteboard.general.changeCount,nil)
436新增: case "clipboardSyncCancel": clipboardGeneration += 1; replyHandler(true,nil)
437新增: case "clipboardSyncRelease":
438新增: guard let id = body["files"] as? String, UUID(uuidString: id) != nil else { replyHandler(nil,"剪贴板文件标识无效"); return }
439新增: fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "release", id], reply: replyHandler)
440新增: case "clipboardSyncRead":
441新增: watchClipboardCaches()
442新增: let board = NSPasteboard.general
443新增: let revision = board.changeCount
444新增: if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly:true]) as? [URL], !urls.isEmpty {
445新增: let reader = UUID(), generation = clipboardGeneration
446新增: clipboardReaders[reader] = urls.map(\.path)
447新增: fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "send"] + urls.map(\.path)) { result, error in
448新增: defer { self.clipboardReaders.removeValue(forKey: reader); self.collectClipboardCaches() }
449新增: guard error == nil, var payload = result as? [String:Any] else { replyHandler(nil,error ?? "剪贴板文件传递失败"); return }
450新增: if generation != self.clipboardGeneration || board.changeCount != revision, let id = payload["files"] as? String {
451新增: self.fileCommand(["clipboard-files", "--json", "--connection", body["connection_id"] as? String ?? "local", "release", id]) { _, _ in }
452新增: }
453新增: payload["revision"] = revision
454新增: replyHandler(payload,nil)
455新增: }
456新增: } else if let image = NSImage(pasteboard:board), let tiff = image.tiffRepresentation, let bitmap = NSBitmapImageRep(data:tiff) {
457新增: guard bitmap.pixelsWide > 0, bitmap.pixelsHigh > 0, bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh,
458新增: let png = bitmap.representation(using:.png,properties:[:]), png.count <= 20 * 1024 * 1024 else { replyHandler(nil,"图片不能超过 20 MB 或 4000 万像素"); return }
459新增: replyHandler(["revision":revision,"png":png.base64EncodedString()],nil)
460新增: } else { replyHandler(["revision":revision,"text":board.string(forType:.string) ?? ""],nil) }
461新增: case "clipboardSyncWrite":
462新增: watchClipboardCaches()
463新增: let board = NSPasteboard.general
464新增: let generation = clipboardGeneration
465新增: let expected = body["revision"] as? Int
466新增: let write: ([URL]?, String) -> Void = { urls, cache in
467新增: guard generation == self.clipboardGeneration, expected == nil || board.changeCount == expected else {
468新增: self.clipboardPending.remove(cache)
469新增: self.releaseClipboardCache(cache) { replyHandler(["superseded":true,"revision":board.changeCount],nil) }
470新增: return
471新增: }
472新增: defer { self.clipboardPending.remove(cache); self.collectClipboardCaches() }
473新增: var written = false
474新增: if let urls {
475新增: board.clearContents(); written = board.writeObjects(urls as [NSURL])
476新增: } else if let encoded = body["png"] as? String, let data = Data(base64Encoded:encoded), data.count <= 20 * 1024 * 1024,
477新增: let bitmap = NSBitmapImageRep(data:data), bitmap.pixelsHigh > 0, bitmap.pixelsWide > 0,
478新增: bitmap.pixelsWide <= 40_000_000 / bitmap.pixelsHigh {
479新增: let image = NSImage(size:bitmap.size); image.addRepresentation(bitmap)
480新增: board.clearContents(); written = board.writeObjects([image])
481新增: } else if let text = body["text"] as? String, text.utf8.count <= 2 * 1024 * 1024 {
482新增: board.clearContents(); written = board.setString(text,forType:.string)
483新增: } else { replyHandler(nil,"剪贴板内容格式或大小无效"); return }
484新增: guard written else { replyHandler(nil,"剪贴板写入失败"); return }
485新增: if !cache.isEmpty { self.clipboardCacheCommand("publish", id: cache) { _, _ in } }
486新增: replyHandler(["revision":board.changeCount],nil)
487新增: }
488新增: if let id = body["files"] as? String, UUID(uuidString:id) != nil {
489新增: fileCommand(["clipboard-files","--json","--connection",body["connection_id"] as? String ?? "local","receive",id]) { result, error in
490新增: guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { replyHandler(nil,error ?? "剪贴板文件读取失败"); return }
491新增: let cache = (result as? [String:Any])?["cache_id"] as? String ?? ""
492新增: if !cache.isEmpty { self.clipboardCopies[cache] = paths; self.clipboardPending.insert(cache) }
493新增: write(paths.map { URL(fileURLWithPath:$0) }, cache)
494新增: }
495新增: } else { write(nil, "") }
352496 case "clipboardReadContent":
353497 let board = NSPasteboard.general
354498 if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty {
@@ -363,6 +507,16 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
363507 }
364508 replyHandler(["png":png.base64EncodedString()],nil)
365509 } else { replyHandler(["text":board.string(forType:.string) ?? ""],nil) }
510新增: case "chooseGuestMedia":
511新增: guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return }
512新增: let panel = NSOpenPanel()
513新增: panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.allowsMultipleSelection = false
514新增: panel.allowedContentTypes = [UTType(filenameExtension: "ipsw") ?? .data]
515新增: panel.title = "选择 Apple 恢复镜像"; nativeFilePanelOpen = true
516新增: panel.beginSheetModal(for: window) { response in
517新增: self.nativeFilePanelOpen = false
518新增: replyHandler(response == .OK ? (panel.url?.path ?? "") : "", nil)
519新增: }
366520 case "chooseUploadFiles":
367521 guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return }
368522 let panel = NSOpenPanel()
@@ -429,6 +583,21 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
429583 do { try data.write(to: url, options: .atomic); replyHandler(true, nil) }
430584 catch { replyHandler(nil, "主题未能导出,请检查保存位置的权限") }
431585 }
586新增: case "shareLocalProject":
587新增: guard !nativeFilePanelOpen, let connection = body["connection_id"] as? String,
588新增: !connection.isEmpty, let mode = body["mode"] as? String, ["read","write"].contains(mode)
589新增: else { replyHandler(nil,"请在云端工作台重新选择项目"); return }
590新增: let panel = NSOpenPanel()
591新增: panel.canChooseDirectories = true; panel.canChooseFiles = false
592新增: panel.canCreateDirectories = false; panel.allowsMultipleSelection = false
593新增: panel.prompt = mode == "write" ? "允许云端读写" : "允许云端读取"
594新增: panel.message = mode == "write" ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。"
595新增: nativeFilePanelOpen = true
596新增: panel.beginSheetModal(for: window) { response in
597新增: self.nativeFilePanelOpen = false
598新增: guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return }
599新增: self.fileCommand(["share-project", "--json", "--connection", connection, mode, url.path], reply: replyHandler)
600新增: }
432601 case "chooseFolder":
433602 let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false
434603 let storage = (body["purpose"] as? String) == "environmentStorage"
新增desktop/MacGuestLogin.swift+51 −0看文件
@@ -0,0 +1,51 @@
1新增:import Cocoa
2新增:import Security
3新增:
4新增:// The trial credential belongs to this local VM. It is never passed to the
5新增:// WebKit page, the control service, logs, command-line arguments or iCloud.
6新增:enum MacGuestLoginCredential {
7新增: private static func item() throws -> [String: Any] {
8新增: guard CageProfile.macGuestTrial else { throw CageUpdateError("此操作只适用于本机 macOS 试用版。") }
9新增: struct Binding: Decodable { let machineID: String; let user: String }
10新增: let url = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("macos-guest.json")
11新增: let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: url))
12新增: return [kSecClass as String: kSecClassGenericPassword,
13新增: kSecAttrService as String: "io.github.lee-xeo.claude-cage.macos-trial.guest-login",
14新增: kSecAttrAccount as String: binding.user + "@" + binding.machineID,
15新增: kSecAttrSynchronizable as String: false]
16新增: }
17新增: static func importFromPipe() throws {
18新增: guard isatty(STDIN_FILENO) == 0 else { throw CageUpdateError("请通过私有管道提供试用客机凭据。") }
19新增: let secret = FileHandle.standardInput.readData(ofLength: 1025)
20新增: guard !secret.isEmpty, secret.count <= 1024 else { throw CageUpdateError("客机凭据为空或过长。") }
21新增: var query = try item()
22新增: query[kSecAttrLabel as String] = "Cage macOS 试用客机登录"
23新增: query[kSecValueData as String] = secret
24新增: let status = SecItemAdd(query as CFDictionary, nil)
25新增: if status == errSecDuplicateItem, try read() == secret { return }
26新增: guard status == errSecSuccess else { throw CageUpdateError("无法保存本机试用客机凭据(\(status))。") }
27新增: }
28新增: private static func read() throws -> Data {
29新增: var query = try item()
30新增: query[kSecReturnData as String] = true
31新增: query[kSecMatchLimit as String] = kSecMatchLimitOne
32新增: var value: CFTypeRef?
33新增: let status = SecItemCopyMatching(query as CFDictionary, &value)
34新增: guard status == errSecSuccess, let data = value as? Data else { throw CageUpdateError("本机钥匙串中没有可用的试用客机密码。") }
35新增: return data
36新增: }
37新增: static func copyForLogin() throws {
38新增: guard let text = String(data: try read(), encoding: .utf8) else { throw CageUpdateError("客机密码格式无效。") }
39新增: let item = NSPasteboardItem()
40新增: item.setString(text, forType: .string)
41新增: item.setData(Data(), forType: .init("org.nspasteboard.ConcealedType"))
42新增: item.setData(Data(), forType: .init("org.nspasteboard.TransientType"))
43新增: let board = NSPasteboard.general
44新增: board.clearContents()
45新增: guard board.writeObjects([item]) else { throw CageUpdateError("无法写入剪贴板。") }
46新增: let change = board.changeCount
47新增: DispatchQueue.main.asyncAfter(deadline: .now() + 60) {
48新增: if board.changeCount == change { board.clearContents() }
49新增: }
50新增: }
51新增:}
新增desktop/MacKeyboard.swift+54 −0看文件
@@ -0,0 +1,54 @@
1新增:import Foundation
2新增:
3新增:// The host and guest use the same physical key names. Text remains layout-aware.
4新增:enum MacKeyboard {
5新增: static let codes: [UInt16: String] = [
6新增: 0:"KeyA", 1:"KeyS", 2:"KeyD", 3:"KeyF", 4:"KeyH", 5:"KeyG", 6:"KeyZ", 7:"KeyX", 8:"KeyC", 9:"KeyV",
7新增: 10:"IntlBackslash", 11:"KeyB", 12:"KeyQ", 13:"KeyW", 14:"KeyE", 15:"KeyR", 16:"KeyY", 17:"KeyT",
8新增: 18:"Digit1", 19:"Digit2", 20:"Digit3", 21:"Digit4", 22:"Digit6", 23:"Digit5", 24:"Equal", 25:"Digit9",
9新增: 26:"Digit7", 27:"Minus", 28:"Digit8", 29:"Digit0", 30:"BracketRight", 31:"KeyO", 32:"KeyU", 33:"BracketLeft",
10新增: 34:"KeyI", 35:"KeyP", 36:"Enter", 37:"KeyL", 38:"KeyJ", 39:"Quote", 40:"KeyK", 41:"Semicolon",
11新增: 42:"Backslash", 43:"Comma", 44:"Slash", 45:"KeyN", 46:"KeyM", 47:"Period", 48:"Tab", 49:"Space",
12新增: 50:"Backquote", 51:"Backspace", 53:"Escape", 54:"MetaRight", 55:"MetaLeft", 56:"ShiftLeft", 57:"CapsLock",
13新增: 58:"AltLeft", 59:"ControlLeft", 60:"ShiftRight", 61:"AltRight", 62:"ControlRight",
14新增: 64:"F17", 65:"NumpadDecimal", 67:"NumpadMultiply", 69:"NumpadAdd", 71:"NumLock", 75:"NumpadDivide",
15新增: 76:"NumpadEnter", 78:"NumpadSubtract", 79:"F18", 80:"F19", 81:"NumpadEqual", 82:"Numpad0", 83:"Numpad1",
16新增: 84:"Numpad2", 85:"Numpad3", 86:"Numpad4", 87:"Numpad5", 88:"Numpad6", 89:"Numpad7", 90:"F20",
17新增: 91:"Numpad8", 92:"Numpad9", 95:"NumpadComma", 96:"F5", 97:"F6", 98:"F7", 99:"F3", 100:"F8", 101:"F9", 103:"F11",
18新增: 105:"F13", 106:"F16", 107:"F14", 109:"F10", 111:"F12", 113:"F15", 114:"Insert", 115:"Home",
19新增: 116:"PageUp", 117:"Delete", 118:"F4", 119:"End", 120:"F2", 121:"PageDown", 122:"F1",
20新增: 123:"ArrowLeft", 124:"ArrowRight", 125:"ArrowDown", 126:"ArrowUp",
21新增: ]
22新增: static let keyCodes = Dictionary(uniqueKeysWithValues: codes.map { ($0.value, $0.key) })
23新增: private static let names = [
24新增: "MetaLeft":"Meta", "MetaRight":"Meta", "ControlLeft":"Control", "ControlRight":"Control",
25新增: "ShiftLeft":"Shift", "ShiftRight":"Shift", "AltLeft":"Alt", "AltRight":"Alt", "Space":" ",
26新增: "NumpadEnter":"Enter", "NumpadDecimal":".", "NumpadMultiply":"*", "NumpadAdd":"+",
27新增: "NumpadDivide":"/", "NumpadSubtract":"-", "NumpadEqual":"=", "NumpadComma":",",
28新增: ]
29新增: private static let symbols = [
30新增: " ":"Space", "=":"Equal", "+":"Equal", "-":"Minus", "_":"Minus", "[":"BracketLeft", "{":"BracketLeft",
31新增: "]":"BracketRight", "}":"BracketRight", "'":"Quote", "\"":"Quote", ";":"Semicolon", ":":"Semicolon",
32新增: "\\":"Backslash", "|":"Backslash", ",":"Comma", "<":"Comma", ".":"Period", ">":"Period",
33新增: "/":"Slash", "?":"Slash", "`":"Backquote", "~":"Backquote",
34新增: ]
35新增:
36新增: static func identity(_ keyCode: UInt16, characters: String) -> (key: String, code: String) {
37新增: guard let code = codes[keyCode] else { return (characters.isEmpty ? "Unidentified" : characters, "Unidentified") }
38新增: if let key = names[code] { return (key, code) }
39新增: if code.hasPrefix("Key") || code.hasPrefix("Digit") || code.hasPrefix("Numpad") ||
40新增: ["Equal", "Minus", "BracketLeft", "BracketRight", "Quote", "Semicolon", "Backslash", "IntlBackslash", "Comma", "Period", "Slash", "Backquote"].contains(code) {
41新增: return (characters.isEmpty ? "Unidentified" : characters, code)
42新增: }
43新增: return (code, code)
44新增: }
45新增:
46新增: static func virtualKey(code: String, key: String, shortcut: Bool) -> UInt16? {
47新增: if shortcut, key.utf8.count == 1, let ascii = key.uppercased().utf8.first {
48新增: if (65...90).contains(ascii) { return keyCodes["Key" + key.uppercased()] }
49新增: if (48...57).contains(ascii) { return keyCodes["Digit" + key] }
50新增: if let symbol = symbols[key] { return keyCodes[symbol] }
51新增: }
52新增: return keyCodes[code] ?? keyCodes[key] ?? symbols[key].flatMap { keyCodes[$0] }
53新增: }
54新增:}
修改desktop/NativeInput.swift+5 −16看文件
@@ -85,7 +85,8 @@ final class CageNativeInput: NSView, NSTextInputClient {
8585 }
8686
8787 override func keyDown(with event: NSEvent) {
88删除: if event.modifierFlags.contains(.command) {
88新增: let physical = MacKeyboard.codes[event.keyCode] ?? ""
89新增: if event.modifierFlags.contains(.command) || (!hasMarkedText() && physical.hasPrefix("F")) {
8990 sendKey(event, down: true)
9091 return
9192 }
@@ -96,25 +97,13 @@ final class CageNativeInput: NSView, NSTextInputClient {
9697 override func keyUp(with event: NSEvent) { sendKey(event, down: false) }
9798 override func flagsChanged(with event: NSEvent) {
9899 let flags: [UInt16: NSEvent.ModifierFlags] = [54: .command, 55: .command,
99删除: 56: .shift, 60: .shift, 58: .option, 61: .option, 59: .control, 62: .control]
100新增: 56: .shift, 60: .shift, 57: .capsLock, 58: .option, 61: .option, 59: .control, 62: .control]
100101 if let flag = flags[event.keyCode] { sendKey(event, down: event.modifierFlags.contains(flag)) }
101102 }
102103
103104 private func sendKey(_ event: NSEvent, down: Bool, text: String? = nil) {
104删除: let special: [UInt16: String] = [36:"Enter",48:"Tab",49:" ",51:"Backspace",
105删除: 53:"Escape",54:"Meta",55:"Meta",56:"Shift",57:"CapsLock",58:"Alt",59:"Control",
106删除: 60:"Shift",61:"Alt",62:"Control",115:"Home",116:"PageUp",117:"Delete",
107删除: 119:"End",121:"PageDown",123:"ArrowLeft",124:"ArrowRight",125:"ArrowDown",126:"ArrowUp"]
108删除: let letters: [UInt16: String] = [0:"A",1:"S",2:"D",3:"F",4:"H",5:"G",6:"Z",7:"X",8:"C",9:"V",11:"B",12:"Q",13:"W",14:"E",15:"R",16:"Y",17:"T",31:"O",32:"U",34:"I",35:"P",37:"L",38:"J",40:"K",45:"N",46:"M"]
109删除: let codes: [UInt16: String] = [36:"Enter",48:"Tab",49:"Space",51:"Backspace",53:"Escape",
110删除: 54:"MetaRight",55:"MetaLeft",56:"ShiftLeft",57:"CapsLock",58:"AltLeft",59:"ControlLeft",
111删除: 60:"ShiftRight",61:"AltRight",62:"ControlRight",115:"Home",116:"PageUp",117:"Delete",
112删除: 119:"End",121:"PageDown",123:"ArrowLeft",124:"ArrowRight",125:"ArrowDown",126:"ArrowUp",
113删除: 18:"Digit1",19:"Digit2",20:"Digit3",21:"Digit4",22:"Digit6",23:"Digit5",25:"Digit9",26:"Digit7",28:"Digit8",29:"Digit0",
114删除: 24:"Equal",27:"Minus",30:"BracketRight",33:"BracketLeft",39:"Quote",41:"Semicolon",42:"Backslash",43:"Comma",44:"Slash",47:"Period",50:"Backquote"]
115删除: let key = text ?? special[event.keyCode] ?? event.charactersIgnoringModifiers ?? "Unidentified"
116删除: let code = letters[event.keyCode].map { "Key" + $0 } ?? codes[event.keyCode] ?? "Unidentified"
117删除: emit(down ? "keydown" : "keyup", ["key": key, "code": code,
105新增: let identity = MacKeyboard.identity(event.keyCode, characters: text ?? event.charactersIgnoringModifiers ?? "")
106新增: emit(down ? "keydown" : "keyup", ["key": text ?? identity.key, "code": identity.code,
118107 "metaKey":event.modifierFlags.contains(.command),"ctrlKey":event.modifierFlags.contains(.control),
119108 "altKey":event.modifierFlags.contains(.option),"shiftKey":event.modifierFlags.contains(.shift),"repeat":event.isARepeat,
120109 "modifierCapsLock":event.modifierFlags.contains(.capsLock),"textKey":text != nil])
修改desktop/NativeInputTests.swift+31 −2看文件
@@ -1,14 +1,31 @@
11import AppKit
22import WebKit
33
4新增:private final class RecordingWebView: WKWebView {
5新增: var scripts: [String] = []
6新增: override func evaluateJavaScript(_ javaScriptString: String, completionHandler: (@MainActor @Sendable (Any?, Error?) -> Void)? = nil) {
7新增: scripts.append(javaScriptString)
8新增: completionHandler?(nil, nil)
9新增: }
10新增:}
11新增:
412@main
513enum NativeInputTests {
614 static func main() {
15新增: for number in 1...20 {
16新增: let name = "F\(number)"
17新增: let code = MacKeyboard.keyCodes[name]!
18新增: let identity = MacKeyboard.identity(code, characters: String(UnicodeScalar(0xf703 + number)!))
19新增: precondition(identity.key == name && identity.code == name, "function key became private-use text")
20新增: }
21新增: precondition(MacKeyboard.identity(83, characters: "1").code == "Numpad1")
22新增: precondition(MacKeyboard.identity(76, characters: "\r").key == "Enter")
23新增: precondition(MacKeyboard.virtualKey(code: "KeyW", key: "z", shortcut: true) == 6, "logical shortcut followed a foreign keyboard layout")
724 let app = NSApplication.shared
825 app.setActivationPolicy(.prohibited)
926 let window = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 900, height: 700),
1027 styleMask: [.titled, .resizable], backing: .buffered, defer: false)
11删除: let web = WKWebView(frame: window.contentView!.bounds)
28新增: let web = RecordingWebView(frame: window.contentView!.bounds)
1229 window.contentView!.addSubview(web)
1330 let input = CageNativeInput(frame: .zero)
1431 input.configure(web: web)
@@ -35,8 +52,20 @@ enum NativeInputTests {
3552 precondition(abs(moved.minY - lower.minY - 100) < 0.5)
3653 web.setFrameSize(NSSize(width: 1000, height: 800))
3754 _ = check(500, 680, 38)
55新增: for number in 1...20 {
56新增: let code = MacKeyboard.keyCodes["F\(number)"]!
57新增: let character = String(UnicodeScalar(0xf703 + number)!)
58新增: let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0,
59新增: windowNumber: window.windowNumber, context: nil, characters: character,
60新增: charactersIgnoringModifiers: character, isARepeat: false, keyCode: code)!
61新增: web.scripts.removeAll()
62新增: input.keyDown(with: event)
63新增: input.keyUp(with: event)
64新增: precondition(web.scripts.count == 2 && web.scripts.allSatisfy { $0.contains("\"code\":\"F\(number)\"") },
65新增: "function key was consumed by host text interpretation")
66新增: }
3867 precondition(!input.handle(["operation":"deactivate", "owner":UUID().uuidString]))
3968 precondition(input.handle(["operation":"deactivate", "owner":owner]))
40删除: print("Native input coordinates: top, bottom, window movement, resize, and stale owner checks passed")
69新增: print("Native input F1-F20 down/up, coordinates, window movement, resize, and stale owner checks passed")
4170 }
4271}
修改desktop/linux/cage-desktop.c+260 −11看文件
@@ -34,6 +34,26 @@ typedef struct {
3434static Cage app;
3535typedef struct { GPtrArray *paths; gint64 expires; } FileSelection;
3636static GHashTable *file_selections;
37新增:static guint64 clipboard_revision = 1;
38新增:static guint64 clipboard_generation = 0;
39新增:static gboolean clipboard_watching = FALSE;
40新增:typedef struct { GPtrArray *paths; gboolean pending, releasing; } ClipboardCopy;
41新增:static GHashTable *clipboard_copies;
42新增:static GPtrArray *clipboard_readers;
43新增:static gboolean clipboard_cache_loaded = FALSE, clipboard_cache_collecting = FALSE;
44新增:static void clipboard_cache_watch(void);
45新增:static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data);
46新增:static void clipboard_changed(GtkClipboard *clipboard, GdkEventOwnerChange *event, gpointer data) {
47新增: (void)clipboard; (void)event; (void)data; clipboard_revision++;
48新增:}
49新增:static guint64 clipboard_current_revision(void) {
50新增: clipboard_cache_watch();
51新增: if (!clipboard_watching) {
52新增: g_signal_connect(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), "owner-change", G_CALLBACK(clipboard_changed), NULL);
53新增: clipboard_watching = TRUE;
54新增: }
55新增: return clipboard_revision;
56新增:}
3757static void bootstrap(const char *option);
3858static void show_error(const char *message);
3959
@@ -263,7 +283,7 @@ static char *choose_file(GtkFileChooserAction kind, const char *title, const cha
263283 app.picker_open = FALSE;
264284 return path;
265285}
266删除:typedef struct { WebKitScriptMessageReply *reply; JSCContext *context; } PendingReply;
286新增:typedef struct { WebKitScriptMessageReply *reply; JSCContext *context; gboolean sync; guint64 revision, generation; char *connection; GPtrArray *clipboard_paths; } PendingReply;
267287static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext *context) {
268288 PendingReply *pending = g_new0(PendingReply, 1);
269289 pending->reply = webkit_script_message_reply_ref(reply);
@@ -271,14 +291,27 @@ static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext *
271291 return pending;
272292}
273293static void pending_free(PendingReply *pending) {
294新增: if (pending->clipboard_paths) {
295新增: g_ptr_array_remove(clipboard_readers, pending->clipboard_paths);
296新增: g_ptr_array_unref(pending->clipboard_paths);
297新增: }
274298 webkit_script_message_reply_unref(pending->reply);
275299 g_object_unref(pending->context);
300新增: g_free(pending->connection);
276301 g_free(pending);
277302}
278303static void browser_file_finished(JsonObject *object, const GError *error, gpointer data) {
279304 PendingReply *pending = data;
280305 if (error) reply_error(pending->reply, error->message);
281306 else {
307新增: if (pending->sync) {
308新增: json_object_set_int_member(object, "revision", pending->revision);
309新增: const char *id = text_member(object, "files");
310新增: if (*id && (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision())) {
311新增: const char *args[] = {app.backend, "clipboard-files", "--json", "--connection", pending->connection, "release", id, NULL};
312新增: backend_arguments(args, 10, clipboard_cache_ignored, NULL);
313新增: }
314新增: }
282315 JsonNode *node = json_node_new(JSON_NODE_OBJECT);
283316 json_node_set_object(node, object);
284317 char *json = json_to_string(node, FALSE);
@@ -300,7 +333,7 @@ static void clipboard_content_text(GtkClipboard *clipboard, const gchar *text, g
300333 if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。");
301334 else {
302335 char *quoted = quote(text ? text : "");
303删除: char *json = g_strdup_printf("{\"text\":%s}", quoted);
336新增: char *json = pending->sync ? g_strdup_printf("{\"text\":%s,\"revision\":%lu}", quoted, (unsigned long)pending->revision) : g_strdup_printf("{\"text\":%s}", quoted);
304337 reply_json(pending->reply, pending->context, json);
305338 g_free(json); g_free(quoted);
306339 }
@@ -319,7 +352,7 @@ static void clipboard_content_image(GtkClipboard *clipboard, GdkPixbuf *image, g
319352 reply_error(pending->reply, "图片不能超过 20 MB 或 4000 万像素。");
320353 } else {
321354 char *encoded = g_base64_encode((const guchar *)buffer, length);
322删除: char *json = g_strdup_printf("{\"png\":\"%s\"}", encoded);
355新增: char *json = pending->sync ? g_strdup_printf("{\"png\":\"%s\",\"revision\":%lu}", encoded, (unsigned long)pending->revision) : g_strdup_printf("{\"png\":\"%s\"}", encoded);
323356 reply_json(pending->reply, pending->context, json);
324357 g_free(json); g_free(encoded);
325358 }
@@ -381,6 +414,16 @@ static void reply_selected_uris(char **uris, PendingReply *pending) {
381414 }
382415 g_free(hostname); g_ptr_array_add(paths, path);
383416 }
417新增: if (!error && pending->sync) {
418新增: if (!clipboard_readers) clipboard_readers = g_ptr_array_new();
419新增: pending->clipboard_paths = g_ptr_array_ref(paths);
420新增: g_ptr_array_add(clipboard_readers, pending->clipboard_paths);
421新增: const char **args = g_new0(const char *, paths->len + 7);
422新增: args[0] = app.backend; args[1] = "clipboard-files"; args[2] = "--json"; args[3] = "--connection"; args[4] = pending->connection; args[5] = "send";
423新增: for (guint i = 0; i < paths->len; i++) args[i + 6] = g_ptr_array_index(paths, i);
424新增: backend_arguments(args, 1800, browser_file_finished, pending);
425新增: g_free(args); g_ptr_array_unref(paths); return;
426新增: }
384427 char *json = error ? NULL : remember_files(paths, &error);
385428 if (error) reply_error(pending->reply, error->message);
386429 else reply_json(pending->reply, pending->context, json);
@@ -403,6 +446,150 @@ static void clipboard_file_uris(GtkClipboard *clipboard, gchar **uris, gpointer
403446 if (uris && uris[0]) reply_selected_uris(uris, data);
404447 else gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("x-special/gnome-copied-files"), clipboard_gnome_files, data);
405448}
449新增:static void clipboard_sync_reply(PendingReply *pending, gboolean superseded) {
450新增: gdk_display_sync(gdk_display_get_default());
451新增: while (g_main_context_iteration(NULL, FALSE)) { }
452新增: char *json = g_strdup_printf("{\"revision\":%lu,\"superseded\":%s}", (unsigned long)clipboard_current_revision(), superseded ? "true" : "false");
453新增: reply_json(pending->reply, pending->context, json); g_free(json); pending_free(pending);
454新增:}
455新增:static void clipboard_cache_command(const char *action, const char *id, BackendCallback callback, gpointer data) {
456新增: char *quoted = quote(id ? id : "");
457新增: char *request = g_strdup_printf("{\"action\":\"%s\",\"cache_id\":%s}", action, quoted);
458新增: const char *args[] = {app.backend, "clipboard-files", "--json", "cache", request, NULL};
459新增: backend_arguments(args, 10, callback, data);
460新增: g_free(request); g_free(quoted);
461新增:}
462新增:static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data) { (void)object; (void)error; (void)data; }
463新增:static void clipboard_copy_free(gpointer data) { ClipboardCopy *copy = data; g_ptr_array_unref(copy->paths); g_free(copy); }
464新增:static void clipboard_cache_remember(JsonObject *object, gboolean pending) {
465新增: const char *id = text_member(object, "cache_id");
466新增: JsonArray *paths = json_object_has_member(object, "paths") ? json_object_get_array_member(object, "paths") : NULL;
467新增: if (!*id || !paths || !json_array_get_length(paths) || g_hash_table_contains(clipboard_copies, id)) return;
468新增: ClipboardCopy *copy = g_new0(ClipboardCopy, 1);
469新增: copy->pending = pending;
470新增: copy->paths = g_ptr_array_new_with_free_func(g_free);
471新增: for (guint i = 0; i < json_array_get_length(paths); i++) g_ptr_array_add(copy->paths, g_strdup(json_array_get_string_element(paths, i)));
472新增: g_hash_table_insert(clipboard_copies, g_strdup(id), copy);
473新增:}
474新增:typedef struct { char *id; PendingReply *discarded; } ClipboardDisposal;
475新增:static void clipboard_cache_released(JsonObject *object, const GError *error, gpointer data) {
476新增: (void)object;
477新增: ClipboardDisposal *disposal = data;
478新增: ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, disposal->id);
479新增: if (copy) { copy->releasing = FALSE; if (!error) g_hash_table_remove(clipboard_copies, disposal->id); }
480新增: if (disposal->discarded) clipboard_sync_reply(disposal->discarded, TRUE);
481新增: g_free(disposal->id); g_free(disposal);
482新增:}
483新增:static void clipboard_cache_release(const char *id, PendingReply *discarded) {
484新增: if (!id || !*id) { if (discarded) clipboard_sync_reply(discarded, TRUE); return; }
485新增: ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, id);
486新增: if (copy) { copy->releasing = TRUE; copy->pending = FALSE; }
487新增: ClipboardDisposal *disposal = g_new0(ClipboardDisposal, 1);
488新增: disposal->id = g_strdup(id); disposal->discarded = discarded;
489新增: clipboard_cache_command("release", id, clipboard_cache_released, disposal);
490新增:}
491新增:static gboolean clipboard_cache_referenced(GPtrArray *selected, GPtrArray *owned) {
492新增: if (!selected) return FALSE;
493新增: char *root = g_path_get_dirname(g_ptr_array_index(owned, 0));
494新增: char *prefix = g_strconcat(root, G_DIR_SEPARATOR_S, NULL);
495新增: gboolean found = FALSE;
496新增: for (guint i = 0; i < selected->len && !found; i++) {
497新增: const char *path = g_ptr_array_index(selected, i);
498新增: char *parent = g_strconcat(path, G_DIR_SEPARATOR_S, NULL);
499新增: found = !strcmp(path, root) || g_str_has_prefix(path, prefix) || g_str_has_prefix(root, parent);
500新增: g_free(parent);
501新增: }
502新增: g_free(root); g_free(prefix); return found;
503新增:}
504新增:static void clipboard_cache_collect_uris(char **uris, guint64 revision) {
505新增: clipboard_cache_collecting = FALSE;
506新增: if (revision != clipboard_revision) return;
507新增: GPtrArray *selected = g_ptr_array_new_with_free_func(g_free);
508新增: for (guint i = 0; uris && uris[i]; i++) {
509新增: char *path = g_filename_from_uri(uris[i], NULL, NULL);
510新增: if (!path) { g_ptr_array_unref(selected); return; }
511新增: g_ptr_array_add(selected, path);
512新增: }
513新增: GHashTableIter iterator; gpointer key, value;
514新增: g_hash_table_iter_init(&iterator, clipboard_copies);
515新增: while (g_hash_table_iter_next(&iterator, &key, &value)) {
516新增: ClipboardCopy *copy = value;
517新增: gboolean referenced = copy->pending || copy->releasing || clipboard_cache_referenced(selected, copy->paths);
518新增: for (guint i = 0; clipboard_readers && i < clipboard_readers->len && !referenced; i++)
519新增: referenced = clipboard_cache_referenced(g_ptr_array_index(clipboard_readers, i), copy->paths);
520新增: if (!referenced) clipboard_cache_release(key, NULL);
521新增: }
522新增: g_ptr_array_unref(selected);
523新增:}
524新增:static void clipboard_cache_gnome(GtkClipboard *clipboard, GtkSelectionData *selection, gpointer data) {
525新增: (void)clipboard;
526新增: guint64 revision = *(guint64 *)data;
527新增: gint length = gtk_selection_data_get_length(selection);
528新增: if (length > MAX_MESSAGE) { clipboard_cache_collecting = FALSE; g_free(data); return; }
529新增: char *text = length > 0 ? g_strndup((const char *)gtk_selection_data_get_data(selection), length) : NULL;
530新增: char *start = text ? strchr(text, '\n') : NULL;
531新增: char **uris = start ? g_uri_list_extract_uris(start + 1) : NULL;
532新增: clipboard_cache_collect_uris(uris, revision);
533新增: g_strfreev(uris); g_free(text); g_free(data);
534新增:}
535新增:static void clipboard_cache_uris(GtkClipboard *clipboard, gchar **uris, gpointer data) {
536新增: if (!uris) { gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("x-special/gnome-copied-files"), clipboard_cache_gnome, data); return; }
537新增: clipboard_cache_collect_uris(uris, *(guint64 *)data); g_free(data);
538新增:}
539新增:static gboolean clipboard_cache_tick(gpointer data) {
540新增: (void)data;
541新增: if (!clipboard_cache_loaded || clipboard_cache_collecting || !g_hash_table_size(clipboard_copies)) return G_SOURCE_CONTINUE;
542新增: clipboard_cache_collecting = TRUE;
543新增: guint64 *revision = g_new(guint64, 1); *revision = clipboard_revision;
544新增: gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_cache_uris, revision);
545新增: return G_SOURCE_CONTINUE;
546新增:}
547新增:static void clipboard_cache_loaded_reply(JsonObject *object, const GError *error, gpointer data) {
548新增: (void)data;
549新增: clipboard_cache_loaded = TRUE;
550新增: if (error || !object || !json_object_has_member(object, "selections")) return;
551新增: JsonArray *items = json_object_get_array_member(object, "selections");
552新增: for (guint i = 0; items && i < json_array_get_length(items); i++) clipboard_cache_remember(json_array_get_object_element(items, i), FALSE);
553新增: clipboard_cache_tick(NULL);
554新增:}
555新增:static void clipboard_cache_watch(void) {
556新增: if (clipboard_copies) return;
557新增: clipboard_copies = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, clipboard_copy_free);
558新增: g_timeout_add_seconds(1, clipboard_cache_tick, NULL);
559新增: clipboard_cache_command("list", "", clipboard_cache_loaded_reply, NULL);
560新增:}
561新增:static void clipboard_sync_provide(GtkClipboard *clipboard, GtkSelectionData *selection, guint info, gpointer data) {
562新增: (void)clipboard; char **payload = data;
563新增: gtk_selection_data_set(selection, gdk_atom_intern_static_string(info ? "x-special/gnome-copied-files" : "text/uri-list"),8,(const guchar *)payload[info],strlen(payload[info]));
564新增:}
565新增:static void clipboard_sync_clear(GtkClipboard *clipboard, gpointer data) { (void)clipboard; g_strfreev(data); }
566新增:static void clipboard_files_received(JsonObject *object, const GError *error, gpointer data) {
567新增: PendingReply *pending = data;
568新增: if (error) { reply_error(pending->reply, error->message); pending_free(pending); return; }
569新增: clipboard_cache_watch(); clipboard_cache_remember(object, TRUE);
570新增: const char *cache = text_member(object, "cache_id");
571新增: if (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision()) { clipboard_cache_release(cache, pending); return; }
572新增: JsonArray *paths = json_object_get_array_member(object, "paths");
573新增: if (!paths || !json_array_get_length(paths)) { clipboard_cache_release(cache, NULL); reply_error(pending->reply,"剪贴板文件读取失败。"); pending_free(pending); return; }
574新增: GString *text = g_string_new("copy\n"), *uris = g_string_new("");
575新增: for (guint i = 0; i < json_array_get_length(paths); i++) {
576新增: char *uri = g_filename_to_uri(json_array_get_string_element(paths, i), NULL, NULL);
577新增: if (!uri) { clipboard_cache_release(cache, NULL); g_string_free(text,TRUE); g_string_free(uris,TRUE); reply_error(pending->reply,"剪贴板文件位置无效。"); pending_free(pending); return; }
578新增: g_string_append_printf(text,"%s\n",uri); g_string_append_printf(uris,"%s\r\n",uri); g_free(uri);
579新增: }
580新增: /* GTK copies these values into an owned provider, including native file
581新增: manager targets. Use the selection callbacks below for both formats. */
582新增: GtkTargetEntry targets[] = {{"text/uri-list",0,0},{"x-special/gnome-copied-files",0,1}};
583新增: char **payload = g_new0(char *,3); payload[0] = g_string_free(uris,FALSE); payload[1] = g_string_free(text,FALSE);
584新增: if (!gtk_clipboard_set_with_data(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), targets,2, clipboard_sync_provide,clipboard_sync_clear,payload)) {
585新增: clipboard_cache_release(cache, NULL); g_strfreev(payload); reply_error(pending->reply,"剪贴板文件写入失败。"); pending_free(pending);
586新增: } else {
587新增: clipboard_revision++;
588新增: ClipboardCopy *copy = g_hash_table_lookup(clipboard_copies, cache); if (copy) copy->pending = FALSE;
589新增: if (*cache) clipboard_cache_command("publish", cache, clipboard_cache_ignored, NULL);
590新增: clipboard_sync_reply(pending,FALSE);
591新增: }
592新增:}
406593static void session_refreshed(JsonObject *object, const GError *error, gpointer data) {
407594 PendingReply *pending = data;
408595 const char *url = text_member(object, "url");
@@ -491,7 +678,7 @@ static gboolean start_smoke(gpointer data) {
491678 "if(phase==='seed')localStorage.setItem(storageKey,marker);"
492679 "const storageMarkerMatched=!phase||localStorage.getItem(storageKey)===marker;"
493680 "if(phase==='verify'&&storageMarkerMatched)localStorage.removeItem(storageKey);"
494删除: "stage='bridge';const bridge=window.webkit.messageHandlers.cage;"
681新增: "stage='bridge';const bridge=window.cageNativeBridge;"
495682 "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}"
496683 "stage='account-device';const native=await bridge.postMessage({action:'accountDevice',operation:'status'});"
497684 "stage='app-update';const update=await bridge.postMessage({action:'appUpdate',operation:'status'});"
@@ -516,7 +703,7 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val
516703 (void)manager; (void)data;
517704 char *json = jsc_value_to_json(value, 0);
518705 JsonParser *parser = json_parser_new();
519删除: if (!json || strlen(json) > MAX_MESSAGE || !json_parser_load_from_data(parser, json, -1, NULL) ||
706新增: if (!json || strlen(json) > 30 * 1024 * 1024 || !json_parser_load_from_data(parser, json, -1, NULL) ||
520707 !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) {
521708 reply_error(reply, "原生请求格式无效。");
522709 goto done;
@@ -603,6 +790,19 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val
603790 }
604791 g_free(path);
605792 }
793新增: } else if (!strcmp(name, "shareLocalProject")) {
794新增: const char *connection = text_member(request, "connection_id"), *mode = text_member(request, "mode");
795新增: if (app.picker_open || !*connection || (strcmp(mode,"read") && strcmp(mode,"write"))) {
796新增: reply_error(reply, "请在云端工作台重新选择项目。");
797新增: } else {
798新增: const char *prompt = !strcmp(mode,"write") ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。";
799新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, prompt, NULL);
800新增: if (path) {
801新增: const char *args[] = {app.backend,"share-project","--json","--connection",connection,mode,path,NULL};
802新增: backend_arguments(args,90,browser_file_finished,pending_reply(reply,context));
803新增: } else reply_json(reply,context,"{\"canceled\":true}");
804新增: g_free(path);
805新增: }
606806 } else if (!strcmp(name, "chooseFolder")) {
607807 if (app.picker_open) reply_error(reply, "请先完成当前文件选择。");
608808 else {
@@ -614,6 +814,39 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val
614814 }
615815 } else if (!strcmp(name, "clipboardRead")) {
616816 gtk_clipboard_request_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_received, pending_reply(reply, context));
817新增: } else if (!strcmp(name, "clipboardRevision")) {
818新增: char revision[32]; g_snprintf(revision,sizeof(revision),"%lu",(unsigned long)clipboard_current_revision()); reply_json(reply,context,revision);
819新增: } else if (!strcmp(name, "clipboardSyncCancel")) {
820新增: clipboard_generation++; reply_json(reply,context,"true");
821新增: } else if (!strcmp(name, "clipboardSyncRelease")) {
822新增: const char *id = text_member(request, "files");
823新增: if (!g_uuid_string_is_valid(id)) reply_error(reply, "剪贴板文件标识无效。");
824新增: else {
825新增: const char *args[] = {app.backend, "clipboard-files", "--json", "--connection", text_member(request, "connection_id"), "release", id, NULL};
826新增: backend_arguments(args, 10, browser_file_finished, pending_reply(reply, context));
827新增: }
828新增: } else if (!strcmp(name, "clipboardSyncRead")) {
829新增: PendingReply *pending = pending_reply(reply,context); pending->sync = TRUE; pending->generation = clipboard_generation; pending->revision = clipboard_current_revision(); pending->connection = g_strdup(text_member(request,"connection_id"));
830新增: gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),clipboard_file_uris,pending);
831新增: } else if (!strcmp(name, "clipboardSyncWrite")) {
832新增: PendingReply *pending = pending_reply(reply,context); pending->generation = clipboard_generation; pending->revision = json_object_has_member(request,"revision") ? (guint64)json_object_get_int_member(request,"revision") : clipboard_current_revision();
833新增: if (pending->revision != clipboard_current_revision()) clipboard_sync_reply(pending,TRUE);
834新增: else if (*text_member(request,"files")) {
835新增: const char *id = text_member(request,"files");
836新增: if (!g_uuid_string_is_valid(id)) { reply_error(reply,"剪贴板文件标识无效。"); pending_free(pending); }
837新增: else { const char *args[] = {app.backend,"clipboard-files","--json","--connection",text_member(request,"connection_id"),"receive",id,NULL}; backend_arguments(args,1800,clipboard_files_received,pending); }
838新增: } else if (*text_member(request,"png")) {
839新增: gsize length = 0; guchar *bytes = g_base64_decode(text_member(request,"png"),&length);
840新增: GdkPixbufLoader *loader = gdk_pixbuf_loader_new_with_type("png",NULL);
841新增: gboolean valid = loader && length <= 20 * 1024 * 1024 && gdk_pixbuf_loader_write(loader,bytes,length,NULL) && gdk_pixbuf_loader_close(loader,NULL);
842新增: GdkPixbuf *image = valid ? gdk_pixbuf_loader_get_pixbuf(loader) : NULL;
843新增: if (!image || (gint64)gdk_pixbuf_get_width(image) * gdk_pixbuf_get_height(image) > 40000000) { reply_error(reply,"剪贴板图片格式或大小无效。"); pending_free(pending); }
844新增: else { gtk_clipboard_set_image(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),image); clipboard_revision++; clipboard_sync_reply(pending,FALSE); }
845新增: if (loader) g_object_unref(loader);
846新增: g_free(bytes);
847新增: } else if (json_object_has_member(request,"text") && strlen(text_member(request,"text")) <= MAX_MESSAGE) {
848新增: gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD),text_member(request,"text"),-1); clipboard_revision++; clipboard_sync_reply(pending,FALSE);
849新增: } else { reply_error(reply,"剪贴板内容格式或大小无效。"); pending_free(pending); }
617850 } else if (!strcmp(name, "clipboardReadContent")) {
618851 gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_file_uris, pending_reply(reply, context));
619852 } else if (!strcmp(name, "chooseUploadFiles")) {
@@ -739,7 +972,7 @@ static void install_bridge(void) {
739972 "window.cageLinuxBridgeInit='origin-valid';window.cageNativeIMEAvailable=true;try{"
740973 "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;"
741974 "const cage=Object.freeze({postMessage(request){return transport.postMessage({token,request});}});"
742删除: "Object.defineProperty(window.webkit.messageHandlers,'cage',{value:cage,writable:false,configurable:false});"
975新增: "Object.defineProperty(window,'cageNativeBridge',{value:cage,writable:false,configurable:false});"
743976 "window.cageLinuxBridgeInit='ready';}catch(error){window.cageLinuxBridgeInit=error.name;}"
744977 "})();", app.port, token);
745978 /* The host allowlist narrows injection; the script and native receiver
@@ -757,7 +990,20 @@ static void bootstrapped(JsonObject *object, const GError *error, gpointer data)
757990 (void)data;
758991 app.bootstrapping = FALSE;
759992 gtk_widget_set_sensitive(app.retry, TRUE);
760删除: if (error) { show_error(error->message); return; }
993新增: if (error) {
994新增: diagnostic_event(error->message);
995新增: gboolean chinese = FALSE;
996新增: for (const char *p = error->message; *p; p = g_utf8_next_char(p)) {
997新增: gunichar value = g_utf8_get_char(p);
998新增: if (value >= 0x4E00 && value <= 0x9FFF) { chinese = TRUE; break; }
999新增: }
1000新增: if (chinese) show_error(error->message);
1001新增: else {
1002新增: char *message = g_strdup_printf("启动工作台失败:本机后台未返回可识别的原因(错误码 %d)。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。", error->code);
1003新增: show_error(message); g_free(message);
1004新增: }
1005新增: return;
1006新增: }
7611007 const char *status = text_member(object, "status");
7621008 app.needs_update = strcmp(status, "ready") != 0;
7631009 if (!strcmp(status, "upgrade_pending")) {
@@ -831,9 +1077,12 @@ static void load_changed(WebKitWebView *web, WebKitLoadEvent event, gpointer dat
8311077 }
8321078}
8331079static gboolean load_failed(WebKitWebView *web, WebKitLoadEvent event, const char *uri, GError *error, gpointer data) {
834删除: (void)web; (void)event; (void)uri; (void)error; (void)data;
1080新增: (void)web; (void)event; (void)uri; (void)data;
8351081 app.navigation_failed = TRUE;
836删除: show_error("无法连接 Cage 工作台。后台任务保留,可重试连接。");
1082新增: if (error) diagnostic_event(error->message);
1083新增: char *message = g_strdup_printf("打开工作台失败:内置网页组件未能加载本机后台(错误码 %d)。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。", error ? error->code : 0);
1084新增: show_error(message);
1085新增: g_free(message);
8371086 return TRUE;
8381087}
8391088static void process_terminated(WebKitWebView *web, WebKitWebProcessTerminationReason reason, gpointer data) {
@@ -978,7 +1227,7 @@ static gboolean smoke_diagnostics(gpointer data) {
9781227 "const account=await fetch('/api/account');const state=await fetch('/api/status');const settings=await fetch('/api/settings');"
9791228 "let unlocked=false;try{unlocked=(await account.json()).unlocked===true;}catch{}"
9801229 "const descriptor=Object.getOwnPropertyDescriptor(window,'webkit');"
981删除: "return {bridgeAvailable:!!window.webkit?.messageHandlers?.cage,bridgeInit:window.cageLinuxBridgeInit||'not-injected',webkitConfigurable:descriptor?.configurable,transportPresent:!!window.webkit?.messageHandlers?.cageTransport,readyState:document.readyState,"
1230新增: "return {bridgeAvailable:!!window.cageNativeBridge,bridgeInit:window.cageLinuxBridgeInit||'not-injected',webkitConfigurable:descriptor?.configurable,transportPresent:!!window.webkit?.messageHandlers?.cageTransport,readyState:document.readyState,"
9821231 "renderedButtons:document.querySelectorAll('button').length,accountStatus:account.status,accountUnlocked:unlocked,statusStatus:state.status,settingsStatus:settings.status};";
9831232 webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, "cage-smoke-diagnostics", NULL, smoke_diagnostics_ready, NULL);
9841233 return G_SOURCE_REMOVE;
@@ -1030,7 +1279,7 @@ int main(int argc, char **argv) {
10301279 }
10311280 char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, app.profile, -1);
10321281 char *id = g_strdup_printf("app.cage.desktop.p%.24s", hash);
1033删除: app.application = gtk_application_new(id, G_APPLICATION_DEFAULT_FLAGS);
1282新增: app.application = gtk_application_new(id, G_APPLICATION_FLAGS_NONE);
10341283 g_free(hash); g_free(id);
10351284 g_signal_connect(app.application, "activate", G_CALLBACK(activate), NULL);
10361285 if (app.smoke_output) {
修改desktop/windows/MainWindow.cs+116 −28看文件
@@ -23,25 +23,12 @@ internal sealed class MainWindow : Form
2323 public MainWindow()
2424 {
2525 nativeInput = new NativeInput(value => Script("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:" + JsonSerializer.Serialize(value) + "}));"));
26删除: Text = "Cage"; Width = 1280; Height = 850; MinimumSize = new Size(820, 580);
26新增: AutoScaleMode = AutoScaleMode.Dpi; AutoScaleDimensions = new SizeF(96, 96);
27新增: Text = "Cage";
2728 StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247);
2829 Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath!) ?? SystemIcons.Application;
29删除: var menus = new MenuStrip();
30删除: var file = new ToolStripMenuItem("文件");
31删除: AddAction(file, "打开项目…", "openProject", Keys.Control | Keys.O);
32删除: AddAction(file, "新建网页", "newTab", Keys.Control | Keys.T);
33删除: AddAction(file, "新建终端", "newTerminal", Keys.Control | Keys.Shift | Keys.Enter);
34删除: AddAction(file, "关闭当前标签", "closeTab", Keys.Control | Keys.W);
35删除: file.DropDownItems.Add("关闭窗口(保留环境)", null, (_, _) => Hide());
36删除: file.DropDownItems.Add("退出 Cage…", null, (_, _) => RequestQuit());
37删除: var settings = new ToolStripMenuItem("设置");
38删除: AddAction(settings, "打开设置", "settings", Keys.Control | Keys.Oemcomma);
39删除: settings.DropDownItems.Add("检查应用更新…", null, (_, _) => updater!.Handle("check"));
40删除: var help = new ToolStripMenuItem("帮助");
41删除: help.DropDownItems.Add("关于 Cage", null, (_, _) => MessageBox.Show(this, $"Cage {AppUpdater.Version}\n本机隔离编码工作区", "关于 Cage"));
42删除: menus.Items.AddRange([file, settings, help]); MainMenuStrip = menus;
4330 status.Controls.AddRange([message, retry, existing, complete]);
44删除: Controls.Add(web); Controls.Add(status); Controls.Add(menus);
31新增: Controls.Add(web); Controls.Add(status);
4532 Controls.Add(nativeInput);
4633 retry.Click += async (_, _) => {
4734 if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap();
@@ -50,9 +37,13 @@ internal sealed class MainWindow : Form
5037 complete.Click += async (_, _) => {
5138 if (ConfirmStop()) await Bootstrap("--complete-update");
5239 };
53删除: var trayMenu = new ContextMenuStrip();
40新增: var trayMenu = new TrayMenu();
5441 trayMenu.Items.Add("打开 Cage", null, (_, _) => RestoreWindow());
42新增: trayMenu.Items.Add("检查应用更新…", null, (_, _) => updater!.Handle("check"));
43新增: trayMenu.Items.Add("关于 Cage", null, (_, _) => MessageBox.Show(this, $"Cage {AppUpdater.Version}\n本机隔离编码工作区", "关于 Cage"));
44新增: trayMenu.Items.Add(new ToolStripSeparator());
5545 trayMenu.Items.Add("退出 Cage…", null, (_, _) => RequestQuit());
46新增: trayMenu.Opening += (_, _) => (chrome ?? new WindowChrome(BackColor, ForeColor, false)).ApplyMenu(trayMenu);
5647 tray = new NotifyIcon { Icon = Icon, Text = "Cage", Visible = true, ContextMenuStrip = trayMenu };
5748 tray.DoubleClick += (_, _) => RestoreWindow();
5849 updater = new AppUpdater(PublishUpdate, () => { allowQuit = true; Close(); }, () => _ = Bootstrap());
@@ -62,17 +53,61 @@ internal sealed class MainWindow : Form
6253 };
6354 Resize += (_, _) => PublishVisibility(); VisibleChanged += (_, _) => PublishVisibility();
6455 FormClosing += (_, e) => {
56新增: SaveWindowPlacement();
6557 if (!allowQuit && e.CloseReason is not (CloseReason.WindowsShutDown or CloseReason.TaskManagerClosing)) { e.Cancel = true; Hide(); }
6658 };
67删除: FormClosed += (_, _) => { lifetime.Cancel(); updater.Dispose(); tray.Dispose(); web.Dispose(); };
59新增: FormClosed += (_, _) => { lifetime.Cancel(); updater.Dispose(); tray.Dispose(); trayMenu.Dispose(); web.Dispose(); };
60新增: }
61新增:
62新增: protected override void OnLoad(EventArgs e)
63新增: {
64新增: base.OnLoad(e);
65新增: WindowPlacement? saved = null;
66新增: try { saved = JsonSerializer.Deserialize<WindowPlacement>(File.ReadAllText(Path.Combine(Backend.Root, "window-placement.json"))); }
67新增: catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { }
68新增: var work = Screen.FromHandle(Handle).WorkingArea;
69新增: MinimumSize = WindowLayout.Minimum(work, DeviceDpi);
70新增: StartPosition = FormStartPosition.Manual;
71新增: Bounds = WindowLayout.Bounds(work, DeviceDpi, saved);
72新增: if (saved?.Maximized == true) WindowState = FormWindowState.Maximized;
73新增: }
74新增:
75新增: private void SaveWindowPlacement()
76新增: {
77新增: var bounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
78新增: if (bounds.Width <= 0 || bounds.Height <= 0) return;
79新增: try
80新增: {
81新增: Directory.CreateDirectory(Backend.Root);
82新增: File.WriteAllText(Path.Combine(Backend.Root, "window-placement.json"),
83新增: JsonSerializer.Serialize(new WindowPlacement(bounds.X, bounds.Y, bounds.Width, bounds.Height, DeviceDpi,
84新增: WindowState == FormWindowState.Maximized)));
85新增: }
86新增: catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
87新增: }
88新增:
89新增: protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
90新增: {
91新增: var action = keyData switch {
92新增: Keys.Control | Keys.O => "openProject",
93新增: Keys.Control | Keys.T => "newTab",
94新增: Keys.Control | Keys.Shift | Keys.Enter => "newTerminal",
95新增: Keys.Control | Keys.W => "closeTab",
96新增: Keys.Control | Keys.Oemcomma => "settings",
97新增: _ => null,
98新增: };
99新增: if (action == null) return base.ProcessCmdKey(ref msg, keyData);
100新增: Action(action); return true;
68101 }
69102
70103 private WindowChrome? chrome;
71104
72105 private void ApplyWindowChrome()
73106 {
74删除: if (IsHandleCreated && MainMenuStrip != null)
107新增: if (IsHandleCreated)
75108 chrome?.Apply(Handle, MainMenuStrip);
109新增: if (tray?.ContextMenuStrip != null)
110新增: chrome?.ApplyMenu(tray.ContextMenuStrip);
76111 }
77112
78113 protected override void OnHandleCreated(EventArgs e)
@@ -87,13 +122,11 @@ internal sealed class MainWindow : Form
87122 ApplyWindowChrome();
88123 }
89124
90删除: private void AddAction(ToolStripMenuItem menu, string label, string action, Keys shortcut) =>
91删除: menu.DropDownItems.Add(new ToolStripMenuItem(label, null, (_, _) => Action(action)) { ShortcutKeys = shortcut });
92125 private bool ConfirmStop() => MessageBox.Show(this,
93126 "请先保存编辑器中的文件并结束正在运行的工作。继续后 Cage 会停止环境、安装已验证的更新并重新启动。",
94127 "保存并停止环境后安装重启", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK;
95128
96删除: public void RestoreWindow() { Show(); WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); }
129新增: public void RestoreWindow() { Show(); if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); }
97130 private void RequestQuit()
98131 {
99132 RestoreWindow();
@@ -144,7 +177,15 @@ internal sealed class MainWindow : Form
144177 core.WebMessageReceived += Receive;
145178 core.ProcessFailed += (_, _) => { webFailed = true; Error("工作台显示进程已退出。后台任务保留,可重试连接。"); };
146179 core.NavigationCompleted += (_, e) => {
147删除: if (!e.IsSuccess) { Error("无法连接 Cage 工作台。后台任务保留,可重试连接。"); return; }
180新增: if (!e.IsSuccess) {
181新增: var reason = e.WebErrorStatus.ToString() switch {
182新增: "Timeout" => "等待本机后台响应超时",
183新增: "CannotConnect" => "本机后台没有接受连接,可能尚未启动或已经退出",
184新增: "ConnectionAborted" or "ConnectionReset" => "本机工作台连接在加载完成前中断",
185新增: _ => "内置网页组件未能加载本机工作台(错误类型 " + e.WebErrorStatus + ")",
186新增: };
187新增: Error("打开工作台失败:" + reason + "。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。"); return;
188新增: }
148189 status.Hide(); web.Show(); web.Focus(); PublishVisibility();
149190 };
150191 await core.AddScriptToExecuteOnDocumentCreatedAsync(BridgeScript);
@@ -176,6 +217,8 @@ internal sealed class MainWindow : Form
176217 File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new {
177218 success = true, nativeBridgeReady = true, version = AppUpdater.Version,
178219 webviewVersion = web.CoreWebView2.Environment.BrowserVersionString,
220新增: windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi,
221新增: nativeMenuBar = MainMenuStrip != null,
179222 }));
180223 }
181224 catch (Exception error) { Error(error.Message); }
@@ -201,8 +244,11 @@ internal sealed class MainWindow : Form
201244 Text = controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage";
202245 web.CoreWebView2.Navigate(entry.AbsoluteUri);
203246 }
204删除: catch (OperationCanceledException) { if (!lifetime.IsCancellationRequested) Error("连接后台超时,请重试。"); }
205删除: catch (Exception error) { Error(error.Message); }
247新增: catch (OperationCanceledException) { if (!lifetime.IsCancellationRequested) Error("启动工作台失败:等待本机后台响应超时。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。"); }
248新增: catch (Exception error) {
249新增: _ = Backend.Report("Workbench startup failed: " + error);
250新增: Error(error.Message.Any(c => c is >= '\u4E00' and <= '\u9FFF') ? error.Message : "启动工作台失败:本机后台未返回可识别的原因(错误类型 " + error.GetType().Name + ")。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。");
251新增: }
206252 finally { bootstrapping = false; }
207253 }
208254
@@ -233,10 +279,14 @@ internal sealed class MainWindow : Form
233279 string id = "";
234280 try
235281 {
236删除: if (e.WebMessageAsJson.Length > 2 * 1024 * 1024) throw new InvalidDataException("请求过大");
237删除: var body = JsonDocument.Parse(e.WebMessageAsJson).RootElement;
282新增: var message = e.WebMessageAsJson;
283新增: using var envelope = JsonDocument.Parse(message);
284新增: var body = envelope.RootElement;
238285 id = body.Text("id");
239286 if (!Guid.TryParse(id, out _)) return;
287新增: // Match the Linux bridge envelope limit. A 20 MiB PNG needs about
288新增: // 27 MiB after Base64 encoding; retain the ID to reply on rejection.
289新增: if (message.Length > 30 * 1024 * 1024) throw new InvalidDataException("请求内容过大,请减少图片或文本内容后重试");
240290 var request = body.GetProperty("request");
241291 object? result;
242292 switch (request.Text("action"))
@@ -277,11 +327,30 @@ internal sealed class MainWindow : Form
277327 File.WriteAllText(picker.FileName, themeText, new System.Text.UTF8Encoding(false)); result = true;
278328 }
279329 break;
330新增: case "shareLocalProject":
331新增: {
332新增: var connection = request.Text("connection_id");
333新增: var accessMode = request.Text("mode");
334新增: if (connection.Length == 0 || accessMode is not ("read" or "write")) throw new InvalidDataException("请在云端工作台重新选择项目");
335新增: using var picker = new FolderBrowserDialog {
336新增: Description = accessMode == "write" ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。",
337新增: UseDescriptionForTitle = true, ShowNewFolderButton = false
338新增: };
339新增: if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; }
340新增: var response = await Backend.Json(["share-project", "--json", "--connection", connection, accessMode, picker.SelectedPath], lifetime.Token, TimeSpan.FromSeconds(90));
341新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
342新增: result = response.Data; break;
343新增: }
280344 case "chooseFolder":
281345 using (var picker = new FolderBrowserDialog { Description = request.Text("purpose") == "environmentStorage" ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true })
282346 result = picker.ShowDialog(this) == DialogResult.OK ? picker.SelectedPath : "";
283347 break;
284348 case "clipboardRead": result = Clipboard.ContainsText() ? Clipboard.GetText() : ""; break;
349新增: case "clipboardRevision": result = SharedClipboard.Revision; break;
350新增: case "clipboardSyncCancel": SharedClipboard.Cancel(); result = true; break;
351新增: case "clipboardSyncRead": result = await SharedClipboard.Read(request, lifetime.Token); break;
352新增: case "clipboardSyncWrite": result = await SharedClipboard.Write(request, lifetime.Token); break;
353新增: case "clipboardSyncRelease": result = await SharedClipboard.Release(request, lifetime.Token); break;
285354 case "saveBrowserDownload":
286355 case "browserDownloadAction":
287356 {
@@ -316,6 +385,18 @@ internal sealed class MainWindow : Form
316385 }
317386 else result = new { text = Clipboard.ContainsText() ? Clipboard.GetText() : "" };
318387 break;
388新增: case "chooseGuestMedia":
389新增: using (var picker = new OpenFileDialog { Title = "选择 Windows 11 x64 安装镜像", Filter = "Windows ISO (*.iso)|*.iso", Multiselect = false })
390新增: result = picker.ShowDialog(this) == DialogResult.OK ? picker.FileName : "";
391新增: break;
392新增: case "guestInstallReference":
393新增: var reference = request.Text("kind") switch {
394新增: "windows-media" => "https://www.microsoft.com/software-download/windows11",
395新增: "editor-license" => "https://aka.ms/vscode-server-license",
396新增: _ => throw new InvalidDataException("未知的安装参考页面")
397新增: };
398新增: System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(reference) { UseShellExecute = true });
399新增: result = true; break;
319400 case "chooseUploadFiles":
320401 using (var picker = new OpenFileDialog { Title = "选择本机文件", Multiselect = request.TryGetProperty("multiple", out var multiple) && multiple.ValueKind == JsonValueKind.True, CheckFileExists = true })
321402 result = picker.ShowDialog(this) == DialogResult.OK ? RememberFiles(picker.FileNames) : new { canceled = true };
@@ -375,6 +456,11 @@ internal sealed class MainWindow : Form
375456 if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return;
376457 window.cageNativeIMEAvailable = true;
377458 const pending = new Map();
459新增: const fileActions = new Set([
460新增: 'uploadHostFiles', 'chooseUploadFiles', 'clipboardSyncRead', 'clipboardSyncWrite',
461新增: 'saveBrowserDownload', 'browserDownloadAction', 'desktopFileAction', 'exportDiagnostics',
462新增: 'importTheme', 'exportTheme', 'shareLocalProject', 'chooseFolder', 'chooseGuestMedia',
463新增: ]);
378464 chrome.webview.addEventListener('message', ({data}) => {
379465 const item = pending.get(data.id); if (!item) return;
380466 pending.delete(data.id); clearTimeout(item.timer);
@@ -382,7 +468,9 @@ internal sealed class MainWindow : Form
382468 });
383469 const cage = {postMessage(request) { return new Promise((resolve, reject) => {
384470 const id = crypto.randomUUID();
385删除: const timer = setTimeout(() => { pending.delete(id); reject(new Error('原生操作超时,请重试')); }, request.action === 'uploadHostFiles' || request.action === 'chooseUploadFiles' ? 1800000 : 240000);
471新增: // File commands have a 30-minute backend deadline. Leave time for
472新增: // the native file dialog and the final subprocess response.
473新增: const timer = setTimeout(() => { pending.delete(id); reject(new Error('原生操作超时,请重试')); }, fileActions.has(request.action) ? 3600000 : 240000);
386474 pending.set(id, {resolve, reject, timer}); chrome.webview.postMessage({id, request});
387475 }); }};
388476 Object.defineProperty(window, 'webkit', {value: {messageHandlers: {cage}}, writable: false});
修改desktop/windows/NativeInput.cs+40 −3看文件
@@ -13,6 +13,8 @@ internal sealed class NativeInput : TextBox
1313 private bool composing, resetting;
1414 private Keys lastKey;
1515 private bool repeating;
16新增: private int scanCode;
17新增: private bool extendedKey;
1618 private char? highSurrogate;
1719
1820 internal NativeInput(Action<Dictionary<string, object?>> publish)
@@ -79,6 +81,7 @@ internal sealed class NativeInput : TextBox
7981 {
8082 if (!composing && (keyData & (Keys.Control | Keys.Alt)) != 0)
8183 {
84新增: ReadKeyMessage(msg);
8285 Key(keyData & Keys.KeyCode, true);
8386 return true;
8487 }
@@ -113,7 +116,8 @@ internal sealed class NativeInput : TextBox
113116 }
114117 private static bool IsCommand(Keys key) => key is Keys.Enter or Keys.Tab or Keys.Back or Keys.Delete or Keys.Escape or
115118 Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Home or Keys.End or Keys.PageUp or Keys.PageDown or
116删除: Keys.ShiftKey or Keys.ControlKey or Keys.Menu or Keys.LWin or Keys.RWin or Keys.CapsLock || key >= Keys.F1 && key <= Keys.F24;
119新增: Keys.ShiftKey or Keys.ControlKey or Keys.Menu or Keys.LWin or Keys.RWin or Keys.CapsLock or Keys.Insert or
120新增: Keys.PrintScreen or Keys.Scroll or Keys.Pause or Keys.NumLock or Keys.Apps or Keys.Clear || key >= Keys.F1 && key <= Keys.F24;
117121
118122 private void Key(Keys key, bool down, string? text = null)
119123 {
@@ -125,22 +129,55 @@ internal sealed class NativeInput : TextBox
125129 Keys.ShiftKey => ("Shift", "ShiftLeft"), Keys.ControlKey => ("Control", "ControlLeft"), Keys.Menu => ("Alt", "AltLeft"),
126130 Keys.LWin => ("Meta", "MetaLeft"), Keys.RWin => ("Meta", "MetaRight"), Keys.CapsLock => ("CapsLock", "CapsLock"),
127131 Keys.Home => ("Home", "Home"), Keys.End => ("End", "End"), Keys.PageUp => ("PageUp", "PageUp"), Keys.PageDown => ("PageDown", "PageDown"),
132新增: Keys.Space => (" ", "Space"), Keys.Insert => ("Insert", "Insert"), Keys.PrintScreen => ("PrintScreen", "PrintScreen"),
133新增: Keys.Scroll => ("ScrollLock", "ScrollLock"), Keys.Pause => ("Pause", "Pause"), Keys.NumLock => ("NumLock", "NumLock"),
134新增: Keys.Apps => ("ContextMenu", "ContextMenu"), Keys.Clear => ("Clear", "Numpad5"),
135新增: Keys.OemSemicolon => (";", "Semicolon"), Keys.Oemplus => ("=", "Equal"), Keys.Oemcomma => (",", "Comma"),
136新增: Keys.OemMinus => ("-", "Minus"), Keys.OemPeriod => (".", "Period"), Keys.OemQuestion => ("/", "Slash"),
137新增: Keys.Oemtilde => ("`", "Backquote"), Keys.OemOpenBrackets => ("[", "BracketLeft"), Keys.OemPipe => ("\\", "Backslash"),
138新增: Keys.OemCloseBrackets => ("]", "BracketRight"), Keys.OemQuotes => ("'", "Quote"), Keys.OemBackslash => ("\\", "IntlBackslash"),
139新增: Keys.Multiply => ("*", "NumpadMultiply"), Keys.Add => ("+", "NumpadAdd"), Keys.Subtract => ("-", "NumpadSubtract"),
140新增: Keys.Decimal => (".", "NumpadDecimal"), Keys.Divide => ("/", "NumpadDivide"), Keys.Separator => (",", "NumpadComma"),
128141 _ when key >= Keys.A && key <= Keys.Z => (key.ToString().ToLowerInvariant(), "Key" + key),
129142 _ when key >= Keys.D0 && key <= Keys.D9 => (((int)key - (int)Keys.D0).ToString(), "Digit" + ((int)key - (int)Keys.D0)),
143新增: _ when key >= Keys.NumPad0 && key <= Keys.NumPad9 => (((int)key - (int)Keys.NumPad0).ToString(), "Numpad" + ((int)key - (int)Keys.NumPad0)),
130144 _ when key >= Keys.F1 && key <= Keys.F24 => (key.ToString(), key.ToString()),
131145 _ => (text ?? "Unidentified", "Unidentified")
132146 };
147新增: var code = key switch {
148新增: Keys.Enter when extendedKey => "NumpadEnter",
149新增: Keys.ShiftKey when scanCode == 0x36 => "ShiftRight",
150新增: Keys.ControlKey when extendedKey => "ControlRight",
151新增: Keys.Menu when extendedKey => "AltRight",
152新增: _ => pair.Item2,
153新增: };
154新增: if (!extendedKey && key is Keys.Insert or Keys.Delete or Keys.Home or Keys.End or Keys.PageUp or Keys.PageDown or
155新增: Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Clear)
156新增: {
157新增: code = scanCode switch {
158新增: 0x47 => "Numpad7", 0x48 => "Numpad8", 0x49 => "Numpad9", 0x4b => "Numpad4", 0x4c => "Numpad5",
159新增: 0x4d => "Numpad6", 0x4f => "Numpad1", 0x50 => "Numpad2", 0x51 => "Numpad3", 0x52 => "Numpad0",
160新增: 0x53 => "NumpadDecimal", _ => code,
161新增: };
162新增: }
133163 publish(new() { ["owner"] = owner, ["kind"] = down ? "keydown" : "keyup", ["key"] = text ?? pair.Item1,
134删除: ["code"] = pair.Item2, ["textKey"] = text != null, ["repeat"] = repeating,
164新增: ["code"] = code, ["textKey"] = text != null, ["repeat"] = repeating,
135165 ["ctrlKey"] = (ModifierKeys & Keys.Control) != 0, ["altKey"] = (ModifierKeys & Keys.Alt) != 0,
136166 ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false });
137167 }
138168
169新增: private void ReadKeyMessage(Message message)
170新增: {
171新增: scanCode = (int)((message.LParam.ToInt64() >> 16) & 0xff);
172新增: extendedKey = (message.LParam.ToInt64() & (1L << 24)) != 0;
173新增: repeating = (message.LParam.ToInt64() & (1L << 30)) != 0;
174新增: }
175新增:
139176 protected override void WndProc(ref Message message)
140177 {
141178 const int Start = 0x10d, End = 0x10e, Composition = 0x10f;
142179 bool committed = false;
143删除: if (message.Msg == 0x100) repeating = ((long)message.LParam & (1L << 30)) != 0;
180新增: if (message.Msg is 0x100 or 0x101 or 0x104 or 0x105) ReadKeyMessage(message);
144181 if (!resetting && owner.Length > 0)
145182 {
146183 if (message.Msg == Start) { composing = true; Emit("compositionstart"); }
新增desktop/windows/SharedClipboard.cs+175 −0看文件
@@ -0,0 +1,175 @@
1新增:using System.Collections.Specialized;
2新增:using System.Runtime.InteropServices;
3新增:using System.Text.Json;
4新增:
5新增:namespace Cage.Windows;
6新增:
7新增:internal static class SharedClipboard
8新增:{
9新增: private static int generation;
10新增: private static readonly Dictionary<string, string[]> copies = new();
11新增: private static readonly List<string[]> readers = new();
12新增: private static readonly HashSet<string> pending = new();
13新增: private static readonly System.Windows.Forms.Timer timer = new() { Interval = 1000 };
14新增: private static bool watching, loaded, collecting;
15新增:
16新增: public static void Cancel() => generation++;
17新增: [DllImport("user32.dll")]
18新增: private static extern uint GetClipboardSequenceNumber();
19新增: public static uint Revision
20新增: {
21新增: get
22新增: {
23新增: if (!watching)
24新增: {
25新增: watching = true;
26新增: timer.Tick += async (_, _) => await Collect();
27新增: timer.Start();
28新增: }
29新增: return GetClipboardSequenceNumber();
30新增: }
31新增: }
32新增:
33新增: private static async Task<JsonElement> Cache(string action, string id = "")
34新增: {
35新增: var request = JsonSerializer.Serialize(new { action, cache_id = id });
36新增: var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10));
37新增: if (result.Exit != 0) throw new IOException("clipboard_cache_operation_failed");
38新增: return result.Data;
39新增: }
40新增:
41新增: private static bool References(string[] selected, string[] owned)
42新增: {
43新增: var root = Path.GetDirectoryName(owned[0])!;
44新增: return selected.Any(path => Path.GetFullPath(path).Equals(root, StringComparison.OrdinalIgnoreCase)
45新增: || Path.GetFullPath(path).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
46新增: || root.StartsWith(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase));
47新增: }
48新增:
49新增: private static async Task ReleaseLocal(string id)
50新增: {
51新增: try { await Cache("release", id); copies.Remove(id); }
52新增: catch { /* The receipt remains available for the next ownership check. */ }
53新增: }
54新增:
55新增: private static async Task Collect()
56新增: {
57新增: if (collecting) return;
58新增: collecting = true;
59新增: try
60新增: {
61新增: if (!loaded)
62新增: {
63新增: loaded = true;
64新增: var result = await Cache("list");
65新增: foreach (var item in result.GetProperty("selections").EnumerateArray())
66新增: copies.TryAdd(item.Text("cache_id"), item.GetProperty("paths").EnumerateArray().Select(path => path.GetString()!).ToArray());
67新增: }
68新增: foreach (var copy in copies.ToArray())
69新增: {
70新增: var selected = Clipboard.ContainsFileDropList() ? Clipboard.GetFileDropList().Cast<string>().ToArray() : [];
71新增: if (pending.Contains(copy.Key) || References(selected, copy.Value) || readers.Any(paths => References(paths, copy.Value))) continue;
72新增: await ReleaseLocal(copy.Key);
73新增: }
74新增: }
75新增: catch { /* An unreadable OS clipboard retains its files. */ }
76新增: finally { collecting = false; }
77新增: }
78新增:
79新增: private static async Task ReleaseRemote(string connection, string id, CancellationToken token)
80新增: {
81新增: var response = await Backend.Json(["clipboard-files", "--json", "--connection", connection, "release", id], token, TimeSpan.FromSeconds(10));
82新增: if (response.Exit != 0) throw new IOException("clipboard_selection_release_failed");
83新增: }
84新增:
85新增: public static async Task<object> Release(JsonElement request, CancellationToken token)
86新增: {
87新增: var id = request.Text("files");
88新增: if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效");
89新增: await ReleaseRemote(request.Text("connection_id"), id, token);
90新增: return new { ok = true };
91新增: }
92新增:
93新增: public static async Task<object> Read(JsonElement request, CancellationToken token)
94新增: {
95新增: var revision = Revision;
96新增: var capturedGeneration = generation;
97新增: if (Clipboard.ContainsFileDropList())
98新增: {
99新增: var selected = Clipboard.GetFileDropList().Cast<string>().ToArray();
100新增: readers.Add(selected);
101新增: try
102新增: {
103新增: var arguments = new List<string> { "clipboard-files", "--json", "--connection", request.Text("connection_id"), "send" };
104新增: arguments.AddRange(selected);
105新增: var response = await Backend.Json(arguments.ToArray(), token, TimeSpan.FromMinutes(30));
106新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
107新增: var files = response.Data.Text("files");
108新增: if (capturedGeneration != generation || revision != Revision)
109新增: {
110新增: try { await ReleaseRemote(request.Text("connection_id"), files, CancellationToken.None); } catch { }
111新增: }
112新增: return new { revision, files };
113新增: }
114新增: finally { readers.Remove(selected); await Collect(); }
115新增: }
116新增: if (Clipboard.ContainsImage())
117新增: {
118新增: using var image = Clipboard.GetImage() ?? throw new IOException("无法读取剪贴板图片");
119新增: if ((long)image.Width * image.Height > 40_000_000) throw new IOException("图片不能超过 4000 万像素");
120新增: using var output = new MemoryStream();
121新增: image.Save(output, System.Drawing.Imaging.ImageFormat.Png);
122新增: if (output.Length > 20 * 1024 * 1024) throw new IOException("图片不能超过 20 MB");
123新增: return new { revision, png = Convert.ToBase64String(output.ToArray()) };
124新增: }
125新增: return new { revision, text = Clipboard.ContainsText() ? Clipboard.GetText() : "" };
126新增: }
127新增:
128新增: public static async Task<object> Write(JsonElement request, CancellationToken token)
129新增: {
130新增: var currentGeneration = generation;
131新增: string[]? paths = null;
132新增: var cache = "";
133新增: if (request.Text("files") is { Length: > 0 } id)
134新增: {
135新增: if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效");
136新增: var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30));
137新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
138新增: paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray();
139新增: cache = response.Data.Text("cache_id");
140新增: if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); }
141新增: }
142新增: try
143新增: {
144新增: if (currentGeneration != generation || request.TryGetProperty("revision", out var expected) && expected.GetUInt32() != Revision)
145新增: {
146新增: if (cache.Length != 0) await ReleaseLocal(cache);
147新增: return new { revision = Revision, superseded = true };
148新增: }
149新增: if (paths != null)
150新增: {
151新增: var files = new StringCollection(); files.AddRange(paths); Clipboard.SetFileDropList(files);
152新增: }
153新增: else if (request.Text("png") is { Length: > 0 } png)
154新增: {
155新增: var bytes = Convert.FromBase64String(png);
156新增: if (bytes.Length > 20 * 1024 * 1024) throw new InvalidDataException("图片不能超过 20 MB");
157新增: using var input = new MemoryStream(bytes);
158新增: using var image = Image.FromStream(input);
159新增: if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("图片不能超过 4000 万像素");
160新增: Clipboard.SetImage(image);
161新增: }
162新增: else if (request.TryGetProperty("text", out var text))
163新增: {
164新增: var value = text.GetString() ?? "";
165新增: if (System.Text.Encoding.UTF8.GetByteCount(value) > 2 * 1024 * 1024) throw new InvalidDataException("文本不能超过 2 MB");
166新增: if (value.Length == 0) Clipboard.Clear(); else Clipboard.SetText(value);
167新增: }
168新增: else throw new InvalidDataException("剪贴板格式无效");
169新增: var writtenRevision = Revision;
170新增: if (cache.Length != 0) { try { await Cache("publish", cache); } catch { } }
171新增: return new { revision = writtenRevision };
172新增: }
173新增: finally { pending.Remove(cache); await Collect(); }
174新增: }
175新增:}
新增desktop/windows/TrayMenu.cs+35 −0看文件
@@ -0,0 +1,35 @@
1新增:using System.ComponentModel;
2新增:
3新增:namespace Cage.Windows;
4新增:
5新增:internal sealed class TrayMenu : ContextMenuStrip
6新增:{
7新增: public TrayMenu()
8新增: {
9新增: ShowImageMargin = false;
10新增: ShowCheckMargin = false;
11新增: DropShadowEnabled = true;
12新增: Font = new Font(SystemFonts.MenuFont!.FontFamily, 9.5f, FontStyle.Regular, GraphicsUnit.Point);
13新增: }
14新增:
15新增: protected override void OnOpening(CancelEventArgs e)
16新增: {
17新增: base.OnOpening(e);
18新增: Padding = new Padding(LogicalToDeviceUnits(6));
19新增: int width = LogicalToDeviceUnits(208);
20新增: foreach (ToolStripItem item in Items)
21新增: {
22新增: if (item is ToolStripSeparator) continue;
23新增: item.Padding = new Padding(LogicalToDeviceUnits(12), LogicalToDeviceUnits(7),
24新增: LogicalToDeviceUnits(12), LogicalToDeviceUnits(7));
25新增: width = Math.Max(width, item.GetPreferredSize(Size.Empty).Width + Padding.Horizontal);
26新增: }
27新增: foreach (ToolStripItem item in Items)
28新增: {
29新增: int height = item is ToolStripSeparator ? LogicalToDeviceUnits(9) : item.GetPreferredSize(Size.Empty).Height;
30新增: item.AutoSize = false;
31新增: item.Size = new Size(width - Padding.Horizontal, height);
32新增: }
33新增: MinimumSize = new Size(width, 0);
34新增: }
35新增:}
修改desktop/windows/WindowChrome.cs+29 −3看文件
@@ -10,7 +10,7 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark
1010 internal static Color ContrastingText(Color value) =>
1111 value.GetBrightness() < 0.5 ? Color.White : Color.Black;
1212
13删除: internal void Apply(IntPtr window, MenuStrip menus)
13新增: internal void Apply(IntPtr window, MenuStrip? menus)
1414 {
1515 bool accessible = SystemInformation.HighContrast;
1616 int darkFrame = dark && !accessible ? 1 : 0;
@@ -23,9 +23,15 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark
2323 DwmSetWindowAttribute(window, 36, ref text, sizeof(int)); // DWMWA_TEXT_COLOR
2424 }
2525
26新增: if (menus != null) ApplyMenu(menus);
27新增: }
28新增:
29新增: internal void ApplyMenu(ToolStrip menu)
30新增: {
31新增: bool accessible = SystemInformation.HighContrast;
2632 ToolStripRenderer renderer = accessible ? new ToolStripSystemRenderer()
2733 : new MenuRenderer(background, foreground);
28删除: ApplyMenu(menus, renderer, accessible);
34新增: ApplyMenu(menu, renderer, accessible);
2935 }
3036
3137 private void ApplyMenu(ToolStrip menu, ToolStripRenderer renderer, bool accessible)
@@ -56,7 +62,27 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark
5662 {
5763 if (!e.Item.Selected && !e.Item.Pressed) return;
5864 using var brush = new SolidBrush(highlight);
59删除: e.Graphics.FillRectangle(brush, new Rectangle(Point.Empty, e.Item.Size));
65新增: var bounds = new Rectangle(Point.Empty, e.Item.Size);
66新增: if (e.ToolStrip is ToolStripDropDown)
67新增: {
68新增: bounds.Inflate(-2, -1);
69新增: e.Graphics.FillRoundedRectangle(brush, bounds, new Size(5, 5));
70新增: }
71新增: else e.Graphics.FillRectangle(brush, bounds);
72新增: }
73新增:
74新增: protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
75新增: {
76新增: using var pen = new Pen(highlight);
77新增: int y = e.Item.Height / 2;
78新增: e.Graphics.DrawLine(pen, 10, y, e.Item.Width - 10, y);
79新增: }
80新增:
81新增: protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e)
82新增: {
83新增: if (e.ToolStrip is not ToolStripDropDown) return;
84新增: using var pen = new Pen(highlight);
85新增: e.Graphics.DrawRectangle(pen, 0, 0, e.ToolStrip.Width - 1, e.ToolStrip.Height - 1);
6086 }
6187
6288 protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
新增desktop/windows/WindowLayout.cs+35 −0看文件
@@ -0,0 +1,35 @@
1新增:using System.Drawing;
2新增:
3新增:namespace Cage.Windows;
4新增:
5新增:internal sealed record WindowPlacement(int X, int Y, int Width, int Height, int Dpi, bool Maximized);
6新增:
7新增:internal static class WindowLayout
8新增:{
9新增: public static Size Minimum(Rectangle work, int dpi) => new(
10新增: Math.Min(work.Width, (int)Math.Round(820 * dpi / 96.0)),
11新增: Math.Min(work.Height, (int)Math.Round(580 * dpi / 96.0)));
12新增:
13新增: public static Rectangle Bounds(Rectangle work, int dpi, WindowPlacement? saved)
14新增: {
15新增: var minimum = Minimum(work, dpi);
16新增: int width, height, x, y;
17新增: if (saved is { Width: > 0, Height: > 0, Dpi: > 0 })
18新增: {
19新增: width = (int)Math.Round(saved.Width * dpi / (double)saved.Dpi);
20新增: height = (int)Math.Round(saved.Height * dpi / (double)saved.Dpi);
21新增: x = saved.X; y = saved.Y;
22新增: }
23新增: else
24新增: {
25新增: var scale = Math.Min(work.Width * .85 / 1280, work.Height * .85 / 850);
26新增: width = (int)Math.Round(1280 * scale); height = (int)Math.Round(850 * scale);
27新增: x = work.Left + (work.Width - width) / 2;
28新增: y = work.Top + (work.Height - height) / 2;
29新增: }
30新增: width = Math.Clamp(width, minimum.Width, work.Width);
31新增: height = Math.Clamp(height, minimum.Height, work.Height);
32新增: return new Rectangle(Math.Clamp(x, work.Left, work.Right - width),
33新增: Math.Clamp(y, work.Top, work.Bottom - height), width, height);
34新增: }
35新增:}
修改packaging/windows/dependencies.json+7 −0看文件
@@ -48,5 +48,12 @@
4848 "prefix": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64/",
4949 "file": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64-source.tar",
5050 "hash": "b16ca2d09d66de17269f4b85d7823e82e8a42c591fc7b75047047170d095da03"
51新增: },
52新增: "qemuKeycodemap": {
53新增: "version": "f5772a62ec52591ff6870b7e8ef32482371f22c6",
54新增: "file": "keycodemapdb.tar.gz",
55新增: "url": "https://gitlab.com/qemu-project/keycodemapdb/-/archive/f5772a62ec52591ff6870b7e8ef32482371f22c6/keycodemapdb-f5772a62ec52591ff6870b7e8ef32482371f22c6.tar.gz",
56新增: "algorithm": "SHA256",
57新增: "hash": "d014b53382dbb17b8196ad12f50de7f20d0ef1b9f7d54b0be51a6cbb14209195"
5158 }
5259}
新增patches/gvisor-tap-vsock/0005-ipv6-guest-link-drop.patch+95 −0看文件
@@ -0,0 +1,95 @@
1新增:--- a/pkg/tap/switch.go
2新增:+++ b/pkg/tap/switch.go
3新增:@@ -33,6 +33,8 @@
4新增: }
5新增:
6新增: type Switch struct {
7新增:+ droppedIPv6 func([]byte)
8新增:+
9新增: Sent uint64
10新增: Received uint64
11新增:
12新增:@@ -59,6 +61,9 @@
13新增: cam: make(map[tcpip.LinkAddress]int),
14新增: }
15新增: }
16新增:+
17新增:+// SetDroppedIPv6 is configured before Accept, only for an IPv4-only stack.
18新增:+func (e *Switch) SetDroppedIPv6(observe func([]byte)) { e.droppedIPv6 = observe }
19新增:
20新增: func (e *Switch) CAM() map[string]int {
21新增: e.camLock.RLock()
22新增:@@ -275,7 +280,15 @@
23新增: log.Info(packet.String())
24新增: }
25新增:
26新增:+ if len(buf) < header.EthernetMinimumSize {
27新增:+ return
28新增:+ }
29新增: eth := header.Ethernet(buf)
30新增:+ if e.droppedIPv6 != nil && eth.Type() == header.IPv6ProtocolNumber {
31新增:+ e.droppedIPv6(buf[header.EthernetMinimumSize:])
32新增:+ atomic.AddUint64(&e.Received, uint64(len(buf)))
33新增:+ return
34新增:+ }
35新增:
36新增: e.camLock.Lock()
37新增: _, exists := e.cam[eth.SourceAddress()]
38新增:--- a/pkg/types/configuration.go
39新增:+++ b/pkg/types/configuration.go
40新增:@@ -20,6 +20,10 @@
41新增: type DialContext func(context.Context, string, string) (net.Conn, error)
42新增:
43新增: type Configuration struct {
44新增:+ // DroppedIPv6 observes guest IPv6 payloads discarded at ingress by an
45新增:+ // IPv4-only stack. It does not receive frames when IPv6 is supported.
46新增:+ DroppedIPv6 func([]byte) `yaml:"-" json:"-"`
47新增:+
48新增: DialContext DialContext `yaml:"-"`
49新增: DNSExchange func(context.Context, *dns.Msg) (*dns.Msg, error) `yaml:"-"`
50新增: // Print packets on stderr
51新增:--- a/pkg/virtualnetwork/virtualnetwork.go
52新增:+++ b/pkg/virtualnetwork/virtualnetwork.go
53新增:@@ -12,6 +12,7 @@
54新增: "github.com/containers/gvisor-tap-vsock/pkg/tap"
55新增: "github.com/containers/gvisor-tap-vsock/pkg/types"
56新增: "gvisor.dev/gvisor/pkg/tcpip"
57新增:+ "gvisor.dev/gvisor/pkg/tcpip/header"
58新增: "gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
59新增: "gvisor.dev/gvisor/pkg/tcpip/network/arp"
60新增: "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
61新增:@@ -78,6 +79,9 @@
62新增: return nil, fmt.Errorf("cannot create network stack: %w", err)
63新增: }
64新增:
65新增:+ if configuration.DroppedIPv6 != nil && stack.NetworkProtocolInstance(header.IPv6ProtocolNumber) == nil {
66新增:+ networkSwitch.SetDroppedIPv6(configuration.DroppedIPv6)
67新增:+ }
68新增: mux, err := addServices(configuration, stack, ipPool)
69新增: if err != nil {
70新增: return nil, fmt.Errorf("cannot add network services: %w", err)
71新增:--- /dev/null
72新增:+++ b/pkg/tap/ipv6_drop_test.go
73新增:@@ -0,0 +1,22 @@
74新增:+package tap
75新增:+
76新增:+import (
77新增:+ "bytes"
78新增:+ "context"
79新增:+ "testing"
80新增:+)
81新增:+
82新增:+// The observer must run on data read from the guest, before forwarding the
83新增:+// frame to any other peer or to the IPv4 stack.
84新增:+func TestIPv6DropAtGuestIngress(t *testing.T) {
85新增:+ s := NewSwitch(false)
86新增:+ payload := []byte{0x60, 0, 0, 0, 0, 0, 17, 1}
87新增:+ ethernet := make([]byte, 14)
88新增:+ ethernet[12], ethernet[13] = 0x86, 0xdd
89新增:+ var seen []byte
90新增:+ s.SetDroppedIPv6(func(packet []byte) { seen = append(seen, packet...) })
91新增:+ s.rxBuf(context.Background(), 1, append(ethernet, payload...))
92新增:+ if !bytes.Equal(seen, payload) || s.Sent != 0 || s.Received != uint64(len(ethernet)+len(payload)) {
93新增:+ t.Fatal("IPv6 frame was not observed and dropped at ingress")
94新增:+ }
95新增:+}
新增patches/qemu/0001-windows-balloon-discard.patch+322 −0看文件
@@ -0,0 +1,322 @@
1新增:--- a/accel/stubs/whpx-stub.c
2新增:+++ b/accel/stubs/whpx-stub.c
3新增:@@ -11,3 +11,8 @@
4新增:
5新增: bool whpx_allowed;
6新增: bool whpx_irqchip_in_kernel;
7新增:+
8新增:+int whpx_balloon_mapping(bool add, void *host, uint64_t guest, size_t size)
9新增:+{
10新增:+ return -ENOSYS;
11新增:+}
12新增:--- a/accel/whpx/whpx-common.c
13新增:+++ b/accel/whpx/whpx-common.c
14新增:@@ -284,6 +284,25 @@
15新增: * Memory support.
16新增: */
17新增:
18新增:+int whpx_balloon_mapping(bool add, void *host, uint64_t guest, size_t size)
19新增:+{
20新增:+ HRESULT hr;
21新增:+
22新增:+ if (add) {
23新增:+ hr = whp_dispatch.WHvMapGpaRange(whpx_global.partition, host, guest, size,
24新增:+ WHvMapGpaRangeFlagRead | WHvMapGpaRangeFlagWrite |
25新增:+ WHvMapGpaRangeFlagExecute);
26新增:+ } else {
27新增:+ hr = whp_dispatch.WHvUnmapGpaRange(whpx_global.partition, guest, size);
28新增:+ }
29新增:+ if (FAILED(hr)) {
30新增:+ error_report_once("WHPX balloon %s failed (0x%08lx)",
31新增:+ add ? "map" : "unmap", (unsigned long)hr);
32新增:+ return -EIO;
33新增:+ }
34新增:+ return 0;
35新增:+}
36新增:+
37新增: static void whpx_set_phys_mem(MemoryRegionSection *section, bool add)
38新增: {
39新增: struct whpx_state *whpx = &whpx_global;
40新增:--- a/hw/virtio/virtio-balloon.c
41新增:+++ b/hw/virtio/virtio-balloon.c
42新增:@@ -18,6 +18,8 @@
43新增: #include "qemu/module.h"
44新增: #include "qemu/timer.h"
45新增: #include "qemu/madvise.h"
46新增:+#include "qemu/main-loop.h"
47新增:+#include "system/whpx.h"
48新增: #include "hw/virtio/virtio.h"
49新增: #include "hw/mem/pc-dimm.h"
50新增: #include "hw/core/qdev-properties.h"
51新增:@@ -76,9 +78,114 @@
52新增: migration_in_bg_snapshot();
53新增: }
54新增:
55新增:+typedef struct BalloonDiscardBatch BalloonDiscardBatch;
56新增:+
57新增:+#ifdef _WIN32
58新增:+typedef struct BalloonDiscardRange {
59新增:+ RAMBlock *rb;
60新增:+ MemoryRegion *mr;
61新增:+ ram_addr_t offset;
62新增:+ hwaddr guest;
63新增:+ size_t size;
64新增:+} BalloonDiscardRange;
65新增:+
66新增:+struct BalloonDiscardBatch {
67新增:+ BalloonDiscardRange ranges[256];
68新增:+ size_t count;
69新增:+};
70新增:+
71新增:+static void balloon_windows_discard(RAMBlock *rb, ram_addr_t offset,
72新增:+ hwaddr guest, size_t size)
73新增:+{
74新增:+ void *addr = qemu_ram_get_host_addr(rb) + offset;
75新增:+
76新增:+ /* WHPX must release its backing before Windows can reclaim these pages. */
77新增:+ if (whpx_enabled() && whpx_balloon_mapping(false, addr, guest, size) < 0) {
78新增:+ return;
79新增:+ }
80新增:+ if (!VirtualFree(addr, size, MEM_DECOMMIT)) {
81新增:+ error_report_once("Could not decommit Windows balloon pages (error %lu)",
82新增:+ (unsigned long)GetLastError());
83新增:+ } else if (!VirtualAlloc(addr, size, MEM_COMMIT, PAGE_READWRITE)) {
84新增:+ /* RAMBlock users require accessible host addresses even while the guest
85新增:+ * lends these pages to the balloon. Windows allocates backing on touch. */
86新增:+ error_report("Could not recommit Windows balloon pages (error %lu)",
87新增:+ (unsigned long)GetLastError());
88新增:+ exit(1);
89新增:+ }
90新增:+ if (whpx_enabled() && whpx_balloon_mapping(true, addr, guest, size) < 0) {
91新增:+ /* Resume only after the guest can access the recommitted range. */
92新增:+ exit(1);
93新增:+ }
94新增:+}
95新增:+
96新增:+static int balloon_discard_range_compare(const void *left, const void *right)
97新增:+{
98新增:+ const BalloonDiscardRange *a = left;
99新增:+ const BalloonDiscardRange *b = right;
100新增:+
101新增:+ if (a->rb != b->rb) {
102新增:+ return (uintptr_t)a->rb < (uintptr_t)b->rb ? -1 : 1;
103新增:+ }
104新增:+ return (a->offset > b->offset) - (a->offset < b->offset);
105新增:+}
106新增:+
107新增:+static void balloon_discard_batch_flush(BalloonDiscardBatch *batch)
108新增:+{
109新增:+ size_t i = 0;
110新增:+
111新增:+ qsort(batch->ranges, batch->count, sizeof(batch->ranges[0]),
112新增:+ balloon_discard_range_compare);
113新增:+ while (i < batch->count) {
114新增:+ BalloonDiscardRange *first = &batch->ranges[i++];
115新增:+ ram_addr_t end = first->offset + first->size;
116新增:+
117新增:+ while (i < batch->count && batch->ranges[i].rb == first->rb &&
118新增:+ batch->ranges[i].offset <= end &&
119新增:+ batch->ranges[i].guest == first->guest +
120新增:+ batch->ranges[i].offset - first->offset) {
121新增:+ end = MAX(end, batch->ranges[i].offset + batch->ranges[i].size);
122新增:+ i++;
123新增:+ }
124新增:+ balloon_windows_discard(first->rb, first->offset, first->guest,
125新增:+ end - first->offset);
126新增:+ }
127新增:+ for (i = 0; i < batch->count; i++) {
128新增:+ memory_region_unref(batch->ranges[i].mr);
129新增:+ }
130新增:+ batch->count = 0;
131新增:+}
132新增:+#endif
133新增:+
134新增:+/* Balloon and free-page reporting hand over unused guest pages. Their
135新增:+ * contents are unspecified when the guest takes them back. */
136新增:+static void balloon_discard_range(RAMBlock *rb, ram_addr_t offset, size_t size,
137新增:+ MemoryRegion *mr, BalloonDiscardBatch *batch,
138新增:+ hwaddr guest)
139新增:+{
140新增:+#ifdef _WIN32
141新增:+ /* Batch adjacent pages to reduce Windows memory operations. Retain each region
142新增:+ * until the batch is complete, before acknowledging the virtqueue entry. */
143新增:+ if (batch) {
144新增:+ if (batch->count == ARRAY_SIZE(batch->ranges)) {
145新增:+ balloon_discard_batch_flush(batch);
146新增:+ }
147新增:+ memory_region_ref(mr);
148新增:+ batch->ranges[batch->count++] = (BalloonDiscardRange) {
149新增:+ .rb = rb, .mr = mr, .offset = offset, .guest = guest, .size = size,
150新增:+ };
151新增:+ } else {
152新增:+ balloon_windows_discard(rb, offset, guest, size);
153新增:+ }
154新增:+#else
155新增:+ ram_block_discard_range(rb, offset, size);
156新增:+#endif
157新增:+}
158新增:+
159新增: static void balloon_inflate_page(VirtIOBalloon *balloon,
160新增: MemoryRegion *mr, hwaddr mr_offset,
161新增:- PartiallyBalloonedPage *pbp)
162新增:+ PartiallyBalloonedPage *pbp,
163新增:+ BalloonDiscardBatch *batch, hwaddr guest)
164新增: {
165新增: void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
166新增: ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
167新增:@@ -94,7 +201,7 @@
168新增: if (rb_page_size == BALLOON_PAGE_SIZE) {
169新增: /* Easy case */
170新增:
171新增:- ram_block_discard_range(rb, rb_offset, rb_page_size);
172新增:+ balloon_discard_range(rb, rb_offset, rb_page_size, mr, batch, guest);
173新增: /* We ignore errors from ram_block_discard_range(), because it
174新增: * has already reported them, and failing to discard a balloon
175新增: * page is not fatal */
176新增:@@ -133,7 +240,8 @@
177新增: /* We've accumulated a full host page, we can actually discard
178新增: * it now */
179新增:
180新增:- ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
181新增:+ balloon_discard_range(rb, rb_aligned_offset, rb_page_size, mr, batch,
182新增:+ guest - (rb_offset - rb_aligned_offset));
183新增: /* We ignore errors from ram_block_discard_range(), because it
184新增: * has already reported them, and failing to discard a balloon
185新增: * page is not fatal */
186新增:@@ -144,6 +252,7 @@
187新增: static void balloon_deflate_page(VirtIOBalloon *balloon,
188新增: MemoryRegion *mr, hwaddr mr_offset)
189新增: {
190新增:+#ifndef _WIN32
191新增: void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
192新增: ram_addr_t rb_offset;
193新增: RAMBlock *rb;
194新增:@@ -166,6 +275,8 @@
195新增: strerror(errno));
196新增: /* Otherwise ignore, failing to page hint shouldn't be fatal */
197新增: }
198新增:+#endif
199新增:+ /* Windows recommits and remaps during inflation. Backing is demand-zero. */
200新增: }
201新增:
202新增: /*
203新增:@@ -389,7 +500,7 @@
204新增: continue;
205新增: }
206新增:
207新增:- ram_block_discard_range(rb, ram_offset, size);
208新增:+ balloon_discard_range(rb, ram_offset, size, NULL, NULL, elem->in_addr[i]);
209新增: }
210新增:
211新增: skip_element:
212新增:@@ -407,6 +518,12 @@
213新增:
214新增: for (;;) {
215新增: PartiallyBalloonedPage pbp = {};
216新增:+#ifdef _WIN32
217新增:+ BalloonDiscardBatch batch = {};
218新增:+ BalloonDiscardBatch *discard_batch = &batch;
219新增:+#else
220新增:+ BalloonDiscardBatch *discard_batch = NULL;
221新增:+#endif
222新增: size_t offset = 0;
223新增: uint32_t pfn;
224新增:
225新增:@@ -441,7 +558,9 @@
226新增: if (!virtio_balloon_inhibited()) {
227新增: if (vq == s->ivq) {
228新增: balloon_inflate_page(s, section.mr,
229新增:- section.offset_within_region, &pbp);
230新增:+ section.offset_within_region, &pbp,
231新增:+ discard_batch,
232新增:+ section.offset_within_address_space);
233新增: } else if (vq == s->dvq) {
234新增: balloon_deflate_page(s, section.mr, section.offset_within_region);
235新增: } else {
236新增:@@ -451,12 +570,31 @@
237新增: memory_region_unref(section.mr);
238新增: }
239新增:
240新增:+#ifdef _WIN32
241新增:+ balloon_discard_batch_flush(&batch);
242新增:+#endif
243新增: virtqueue_push(vq, elem, 0);
244新增: virtio_notify(vdev, vq);
245新增: g_free(elem);
246新增: virtio_balloon_pbp_free(&pbp);
247新增:- }
248新增:-}
249新增:+#ifdef _WIN32
250新增:+ /* Let network and control I/O run between memory batches. */
251新增:+ if (vq == s->ivq) {
252新增:+ qemu_bh_schedule(s->balloon_bh);
253新增:+ break;
254新增:+ }
255新增:+#endif
256新增:+ }
257新增:+}
258新增:+
259新增:+#ifdef _WIN32
260新增:+static void virtio_balloon_memory_bh(void *opaque)
261新增:+{
262新增:+ VirtIOBalloon *s = opaque;
263新增:+
264新增:+ virtio_balloon_handle_output(VIRTIO_DEVICE(s), s->ivq);
265新增:+}
266新增:+#endif
267新增:
268新增: static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
269新增: {
270新增:@@ -887,6 +1025,10 @@
271新增: return;
272新增: }
273新增:
274新增:+#ifdef _WIN32
275新增:+ s->balloon_bh = qemu_bh_new_guarded(virtio_balloon_memory_bh, s,
276新增:+ &dev->mem_reentrancy_guard);
277新增:+#endif
278新增: s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
279新增: s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
280新增: s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
281新增:@@ -918,6 +1060,9 @@
282新增: VirtIOBalloon *s = VIRTIO_BALLOON(dev);
283新增:
284新增: qemu_unregister_resettable(OBJECT(dev));
285新增:+#ifdef _WIN32
286新增:+ qemu_bh_delete(s->balloon_bh);
287新增:+#endif
288新增: if (s->free_page_bh) {
289新增: qemu_bh_delete(s->free_page_bh);
290新增: object_unref(OBJECT(s->iothread));
291新增:@@ -942,6 +1087,9 @@
292新增: static void virtio_balloon_device_reset(VirtIODevice *vdev)
293新增: {
294新增: VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
295新增:+#ifdef _WIN32
296新增:+ qemu_bh_cancel(s->balloon_bh);
297新增:+#endif
298新增:
299新增: if (virtio_balloon_free_page_support(s)) {
300新增: virtio_balloon_free_page_stop(s);
301新增:--- a/include/hw/virtio/virtio-balloon.h
302新增:+++ b/include/hw/virtio/virtio-balloon.h
303新增:@@ -54,6 +54,9 @@
304新增: QEMUTimer *stats_timer;
305新增: IOThread *iothread;
306新增: QEMUBH *free_page_bh;
307新增:+#ifdef _WIN32
308新增:+ QEMUBH *balloon_bh;
309新增:+#endif
310新增: /*
311新增: * Lock to synchronize threads to access the free page reporting related
312新增: * fields (e.g. free_page_hint_status).
313新增:--- a/include/system/whpx.h
314新增:+++ b/include/system/whpx.h
315新增:@@ -24,6 +24,7 @@
316新增: #endif /* COMPILING_PER_TARGET */
317新增:
318新增: #ifdef CONFIG_WHPX_IS_POSSIBLE
319新增:+int whpx_balloon_mapping(bool add, void *host, uint64_t guest, size_t size);
320新增: extern bool whpx_allowed;
321新增: extern bool whpx_irqchip_in_kernel;
322新增: #define whpx_enabled() (whpx_allowed)
修改scripts/build-app.sh+43 −18看文件
@@ -2,15 +2,26 @@
22set -euo pipefail
33cd "$(dirname "$0")/.."
44if [[ "$(uname -s)" != Darwin ]]; then echo 'Cage.app must be built on macOS.' >&2; exit 1; fi
5删除:case "${1:-}" in ''|--install) ;; *) echo 'Usage: scripts/build-app.sh [--install]' >&2; exit 2 ;; esac
6删除:app_destination="${CAGE_BUILD_OUTPUT:-$PWD/_output/Cage.app}"
5新增:case "${1:-}" in ''|--install|--macos-trial|--install-macos-trial) ;; *) echo 'Usage: scripts/build-app.sh [--install|--macos-trial|--install-macos-trial]' >&2; exit 2 ;; esac
6新增:bundle_id=io.github.lee-xeo.claude-cage
7新增:app_name=Cage
8新增:if [[ "${1:-}" == *macos-trial ]]; then
9新增: bundle_id+=.macos-trial
10新增: app_name='Cage macOS'
11新增:fi
12新增:installed_app="$HOME/Applications/$app_name.app"
13新增:app_destination="${CAGE_BUILD_OUTPUT:-$PWD/_output/$app_name.app}"
714if [[ "$app_destination" != /*.app ]]; then echo 'CAGE_BUILD_OUTPUT must be an absolute .app path.' >&2; exit 2; fi
815check_destination() {
916 local target="$1"
1017 [[ ! -e "$target" ]] && return 0
11删除: if [[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$target/Contents/Info.plist" 2>/dev/null)" != io.github.lee-xeo.claude-cage ]]; then
18新增: if [[ "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$target/Contents/Info.plist" 2>/dev/null)" != "$bundle_id" ]]; then
1219 echo 'Build destination is not a Cage application.' >&2; exit 1
1320 fi
21新增: if ! codesign --verify --deep --strict "$target"; then
22新增: echo '现有 Cage 应用包含修改内容或无法验证完整性,已保留。请将个人文件移出应用包,或选择新的构建目录后重试。' >&2
23新增: exit 1
24新增: fi
1425 local running_pids
1526 running_pids="$(/usr/sbin/lsof -t "$target/Contents/MacOS/Cage" "$target/Contents/Resources/cage" 2>/dev/null || true)"
1627 if [[ -n "$running_pids" ]]; then
@@ -18,7 +29,7 @@ check_destination() {
1829 fi
1930}
2031check_destination "$app_destination"
21删除:if [[ "${1:-}" == --install ]]; then check_destination "$HOME/Applications/Cage.app"; fi
32新增:if [[ "${1:-}" == --install* ]]; then check_destination "$installed_app"; fi
2233version="$(tr -d '\n\r' < VERSION)"
2334if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then echo 'Invalid VERSION.' >&2; exit 1; fi
2435short_version="${version%%-*}"
@@ -31,15 +42,24 @@ export MACOSX_DEPLOYMENT_TARGET=14.0
3142export CGO_CFLAGS="${CGO_CFLAGS:-} -mmacosx-version-min=14.0"
3243export CGO_LDFLAGS="${CGO_LDFLAGS:-} -mmacosx-version-min=14.0"
3344bash scripts/fetch-proxy-core.sh
34删除:make cage VERSION="$version"
45新增:if [[ "$(uname -m)" == arm64 ]]; then
46新增: bash scripts/guest-os/build-macos-guest-core.sh "$version"
47新增:else
48新增: make cage VERSION="$version"
49新增:fi
50新增:_output/bin/cage verify-web-assets
3551build_stage="$(mktemp -d "$PWD/_output/app-build.XXXXXX")"
3652install_stage=''
3753trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT
3854bundle="$build_stage/Cage.app"
3955mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources"
40删除:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication desktop/Cage.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift -o "$bundle/Contents/MacOS/Cage"
56新增:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication desktop/Cage.swift desktop/MacKeyboard.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift desktop/MacGuestLogin.swift -o "$bundle/Contents/MacOS/Cage"
4157swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework Security desktop/Updates.swift desktop/UpdateInstaller.swift -o "$bundle/Contents/Resources/CageUpdateInstaller"
4258cp _output/bin/cage "$bundle/Contents/Resources/cage"
59新增:if [[ "$(uname -m)" == arm64 ]]; then "$bundle/Contents/Resources/cage" verify-macos-guest; fi
60新增:if [[ "$(uname -m)" == arm64 ]]; then
61新增: bash scripts/guest-os/package-macos-guest.sh "$bundle/Contents/Resources/guest-os"
62新增:fi
4363node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources"
4464cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo"
4565for executable in "$bundle/Contents/MacOS/Cage" "$bundle/Contents/Resources/CageUpdateInstaller" "$bundle/Contents/Resources/cage" "$bundle/Contents/Resources/mihomo"; do
@@ -58,9 +78,9 @@ cat > "$bundle/Contents/Info.plist" <<PLIST
5878<?xml version="1.0" encoding="UTF-8"?>
5979<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
6080<plist version="1.0"><dict>
61删除:<key>CFBundleName</key><string>Cage</string>
62删除:<key>CFBundleDisplayName</key><string>Cage</string>
63删除:<key>CFBundleIdentifier</key><string>io.github.lee-xeo.claude-cage</string>
81新增:<key>CFBundleName</key><string>$app_name</string>
82新增:<key>CFBundleDisplayName</key><string>$app_name</string>
83新增:<key>CFBundleIdentifier</key><string>$bundle_id</string>
6484<key>CFBundleVersion</key><string>$build_version</string>
6585<key>CFBundleShortVersionString</key><string>$short_version</string>
6686<key>CageVersion</key><string>$version</string>
@@ -98,26 +118,31 @@ if ! mv "$bundle" "$app_destination"; then
98118fi
99119bundle="$app_destination"
100120printf 'Built: %s\n' "$bundle"
101删除:if [[ "${1:-}" == "--install" ]]; then
121新增:if [[ "${1:-}" == --install* ]]; then
102122 mkdir -p "$HOME/Applications"
103123 install_stage="$(mktemp -d "$HOME/Applications/.Cage-install.XXXXXX")"
104124 ditto "$bundle" "$install_stage/Cage.app"
105125 codesign --verify --deep --strict --verbose=2 "$install_stage/Cage.app"
106删除: check_destination "$HOME/Applications/Cage.app"
107删除: if [[ -e "$HOME/Applications/Cage.app" ]]; then mv "$HOME/Applications/Cage.app" "$install_stage/previous.app"; fi
108删除: if ! mv "$install_stage/Cage.app" "$HOME/Applications/Cage.app"; then
109删除: if [[ -d "$install_stage/previous.app" ]]; then mv "$install_stage/previous.app" "$HOME/Applications/Cage.app"; fi
126新增: check_destination "$installed_app"
127新增: if [[ -e "$installed_app" ]]; then mv "$installed_app" "$install_stage/previous.app"; fi
128新增: if ! mv "$install_stage/Cage.app" "$installed_app"; then
129新增: if [[ -d "$install_stage/previous.app" ]]; then mv "$install_stage/previous.app" "$installed_app"; fi
110130 exit 1
111131 fi
112删除: printf 'Installed: %s/Applications/Cage.app\n' "$HOME"
132新增: printf 'Installed: %s\n' "$installed_app"
113133 # An installed build has one launchable copy. Remove the staging build too,
114134 # along with historical validation copies, after the installed App verifies.
115删除: codesign --verify --deep --strict --verbose=2 "$HOME/Applications/Cage.app"
116删除: node scripts/cleanup-apps.mjs --keep "$HOME/Applications/Cage.app" \
135新增: codesign --verify --deep --strict --verbose=2 "$installed_app"
136新增: if [[ "${1:-}" == --install-macos-trial ]]; then
137新增: # Normal release cleanup scans other Cage installations. The trial has a separate identity.
138新增: if [[ ! "$bundle" -ef "$installed_app" ]]; then mv "$bundle" "$build_stage/installed-trial.app"; fi
139新增: exit 0
140新增: fi
141新增: node scripts/cleanup-apps.mjs --keep "$installed_app" \
117142 --root "$bundle" --root "$PWD/_output" --root "$HOME/Applications" \
118143 --root /Applications --root "$HOME/.claude-cage-validation"
119144else
120删除: if [[ -z "${CAGE_BUILD_OUTPUT:-}" ]]; then
145新增: if [[ -z "${CAGE_BUILD_OUTPUT:-}" && "${1:-}" != --macos-trial ]]; then
121146 node scripts/cleanup-apps.mjs --keep "$bundle" --root "$PWD/_output"
122147 fi
123148fi
修改scripts/build-client-windows.ps1+5 −0看文件
@@ -28,6 +28,7 @@ try {
2828 Invoke-BuildTool $npm @('--prefix', 'ui', 'run', 'build')
2929 }
3030 if (-not (Test-Path -LiteralPath 'internal/workbench/web/index.html')) { throw 'Build the UI before using -SkipUI.' }
31新增: if ($SkipUI) { Invoke-BuildTool $node @('ui/scripts/verify-build.mjs') }
3132 $env:GOOS = 'windows'; $env:GOARCH = 'amd64'; $env:CGO_ENABLED = '0'
3233 $goDependencies = & $go 'list' '-deps' './cmd/cage-client'
3334 if ($LASTEXITCODE -ne 0 -or ($goDependencies -match 'internal/limaembed|github.com/lima-vm/lima/v2|github.com/Code-Hex/vz')) { throw 'Client dependency check failed or includes a virtual machine runtime.' }
@@ -74,6 +75,10 @@ Cage 轻量远程客户端(未签名开发构建)
7475此目录为独立构建产物,不会安装、替换完整 Cage 或自动下载完整 Cage 更新。
7576本构建未签名或发布。Windows 原生运行验收范围以项目测试报告为准。
7677'@)
78新增: if ($IsWindows) {
79新增: Invoke-BuildTool (Join-Path $resources 'cage.exe') @('verify-web-assets')
80新增: Assert-WindowsWorkbench $app
81新增: }
7782 Compress-Archive -Path $app -DestinationPath (Join-Path $result 'Cage-Client-windows-amd64.zip') -CompressionLevel Optimal
7883 if (Test-Path -LiteralPath $destination) { throw 'Client output already exists; no files were replaced.' }
7984 Move-Item -LiteralPath $result -Destination $destination
修改scripts/build-client.sh+4 −1看文件
@@ -24,6 +24,8 @@ destination="$output_root/build-$(date +%Y%m%d-%H%M%S)-$suffix"
2424if [[ "$skip_ui" == false ]]; then
2525 [[ -d ui/node_modules ]] || npm --prefix ui ci --no-audit --no-fund
2626 npm --prefix ui run build
27新增:else
28新增: node ui/scripts/verify-build.mjs
2729fi
2830[[ -f internal/workbench/web/index.html ]] || { echo 'Build the UI before using --skip-ui.' >&2; exit 1; }
2931go list -deps ./cmd/cage-client > "$stage/dependencies.txt"
@@ -31,6 +33,7 @@ if grep -Eq 'internal/limaembed|github.com/lima-vm/lima/v2|github.com/Code-Hex/v
3133 echo 'The client unexpectedly depends on a virtual machine runtime; build stopped.' >&2; exit 1
3234fi
3335CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=$version" -o "$stage/cage" ./cmd/cage-client
36新增:"$stage/cage" verify-web-assets
3437mkdir -p "$stage/result"
3538
3639if [[ "$platform" == macos ]]; then
@@ -38,7 +41,7 @@ if [[ "$platform" == macos ]]; then
3841 mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources"
3942 swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library \
4043 -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication \
41删除: desktop/Cage.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift \
44新增: desktop/Cage.swift desktop/MacKeyboard.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift desktop/MacGuestLogin.swift \
4245 -o "$bundle/Contents/MacOS/Cage"
4346 node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources"
4447 cp "$stage/cage" "$bundle/Contents/Resources/cage"
修改scripts/build-linux.sh+2 −1看文件
@@ -1,7 +1,7 @@
11#!/usr/bin/env bash
22set -euo pipefail
33cd "$(dirname "$0")/.."
4删除:[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { echo 'Build on x86_64 Linux (Debian 12 baseline).' >&2; exit 1; }
4新增:[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { echo 'Build on x86_64 Linux (Ubuntu 22.04 baseline).' >&2; exit 1; }
55case "${1:-}" in ''|--prebuilt-backend) ;; *) echo 'Usage: scripts/build-linux.sh [--prebuilt-backend]' >&2; exit 2 ;; esac
66version=$(tr -d '\r\n' < VERSION)
77[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { echo 'Invalid VERSION.' >&2; exit 1; }
@@ -16,6 +16,7 @@ else
1616 [[ -x _output/bin/cage ]] || { echo 'Missing prebuilt Linux backend.' >&2; exit 1; }
1717 _output/bin/cage help >/dev/null
1818fi
19新增:_output/bin/cage verify-web-assets
1920mkdir -p _output/linux-amd64
2021stage=$(mktemp -d "$PWD/_output/linux-amd64/build.XXXXXX")
2122trap 'rm -rf "$stage"' EXIT
新增scripts/build-qemu-windows.ps1+65 −0看文件
@@ -0,0 +1,65 @@
1新增:#requires -Version 7.0
2新增:[CmdletBinding()]
3新增:param(
4新增: [string]$DependencyCache,
5新增: [string]$OutputDirectory,
6新增: [string]$MsysDirectory = $env:CAGE_MSYS2_ROOT
7新增:)
8新增:. (Join-Path $PSScriptRoot 'windows-common.ps1')
9新增:if (-not $IsWindows) { throw 'Build the Windows QEMU runtime in an MSYS2 UCRT64 environment on Windows.' }
10新增:$repository = Split-Path $PSScriptRoot -Parent
11新增:if (-not $DependencyCache) { $DependencyCache = Join-Path $repository '_output/windows-deps' }
12新增:if (-not $OutputDirectory) { $OutputDirectory = Join-Path $DependencyCache 'qemu-cage' }
13新增:$DependencyCache = [IO.Path]::GetFullPath($DependencyCache)
14新增:$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
15新增:$dependencies = Get-Content (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json
16新增:$patchDirectory = Join-Path $repository 'patches/qemu'
17新增:$inputs = @((Join-Path $PSScriptRoot 'build-qemu-windows.sh'), $PSCommandPath) + @(Get-ChildItem $patchDirectory -Filter '*.patch' | Sort-Object Name | ForEach-Object FullName)
18新增:$fingerprintText = $dependencies.qemuSource.hash + $dependencies.qemuKeycodemap.hash + (($inputs | ForEach-Object { (Get-FileHash $_ -Algorithm SHA256).Hash }) -join '')
19新增:$fingerprint = [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($fingerprintText)))
20新增:$manifestPath = Join-Path $OutputDirectory 'cage-build.json'
21新增:if (Test-Path $manifestPath) {
22新增: $manifest = Get-Content $manifestPath -Raw | ConvertFrom-Json
23新增: if ($manifest.fingerprint -eq $fingerprint) {
24新增: foreach ($file in $manifest.files) {
25新增: if ((Get-FileHash (Join-Path $OutputDirectory $file.name) -Algorithm SHA256).Hash -ne $file.sha256) {
26新增: throw 'The cached QEMU runtime differs from its build manifest. Use a new output directory.'
27新增: }
28新增: }
29新增: Write-Host "Verified Windows QEMU runtime at $OutputDirectory"
30新增: return
31新增: }
32新增:}
33新增:if (-not $MsysDirectory) {
34新增: $MsysDirectory = @('C:\msys64', 'D:\msys64') | Where-Object { Test-Path (Join-Path $_ 'ucrt64/bin/gcc.exe') } | Select-Object -First 1
35新增:}
36新增:if (-not $MsysDirectory -or -not (Test-Path (Join-Path $MsysDirectory 'ucrt64/bin/pkg-config.exe'))) {
37新增: throw 'Set CAGE_MSYS2_ROOT to MSYS2 with the UCRT64 QEMU build dependencies described in docs/windows.md.'
38新增:}
39新增:$archive = Get-VerifiedGitArchive $dependencies.qemuSource $DependencyCache
40新增:$stage = Join-Path $repository ('_output/windows-qemu-' + [guid]::NewGuid().ToString('N'))
41新增:New-Item -ItemType Directory -Path $stage -Force | Out-Null
42新增:Invoke-BuildTool 'tar.exe' @('-xf', $archive, '-C', $stage)
43新增:$source = Join-Path $stage $dependencies.qemuSource.prefix.TrimEnd('/')
44新增:$keymapArchive = Get-VerifiedDependency $dependencies.qemuKeycodemap $DependencyCache
45新增:Invoke-BuildTool 'tar.exe' @('-xf', $keymapArchive, '-C', (Join-Path $source 'subprojects'))
46新增:Move-Item (Join-Path $source ('subprojects/keycodemapdb-' + $dependencies.qemuKeycodemap.version)) (Join-Path $source 'subprojects/keycodemapdb')
47新增:$savedSystem, $savedHere = $env:MSYSTEM, $env:CHERE_INVOKING
48新增:try {
49新增: $env:MSYSTEM = 'UCRT64'
50新增: $env:CHERE_INVOKING = '1'
51新增: Invoke-BuildTool (Join-Path $MsysDirectory 'usr/bin/bash.exe') @('-l', (Join-Path $PSScriptRoot 'build-qemu-windows.sh'),
52新增: $source, (Join-Path $stage 'build'), (Join-Path $stage 'runtime'), $patchDirectory)
53新增: $built = Join-Path $stage 'runtime'
54新增: $files = @(Get-ChildItem $built -File | ForEach-Object {
55新增: @{ name = $_.Name; sha256 = (Get-FileHash $_.FullName -Algorithm SHA256).Hash }
56新增: })
57新增: @{ fingerprint = $fingerprint; source = $dependencies.qemuSource.commit; files = $files } |
58新增: ConvertTo-Json -Depth 4 | Set-Content (Join-Path $built 'cage-build.json')
59新增: New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
60新增: Copy-Item (Join-Path $built '*') $OutputDirectory -Force
61新增:} finally {
62新增: $env:MSYSTEM = $savedSystem
63新增: $env:CHERE_INVOKING = $savedHere
64新增:}
65新增:Write-Host "Built Windows QEMU runtime at $OutputDirectory"
新增scripts/build-qemu-windows.sh+37 −0看文件
@@ -0,0 +1,37 @@
1新增:#!/usr/bin/env bash
2新增:set -euo pipefail
3新增:
4新增:source_dir=$(cygpath -u "$1")
5新增:build_dir=$(cygpath -u "$2")
6新增:output_dir=$(cygpath -u "$3")
7新增:patch_dir=$(cygpath -u "$4")
8新增:
9新增:for patch_file in "$patch_dir"/*.patch; do
10新增: patch -d "$source_dir" -p1 < "$patch_file"
11新增:done
12新增:mkdir -p "$build_dir" "$output_dir"
13新增:cd "$build_dir"
14新增:"$source_dir/configure" --target-list=x86_64-softmmu --without-default-features \
15新增: --prefix=C:/CageQemu --bindir=. --datadir=share --with-suffix= \
16新增: --extra-cflags=-D_WIN32_WINNT=0x0A00 \
17新增: --enable-whpx --enable-tcg --enable-pixman --enable-slirp --enable-tools \
18新增: --disable-docs --disable-guest-agent --disable-werror \
19新增: --disable-debug-info
20新增:ninja -j 6 qemu-system-x86_64.exe qemu-img.exe
21新增:cp qemu-system-x86_64.exe qemu-img.exe "$output_dir/"
22新增:strip "$output_dir"/*.exe
23新增:
24新增:# Copy the DLL dependency closure from this toolchain, using the same versions
25新增:# that were linked into the executables. Windows system DLLs remain system-owned.
26新增:pending=("$output_dir"/*.exe)
27新增:while ((${#pending[@]})); do
28新增: binary=${pending[0]}
29新增: pending=("${pending[@]:1}")
30新增: while read -r dll; do
31新增: if [[ -f "$MINGW_PREFIX/bin/$dll" && ! -f "$output_dir/$dll" ]]; then
32新增: cp "$MINGW_PREFIX/bin/$dll" "$output_dir/$dll"
33新增: pending+=("$output_dir/$dll")
34新增: fi
35新增: done < <(objdump -p "$binary" | awk '/DLL Name:/ {print $3}')
36新增:done
37新增:pacman -Q > "$output_dir/build-packages.txt"
新增scripts/build-tailnet.sh+11 −0看文件
@@ -0,0 +1,11 @@
1新增:#!/usr/bin/env bash
2新增:# Build a guest-only payload without adding Tailscale's dependency graph to Cage.
3新增:set -euo pipefail
4新增:root=$(cd "$(dirname "$0")/.." && pwd)
5新增:[[ $# == 3 && $3 == /* ]] || { echo 'Usage: build-tailnet.sh OS ARCH /absolute/output' >&2; exit 2; }
6新增:os=$1 arch=$2 destination=$3
7新增:case "$os/$arch" in linux/amd64|linux/arm64|darwin/arm64|windows/amd64) ;; *) exit 2 ;; esac
8新增:mkdir -p "$(dirname "$destination")"
9新增:cd "$root/tools/tailnet"
10新增:GOOS=$os GOARCH=$arch CGO_ENABLED=0 GOFLAGS= go build -trimpath -ldflags '-s -w' -o "$destination" .
11新增:if [[ $os == darwin ]]; then codesign -f -s "${CAGE_SIGNING_IDENTITY:--}" "$destination"; fi
修改scripts/build-windows.ps1+42 −3看文件
@@ -2,6 +2,7 @@
22[CmdletBinding()]
33param(
44 [switch]$Release,
5新增: [switch]$Sign,
56 [switch]$SkipUI,
67 [string]$OutputDirectory,
78 [string]$DependencyCache
@@ -13,7 +14,8 @@ if (-not $DependencyCache) { $DependencyCache = Join-Path $repository '_output/w
1314$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
1415if (Test-Path -LiteralPath (Join-Path $OutputDirectory 'Uninstall.exe')) { throw 'Do not build over an installed application. Choose a separate output directory and use the installer to upgrade.' }
1516$version = Get-CageVersion $repository
16删除:if ($Release) { Assert-WindowsSigningConfiguration }
17新增:$signed = $Release -or $Sign
18新增:if ($signed) { Assert-WindowsSigningConfiguration }
1719$go = Get-BuildCommand @('go')
1820$dotnet = Get-BuildCommand @('dotnet')
1921$node = Get-BuildCommand @('node')
@@ -28,6 +30,8 @@ try {
2830 if (-not $SkipUI) {
2931 Invoke-BuildTool $npm @('--prefix', 'ui', 'ci', '--no-audit', '--no-fund')
3032 Invoke-BuildTool $npm @('run', '--prefix', 'ui', 'build')
33新增: } else {
34新增: Invoke-BuildTool $node @('ui/scripts/verify-build.mjs')
3135 }
3236 $limaVersion = (Get-Content 'internal/limaembed/lima-version' -Raw).Trim()
3337 $assets = Join-Path $repository 'internal/limaembed/assets'
@@ -47,10 +51,35 @@ try {
4751 $resources = Join-Path $app 'resources'
4852 New-Item -ItemType Directory -Path $resources -Force | Out-Null
4953 New-Item -ItemType Directory -Path (Join-Path $resources 'runtime') -Force | Out-Null
54新增: $guestSetup = New-Item -ItemType Directory -Path (Join-Path $resources 'guest-os')
55新增: Copy-Item -LiteralPath 'scripts/guest-os/new-windows-test-vm.ps1' -Destination (Join-Path $guestSetup.FullName 'new-windows-guest.ps1')
56新增: Copy-Item -LiteralPath 'scripts/guest-os/windows-host-image.ps1' -Destination $guestSetup.FullName
57新增: foreach ($file in @('windows-guest-media.ps1', 'install-guest-powershell.cmd', 'setup-windows-guest.ps1', 'complete-windows-guest.ps1', 'install-windows-host-manager.ps1', 'install-windows-workbench-components.ps1', 'initialize-windows-workbench-user.ps1', 'windows-host-enrollment.ps1', 'maintain-windows-workbench.ps1', 'update-windows-workbench-components.ps1', 'publish-windows-component-manifest.ps1', 'windows-workbench-packages.ps1')) {
58新增: Copy-Item -LiteralPath (Join-Path 'scripts/guest-os' $file) -Destination $guestSetup.FullName
59新增: }
60新增: $bridgeSetup = New-Item -ItemType Directory -Path (Join-Path $guestSetup.FullName 'guest-clipboard-windows')
61新增: foreach ($file in @('install.ps1', 'install-network.ps1')) {
62新增: Copy-Item -LiteralPath (Join-Path 'scripts/guest-os/guest-clipboard-windows' $file) -Destination $bridgeSetup.FullName
63新增: }
64新增: & (Join-Path $PSScriptRoot 'guest-os/build-windows-workbench-payload.ps1') -Destination (Join-Path $guestSetup.FullName 'payload')
65新增: $tailnetAssets = Join-Path $repository 'internal/tailnetassets/assets'
66新增: New-Item -ItemType Directory -Path $tailnetAssets -Force | Out-Null
67新增: foreach ($tailnetArch in @('amd64','arm64')) {
68新增: $env:GOOS = 'linux'; $env:GOARCH = $tailnetArch; $env:CGO_ENABLED = '0'
69新增: $tailnetOutput = Join-Path $stage ('cage-tailnet-linux-'+$tailnetArch)
70新增: Push-Location (Join-Path $repository 'tools/tailnet')
71新增: try { Invoke-BuildTool $go @('build','-trimpath','-ldflags','-s -w','-o',$tailnetOutput,'.') } finally { Pop-Location }
72新增: $source = [IO.File]::OpenRead($tailnetOutput)
73新增: $target = [IO.File]::Create((Join-Path $tailnetAssets ('cage-tailnet-linux-'+$tailnetArch+'.gz')))
74新增: try { $compressed = [IO.Compression.GZipStream]::new($target,[IO.Compression.CompressionMode]::Compress); try { $source.CopyTo($compressed) } finally { $compressed.Dispose() } } finally { $source.Dispose(); $target.Dispose() }
75新增: }
76新增: $env:GOARCH = 'amd64'
5077 $env:GOOS = 'windows'
5178 $tags = 'external_hcs,external_wsl2,yq_noxml,yq_nolua,yq_noini,yq_nohcl,yq_notoml,yq_noprops,yq_nocsv,yq_nouri,yq_nobase64,yq_nosh,yq_noshell'
5279 $ldflags = "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=$version -X github.com/lima-vm/lima/v2/pkg/version.Version=$limaVersion"
5380 Invoke-BuildTool $go @('build', '-trimpath', '-tags', $tags, '-ldflags', $ldflags, '-o', (Join-Path $resources 'cage.exe'), './cmd/cage')
81新增: Invoke-BuildTool (Join-Path $resources 'cage.exe') @('verify-vm-assets')
82新增: Invoke-BuildTool (Join-Path $resources 'cage.exe') @('verify-web-assets')
5483 Invoke-BuildTool $dotnet @('publish', 'desktop/windows/Cage.Windows.csproj', '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true',
5584 '-p:EnableWindowsTargeting=true', '-p:PublishSingleFile=true', '-p:RestoreLockedMode=true', "-p:Version=$version", "-p:InformationalVersion=$version", '-o', $app)
5685 Get-ChildItem -LiteralPath $app -File | Where-Object { $_.Extension -in @('.pdb', '.xml') } | Remove-Item -Force
@@ -74,13 +103,22 @@ try {
74103 $qemuArchive = Get-VerifiedDependency $dependencies.qemu $DependencyCache
75104 $qemuTarget = Join-Path $resources 'runtime/qemu'
76105 Expand-BuildArchive $qemuArchive $qemuTarget $sevenZip
106新增: $qemuBuilt = Join-Path $DependencyCache 'qemu-cage'
107新增: & (Join-Path $PSScriptRoot 'build-qemu-windows.ps1') -DependencyCache $DependencyCache -OutputDirectory $qemuBuilt
108新增: Copy-Item (Join-Path $qemuBuilt '*') $qemuTarget -Force
77109 # Ship the x64 VM only, with its original firmware, DLLs and notices.
78110 Get-ChildItem -LiteralPath $qemuTarget -Filter 'qemu-system-*.exe' | Where-Object { $_.Name -ne 'qemu-system-x86_64.exe' } | Remove-Item -Force
79111 Get-ChildItem -LiteralPath (Join-Path $qemuTarget 'share') -File |
80112 Where-Object { $_.Name -match '^edk2-(?:aarch64|arm|loongarch64|riscv)-.*\.fd$' } | Remove-Item -Force
81删除: foreach ($file in @('qemu-system-x86_64.exe', 'qemu-img.exe')) {
113新增: foreach ($file in @('qemu-system-x86_64.exe', 'qemu-img.exe', 'share/efi-virtio.rom', 'share/kvmvapic.bin')) {
82114 if (-not (Test-Path -LiteralPath (Join-Path $qemuTarget $file))) { throw "QEMU archive lacks $file" }
83115 }
116新增: $firmwareDirectories = & (Join-Path $qemuTarget 'qemu-system-x86_64.exe') '-L' 'help'
117新增: if ($LASTEXITCODE -ne 0) { throw 'Could not inspect QEMU firmware directories.' }
118新增: $bundledFirmware = [IO.Path]::GetFullPath((Join-Path $qemuTarget 'share')).TrimEnd('\', '/')
119新增: if (-not @($firmwareDirectories | Where-Object { [IO.Path]::GetFullPath($_).TrimEnd('\', '/') -eq $bundledFirmware }).Count) {
120新增: throw 'QEMU cannot locate its bundled firmware after relocation.'
121新增: }
84122 Remove-Item -LiteralPath (Join-Path $qemuTarget '$PLUGINSDIR') -Recurse -Force -ErrorAction SilentlyContinue
85123 Remove-Item -LiteralPath (Join-Path $qemuTarget 'qemu-uninstall.exe') -Force -ErrorAction SilentlyContinue
86124 $webviewArchive = Get-VerifiedDependency $dependencies.webview2 $DependencyCache
@@ -122,12 +160,13 @@ try {
122160 Copy-Item -LiteralPath 'LICENSE' -Destination (Join-Path $app 'LICENSE.txt')
123161 [IO.File]::WriteAllText((Join-Path $app 'Cage.install-id'), 'io.github.lee-xeo.claude-cage')
124162 [IO.File]::WriteAllText((Join-Path $app 'version.txt'), $version)
125删除: if ($Release) {
163新增: if ($signed) {
126164 $signTool = Get-SigningTool
127165 foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) { Sign-CageFile (Join-Path $app $file) $signTool }
128166 } else {
129167 [IO.File]::WriteAllText((Join-Path $app 'DEVELOPMENT-BUILD.txt'), "Unsigned development build. Automatic update installation is disabled. Windows 10/11 runtime acceptance is still required.`n")
130168 }
169新增: Assert-WindowsWorkbench $app
131170 $previousOutput = $null
132171 if (Test-Path -LiteralPath $OutputDirectory) {
133172 $marker = Join-Path $OutputDirectory 'Cage.install-id'
修改scripts/bundle-cloud-kit.mjs+5 −0看文件
@@ -24,6 +24,9 @@ if (offline) {
2424 try {
2525 const version = fs.readFileSync("VERSION", "utf8").trim();
2626 const binary = path.join(stage, "cage");
27新增: for (const arch of ["amd64", "arm64"]) {
28新增: if (!fs.existsSync(path.resolve("internal/tailnetassets/assets/cage-tailnet-linux-" + arch + ".gz"))) throw Error("Build Tailscale guest assets before packaging the cloud kit");
29新增: }
2730 execFileSync("go", ["build", "-trimpath", "-ldflags", "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=" + version, "-o", binary, "./cmd/cage"], {
2831 env: {...process.env, CGO_ENABLED:"0", GOOS:"linux", GOARCH:"amd64"}, stdio:"inherit"
2932 });
@@ -39,6 +42,8 @@ if (offline) {
3942 fs.mkdirSync(recipe, {recursive:true});
4043 for (const name of ["Dockerfile.guest","restore-apt-sources.sh","build-guest.sh"])
4144 fs.copyFileSync(path.join("deploy/cloud",name),path.join(recipe,name));
45新增: fs.mkdirSync(path.join(stage,"internal/cage"),{recursive:true});
46新增: fs.copyFileSync("internal/cage/apt-bootstrap.sh",path.join(stage,"internal/cage/apt-bootstrap.sh"));
4247 for (const name of ["cage-server.service","cage-container-engine.service"])
4348 fs.copyFileSync(path.join("deploy/cloud",name),path.join(stage,name));
4449 const runtime = JSON.parse(fs.readFileSync("deploy/cloud/runtime-artifacts.json"));
修改scripts/ci-windows-build.ps1+12 −1看文件
@@ -63,8 +63,18 @@ try {
6363 & (Join-Path $PSScriptRoot 'install-nsis.ps1') -Destination $env:RUNNER_TEMP
6464 $env:PATH = (Join-Path $env:RUNNER_TEMP 'nsis-3.13') + [IO.Path]::PathSeparator + $env:PATH
6565 Invoke-BuildTool 'node' @('scripts/check-version.mjs')
66删除: Invoke-BuildTool 'node' @('--test', 'internal/cage/browser-clipboard.test.mjs')
66新增: Invoke-BuildTool 'node' @('--test', 'internal/cage/browser-clipboard.test.mjs', 'scripts/windows-native-bridge.test.mjs')
67新增: $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
68新增: & (Join-Path $PSScriptRoot 'test-windows-installation-files.ps1') -HelperShell $windowsPowerShell
6769 & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release
70新增: if (-not $Release) {
71新增: $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
72新增: foreach ($test in @('install-guest-powershell.tests.ps1', 'windows-evaluation.tests.ps1')) {
73新增: Invoke-BuildTool $windowsPowerShell @('-NoProfile', '-NonInteractive', '-File', "scripts/guest-os/$test")
74新增: }
75新增: Invoke-BuildTool $windowsPowerShell @('-NoProfile', '-NonInteractive', '-File', 'scripts/guest-os/windows-powershell-media.smoke.ps1',
76新增: '-GuestToolsDirectory', "$repository/_output/windows-amd64/app/resources/guest-os")
77新增: }
6878 Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj')
6979 Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts')
7080 # Exercise a second volume when the runner keeps its workspace and temp on different drives.
@@ -75,6 +85,7 @@ try {
7585 Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Storage|Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)')
7686 Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)')
7787 Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/driver/qemu', '-run', 'Test(WindowsFirmwareArgument|WindowsPackagedFirmwareBeatsOldUserCopy|WHPXQEMU64Features|WindowsCPUResolution)$')
88新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/hostagent', '-run', '^TestResourceProbeCommand$')
7889 Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths')
7990 Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host')
8091 $packageArguments = @{ Release = $Release; SkipBuild = $true }
修改scripts/collect-app-licenses.mjs+23 −0看文件
@@ -1,5 +1,6 @@
11#!/usr/bin/env node
22import { cpSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
3新增:import { execFileSync } from "node:child_process";
34import { resolve, join } from "node:path";
45
56// Collect the licenses of the packages actually shipped in the workbench.
@@ -10,6 +11,7 @@ mkdirSync(target, { recursive: true });
1011for (const file of ["LICENSE", "NOTICE", "THIRD_PARTY_LICENSES"]) {
1112 cpSync(join(root, file), join(target, file));
1213}
14新增:cpSync(join(root, "internal/exitpolicy/data"), join(target, "exit-country-data"), { recursive: true });
1315const lock = JSON.parse(readFileSync(join(root, "ui/package-lock.json"), "utf8"));
1416const notices = [];
1517for (const [path, entry] of Object.entries(lock.packages)) {
@@ -31,3 +33,24 @@ for (const file of ["LICENSE.txt", "AUTHORS", "NOTICE.cage", "docs", "vendor/pak
3133}
3234// MPL-covered source and local modifications travel with the executable.
3335cpSync(join(root, "ui/.generated/novnc"), join(target, "novnc-source"), { recursive: true });
36新增:
37新增:// The embedded Tailscale node is a separate guest executable and module.
38新增:const tailnetModules = new Set();
39新增:for (const [os, arch] of [["linux", "amd64"], ["darwin", "arm64"], ["windows", "amd64"]]) {
40新增: const dirs = execFileSync("go", ["list", "-deps", "-f", "{{if .Module}}{{.Module.Dir}}{{end}}", "."], {
41新增: cwd: join(root, "tools/tailnet"), env: { ...process.env, GOOS: os, GOARCH: arch, CGO_ENABLED: "0", GOFLAGS: "" }, encoding: "utf8",
42新增: });
43新增: for (const dir of dirs.split("\n").filter(Boolean)) if (resolve(dir) !== join(root, "tools/tailnet")) tailnetModules.add(dir);
44新增:}
45新增:const tailnetNotices = [];
46新增:for (const dir of tailnetModules) {
47新增: const normalized = dir.replaceAll("\\", "/");
48新增: const name = normalized.slice(normalized.lastIndexOf("/pkg/mod/") + 9);
49新增: const dest = join(target, "tailnet-go", name);
50新增: const licenses = readdirSync(dir).filter(file => /^(licen[sc]e|copying|notice|patents|authors)(\.|$)/i.test(file) && statSync(join(dir, file)).isFile());
51新增: if (!licenses.length) throw Error(`Missing guest dependency license: ${name}`);
52新增: mkdirSync(dest, { recursive: true });
53新增: for (const file of licenses) cpSync(join(dir, file), join(dest, file));
54新增: tailnetNotices.push(name);
55新增:}
56新增:writeFileSync(join(target, "tailnet-go", "NOTICE.txt"), tailnetNotices.sort().join("\n") + "\n");
修改scripts/licenses+6 −0看文件
@@ -52,6 +52,7 @@ trap 'rm -f "$list"' EXIT
5252 modules windows arm64 0 ./cmd/agent-vm
5353 modules linux arm64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent
5454 modules linux amd64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent
55新增: modules darwin arm64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent
5556} | awk -F '\t' 'NF == 3 && !seen[$1]++' | LC_ALL=C sort > "$list"
5657
5758[ -s "$list" ] || { echo "licenses: go list found no module" >&2; exit 1; }
@@ -69,6 +70,11 @@ plus patches/ (see NOTICE).
6970Generated by scripts/licenses.
7071
7172EOF
73新增: printf '================================================================================\n'
74新增: printf 'gaoyifan/china-operator-ip: mainland exit address list (MIT)\n'
75新增: printf '================================================================================\n\n'
76新增: cat internal/exitpolicy/data/LICENSE
77新增: printf '\n'
7278 printf '================================================================================\n'
7379 printf 'Go standard library (BSD-3-Clause)\n'
7480 printf '================================================================================\n\n'
新增scripts/mobile-cli-supervisor-smoke.py+61 −0看文件
@@ -0,0 +1,61 @@
1新增:# Linux guest check. Each fixture creates only its own short-lived descendants.
2新增:import json
3新增:import os
4新增:from pathlib import Path
5新增:import signal
6新增:import subprocess
7新增:import sys
8新增:import tempfile
9新增:import time
10新增:
11新增:def until(condition, message, timeout=5):
12新增: deadline = time.monotonic() + timeout
13新增: while time.monotonic() < deadline:
14新增: if condition():
15新增: return
16新增: time.sleep(0.025)
17新增: raise AssertionError(message)
18新增:
19新增:def verify(supervisor, crash):
20新增: with tempfile.TemporaryDirectory(prefix="cage-supervisor-") as directory:
21新增: root = Path(directory)
22新增: child = (
23新增: "import os,time,pathlib;"
24新增: "pathlib.Path('tool.pid').write_text(str(os.getpid()));"
25新增: "time.sleep(1.8);pathlib.Path('late-write').write_text('unexpected')"
26新增: )
27新增: middle = (
28新增: "import sys,subprocess; "
29新增: f"p=subprocess.Popen([sys.executable,'-c',{child!r}],start_new_session=True);p.wait()"
30新增: )
31新增: cli = (
32新增: "import os,sys,subprocess,pathlib;sys.stdin.read();"
33新增: "pathlib.Path('cli.pid').write_text(str(os.getpid()));"
34新增: f"p=subprocess.Popen([sys.executable,'-c',{middle!r}],start_new_session=True);p.wait()"
35新增: )
36新增: proc = subprocess.Popen(
37新增: [sys.executable, "-I", supervisor, directory, sys.executable, "-c", cli],
38新增: stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
39新增: with proc:
40新增: proc.stdin.write(json.dumps("synthetic approved command").encode() + b"\n")
41新增: proc.stdin.flush()
42新增: until(lambda: (root / "tool.pid").is_file(), "tool did not start")
43新增: if crash:
44新增: os.kill(int((root / "cli.pid").read_text()), signal.SIGKILL)
45新增: else:
46新增: proc.stdin.close()
47新增: code = proc.wait(timeout=6)
48新增: if code == 0:
49新增: raise AssertionError("interrupted CLI reported success")
50新增: until(lambda: not Path("/proc", (root / "tool.pid").read_text()).exists(),
51新增: "detached tool survived supervision")
52新增: time.sleep(1.9)
53新增: if (root / "late-write").exists():
54新增: raise AssertionError("tool changed project after termination")
55新增:
56新增:if __name__ == "__main__":
57新增: if not sys.platform.startswith("linux"):
58新增: raise SystemExit("run inside an isolated Linux guest")
59新增: for crash in (False, True):
60新增: verify(str(Path(sys.argv[1]).resolve()), crash)
61新增: print("CLI crash: PASS" if crash else "SSH disconnect: PASS")
修改scripts/package-linux.sh+2 −2看文件
@@ -23,7 +23,7 @@ install -m 644 docs/linux.md "$stage/usr/share/doc/claude-cage/README.md"
2323install -m 755 packaging/linux/preinst "$stage/DEBIAN/preinst"
2424install -m 755 packaging/linux/preinst "$stage/DEBIAN/prerm"
2525# dpkg-shlibdeps derives glibc/GTK dependencies from the build distribution.
26删除:# Use Debian 12 for releases; a newer build must not claim an older ABI.
26新增:# Use Ubuntu 22.04 for releases; a newer build must not claim an older ABI.
2727mkdir -p "$stage/debian"
2828printf 'Source: claude-cage\nSection: devel\nPriority: optional\nMaintainer: Cage contributors <[email protected]>\n\nPackage: claude-cage\nArchitecture: amd64\nDescription: Cage desktop\n' > "$stage/debian/control"
2929dependencies=$(cd "$stage" && dpkg-shlibdeps -O usr/lib/claude-cage/cage-desktop | sed -n 's/^shlibs:Depends=//p')
@@ -36,7 +36,7 @@ Section: devel
3636Priority: optional
3737Architecture: amd64
3838Maintainer: Cage contributors <[email protected]>
39删除:Depends: $dependencies, libwebkit2gtk-4.1-0 (>= 2.40), libglib2.0-bin, ca-certificates
39新增:Depends: $dependencies, libwebkit2gtk-4.1-0 (>= 2.40), libglib2.0-bin, ca-certificates, systemd
4040Suggests: qemu-system-x86, qemu-utils, ovmf, openssh-client, iproute2, git
4141Recommends: dbus-user-session, fonts-noto-cjk, libnotify-bin, zenity | kdialog
4242Homepage: https://github.com/Lee-xeo/Claude-Cage
修改scripts/package-windows.ps1+36 −21看文件
@@ -2,6 +2,7 @@
22[CmdletBinding()]
33param(
44 [switch]$Release,
5新增: [switch]$Sign,
56 [switch]$SkipBuild,
67 [string]$AppDirectory,
78 [string]$OutputDirectory,
@@ -10,30 +11,34 @@ param(
1011. (Join-Path $PSScriptRoot 'windows-common.ps1')
1112$repository = Split-Path $PSScriptRoot -Parent
1213$version = Get-CageVersion $repository
14新增:$signed = $Release -or $Sign
1315if (-not $AppDirectory) { $AppDirectory = Join-Path $repository '_output/windows-amd64/app' }
1416if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository "_output/releases/$version/windows" }
1517$AppDirectory = [IO.Path]::GetFullPath($AppDirectory)
1618$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
17删除:if (-not $SkipBuild) { & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release -OutputDirectory $AppDirectory }
19新增:if (-not $SkipBuild) { & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release -Sign:$Sign -OutputDirectory $AppDirectory }
1820if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'Cage.install-id') -Raw) -ne 'io.github.lee-xeo.claude-cage') { throw 'Invalid Cage app directory.' }
1921if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'version.txt') -Raw).Trim() -ne $version) { throw 'App version differs from VERSION; rebuild before packaging.' }
2022$makeNSIS = Get-BuildCommand @('makensis.exe', 'makensis')
2123$sevenZip = Get-BuildCommand @('7z.exe', '7zz', '7z')
2224if ($IsWindows) {
2325 if ([Diagnostics.FileVersionInfo]::GetVersionInfo((Join-Path $AppDirectory 'Cage.exe')).ProductVersion -ne $version) { throw 'Cage.exe version differs from VERSION; rebuild before packaging.' }
26新增: Invoke-BuildTool (Join-Path $AppDirectory 'resources/cage.exe') @('verify-vm-assets')
27新增: Invoke-BuildTool (Join-Path $AppDirectory 'resources/cage.exe') @('verify-web-assets')
28新增: if ($SkipBuild) { Assert-WindowsWorkbench $AppDirectory }
2429} else {
2530 $metadata = & $sevenZip 'l' '-tPE' (Join-Path $AppDirectory 'Cage.exe')
2631 if ($LASTEXITCODE -ne 0 -or -not ($metadata -match ('^ProductVersion: ' + [regex]::Escape($version) + '$'))) { throw 'Cage.exe version differs from VERSION; rebuild before packaging.' }
2732}
2833$signTool = $null
29删除:if ($Release) {
34新增:if ($signed) {
3035 Assert-WindowsSigningConfiguration
3136 if ($env:CAGE_WINDOWS_CERT_SHA1 -notmatch '^[0-9A-Fa-f]{40}$') { throw 'Build and verify the signed app before packaging.' }
32删除: if (Test-Path -LiteralPath (Join-Path $AppDirectory 'DEVELOPMENT-BUILD.txt')) { throw 'Use build-windows.ps1 -Release before packaging a release.' }
33删除: if (-not $QemuSourceArchive -or -not (Test-Path -LiteralPath $QemuSourceArchive -PathType Leaf)) {
37新增: if (Test-Path -LiteralPath (Join-Path $AppDirectory 'DEVELOPMENT-BUILD.txt')) { throw 'Rebuild with build-windows.ps1 -Sign or -Release before packaging a signed installer.' }
38新增: if ($Release -and (-not $QemuSourceArchive -or -not (Test-Path -LiteralPath $QemuSourceArchive -PathType Leaf))) {
3439 throw 'Release packaging requires -QemuSourceArchive containing the corresponding patched QEMU and bundled library sources. A generic upstream QEMU tarball is not the source for the Weilnetz build.'
3540 }
36删除: Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $QemuSourceArchive)
41新增: if ($Release) { Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $QemuSourceArchive) }
3742 $signTool = Get-SigningTool
3843 foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) {
3944 $signature = Get-AuthenticodeSignature -LiteralPath (Join-Path $AppDirectory $file)
@@ -46,29 +51,30 @@ New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null
4651# Verify source material before the expensive installer compression.
4752$dependencies = Get-Content -LiteralPath (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json
4853$qemuTar = Get-VerifiedGitArchive $dependencies.qemuSource (Join-Path $repository '_output/windows-deps')
49删除:$suffix = if ($Release) { '' } else { '-unsigned' }
54新增:$suffix = if ($Release) { '' } elseif ($Sign) { '-test-signed' } else { '-unsigned' }
5055$artifact = Join-Path $OutputDirectory "Cage-$version-windows-amd64-setup$suffix.exe"
51删除:$manifest = Join-Path $OutputDirectory 'uninstall-files.nsh'
52删除:$files = @(Get-ChildItem -LiteralPath $AppDirectory -File -Recurse)
53删除:$lines = [Collections.Generic.List[string]]::new()
56新增:$manifest = Join-Path $AppDirectory 'Cage.install-files.json'
57新增:$files = @(Get-ChildItem -LiteralPath $AppDirectory -File -Recurse -Force | Where-Object FullName -ne $manifest)
58新增:$ownership = [Collections.Generic.List[object]]::new()
5459foreach ($file in $files) {
55删除: $relative = [IO.Path]::GetRelativePath($AppDirectory, $file.FullName).Replace('/', '\').Replace('$', '$$').Replace('"', '$\"')
56删除: $lines.Add('Delete "$INSTDIR\' + $relative + '"')
57删除:}
58删除:foreach ($directory in (Get-ChildItem -LiteralPath $AppDirectory -Directory -Recurse | Sort-Object { $_.FullName.Length } -Descending)) {
59删除: $relative = [IO.Path]::GetRelativePath($AppDirectory, $directory.FullName).Replace('/', '\').Replace('$', '$$').Replace('"', '$\"')
60删除: $lines.Add('RMDir "$INSTDIR\' + $relative + '"')
60新增: $relative = [IO.Path]::GetRelativePath($AppDirectory, $file.FullName).Replace('\', '/')
61新增: $ownership.Add(@{ path = $relative; sha256 = (Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant() })
6162}
62删除:[IO.File]::WriteAllLines($manifest, $lines)
63新增:@{ version = 1; files = @($ownership | Sort-Object path) } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $manifest -Encoding utf8
6364$numericVersion = ($version -split '-')[0] + '.0'
6465$prefix = if ($IsWindows) { '/' } else { '-' }
65删除:$arguments = @("${prefix}V3", "${prefix}DAPP_DIR=$AppDirectory", "${prefix}DVERSION=$version", "${prefix}DVERSION_NUMERIC=$numericVersion", "${prefix}DOUTPUT_FILE=$artifact", "${prefix}DUNINSTALL_MANIFEST=$manifest")
66删除:if ($Release) {
66新增:# Source files are UTF-8; Windows ACP must not reinterpret Chinese UI text.
67新增:$arguments = @("${prefix}V3", "${prefix}INPUTCHARSET", 'UTF8', "${prefix}DAPP_DIR=$AppDirectory", "${prefix}DVERSION=$version", "${prefix}DVERSION_NUMERIC=$numericVersion", "${prefix}DOUTPUT_FILE=$artifact", "${prefix}DFILE_MANIFEST=$manifest")
68新增:if ($signed) {
6769 $arguments += @("${prefix}DSIGN_PWSH=$((Get-Process -Id $PID).Path)", "${prefix}DSIGN_SCRIPT=$(Join-Path $PSScriptRoot 'sign-windows-file.ps1')")
6870}
6971$arguments += (Join-Path $repository 'packaging/windows/Cage.nsi')
7072Invoke-BuildTool $makeNSIS $arguments
71删除:if ($Release) { Sign-CageFile $artifact $signTool }
73新增:Invoke-BuildTool (Get-BuildCommand @('node.exe', 'node')) @(
74新增: (Join-Path $PSScriptRoot 'verify-windows-installer-icon.mjs'),
75新增: $artifact, (Join-Path $repository 'packaging/windows/Cage.ico'), $sevenZip
76新增:)
77新增:if ($signed) { Sign-CageFile $artifact $signTool }
7278if ((Get-Item -LiteralPath $artifact).Length -gt 512MB) { throw 'Installer exceeds the application updater 512 MiB limit.' }
7379
7480# Source materials travel beside the binary, not inside the application directory.
@@ -82,6 +88,16 @@ if (Test-Path -LiteralPath $qemuSource) { Remove-Item -LiteralPath $qemuSource }
8288Invoke-BuildTool $sevenZip @('a', '-tgzip', '-mx=9', '-bso0', '-bsp0', $qemuSource, $qemuTar)
8389Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $qemuSource)
8490$releaseFiles += $qemuSource
91新增:$qemuRuntime = Join-Path $AppDirectory 'resources/runtime/qemu'
92新增:if (Test-Path (Join-Path $qemuRuntime 'cage-build.json')) {
93新增: $keymapArchive = Get-VerifiedDependency $dependencies.qemuKeycodemap (Join-Path $repository '_output/windows-deps')
94新增: $keymapSource = Join-Path $OutputDirectory ('qemu-keycodemapdb-' + $dependencies.qemuKeycodemap.version + '-source.tar.gz')
95新增: Copy-Item $keymapArchive $keymapSource -Force
96新增: $changesSource = Join-Path $OutputDirectory ('qemu-' + $dependencies.qemu.version + '-cage-changes-source.tar.gz')
97新增: Invoke-BuildTool 'tar' @('-czf', $changesSource, '-C', $repository, 'patches/qemu', 'scripts/build-qemu-windows.ps1',
98新增: 'scripts/build-qemu-windows.sh', '-C', $qemuRuntime, 'cage-build.json', 'build-packages.txt')
99新增: $releaseFiles += @($keymapSource, $changesSource)
100新增:}
85101if ($Release) {
86102 $qemuSourceTarget = Join-Path $OutputDirectory ('qemu-' + $dependencies.qemu.version + '-windows-full-source' + [IO.Path]::GetExtension($QemuSourceArchive))
87103 Copy-Item -LiteralPath $QemuSourceArchive -Destination $qemuSourceTarget -Force
@@ -89,6 +105,5 @@ if ($Release) {
89105}
90106$sums = foreach ($file in $releaseFiles) { (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() + ' ' + [IO.Path]::GetFileName($file) }
91107[IO.File]::WriteAllLines((Join-Path $OutputDirectory 'SHA256SUMS'), $sums)
92删除:Remove-Item -LiteralPath $manifest
93108Write-Host "Windows installer: $artifact"
94删除:if (-not $Release) { Write-Warning 'Unsigned development installer. Do not publish it as an automatic update; Windows VM and installation acceptance are still required.' }
109新增:if (-not $signed) { Write-Warning 'Unsigned development installer. Do not publish it as an automatic update; Windows VM and installation acceptance are still required.' }
新增scripts/shared-clipboard-guest-smoke.py+145 −0看文件
@@ -0,0 +1,145 @@
1新增:"""Isolated real-X11 clipboard check; never connects to the user's VM.
2新增:
3新增:Run with CAGE_CLIPBOARD_QA_SSH_CONFIG and CAGE_CLIPBOARD_QA_SSH_TARGET.
4新增:The supplied guest must have disposable :77 and :78 displays and the helper.
5新增:"""
6新增:import base64
7新增:import json
8新增:import os
9新增:from pathlib import Path
10新增:import queue
11新增:import subprocess
12新增:import threading
13新增:import time
14新增:
15新增:ssh = ['ssh', '-F', os.environ['CAGE_CLIPBOARD_QA_SSH_CONFIG'], os.environ['CAGE_CLIPBOARD_QA_SSH_TARGET']]
16新增:directory = '/tmp/cage-clipboard-ui-qa'
17新增:helper = directory + '/shared-clipboard.py'
18新增:bridge = subprocess.Popen(ssh + ['sudo python3 ' + helper], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
19新增:events = queue.Queue()
20新增:threading.Thread(target=lambda: [events.put(json.loads(line)) for line in bridge.stdout], daemon=True).start()
21新增:owners = []
22新增:
23新增:
24新增:def remote(code, display=':78'):
25新增: return subprocess.check_output(ssh + ['env DISPLAY=' + display + ' NO_AT_BRIDGE=1 python3 -'], input=code, text=True, timeout=12)
26新增:
27新增:
28新增:def expect(predicate):
29新增: until = time.monotonic() + 8
30新增: observed = []
31新增: while time.monotonic() < until:
32新增: try:
33新增: value = events.get(timeout=.2)
34新增: except queue.Empty:
35新增: if bridge.poll() is not None:
36新增: raise RuntimeError('Clipboard bridge exited: ' + bridge.stderr.read())
37新增: continue
38新增: observed.append({key: (len(value[key]) if key == 'png' else value[key]) for key in value})
39新增: if predicate(value):
40新增: return value
41新增: raise AssertionError('Expected clipboard event not received: ' + json.dumps(observed))
42新增:
43新增:
44新增:def send(value, serial):
45新增: bridge.stdin.write(json.dumps({**value, 'serial': serial}) + '\n')
46新增: bridge.stdin.flush()
47新增: expect(lambda event: event.get('ack') == serial)
48新增:
49新增:
50新增:imports = '''import gi, base64, json, ctypes as C
51新增:gi.require_version('Gtk', '3.0')
52新增:from gi.repository import Gtk, Gdk, GdkPixbuf, GLib
53新增:Gtk.init([])
54新增:clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
55新增:'''
56新增:
57新增:
58新增:def owner(action, display=':78', user=None):
59新增: code = imports + action + "\nprint('ready',flush=True)\nGLib.timeout_add_seconds(30, lambda: (Gtk.main_quit(), False)[1])\nGtk.main()\n"
60新增: prefix = 'sudo -H -u ' + user + ' ' if user else ''
61新增: process = subprocess.Popen(ssh + [prefix + 'env DISPLAY=' + display + ' NO_AT_BRIDGE=1 python3 -'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
62新增: process.stdin.write(code); process.stdin.close()
63新增: assert process.stdout.readline().strip() == 'ready'
64新增: owners.append(process)
65新增: return process
66新增:
67新增:
68新增:try:
69新增: send({'text': 'host 中文🙂\nsecond line'}, 1)
70新增: print('host text acknowledged', flush=True)
71新增: for display in (':77', ':78'):
72新增: assert json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_text()))', display)) == 'host 中文🙂\nsecond line'
73新增: print('both displays read text', flush=True)
74新增:
75新增: # A real GTK button writes the system clipboard only after an X11 click.
76新增: owner("""window = Gtk.Window()
77新增:window.set_default_size(240,100)
78新增:window.move(40,40)
79新增:button = Gtk.Button(label='Copy message')
80新增:button.connect('clicked', lambda _button: clipboard.set_text('guest 消息🙂\\nexact text', -1))
81新增:window.add(button)
82新增:window.show_all()
83新增:""")
84新增: subprocess.check_call(ssh + ['env DISPLAY=:78 xdotool mousemove 160 90 click 1'])
85新增: expect(lambda event: event.get('text') == 'guest 消息🙂\nexact text')
86新增: print('native button copy received', flush=True)
87新增: assert json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_text()))', ':77')) == 'guest 消息🙂\nexact text'
88新增:
89新增: owner("image = GdkPixbuf.Pixbuf.new(GdkPixbuf.Colorspace.RGB, True, 8, 12, 9)\nimage.fill(0x2468acff)\nclipboard.set_image(image)", ':77')
90新增: image = expect(lambda event: 'png' in event)
91新增: print('native image copy received', flush=True)
92新增: assert base64.b64decode(image['png']).startswith(b'\x89PNG\r\n\x1a\n')
93新增: assert json.loads(remote(imports + "image=clipboard.wait_for_image(); print(json.dumps([image.get_width(),image.get_height()]))")) == [12, 9]
94新增: send({'png': image['png']}, 2)
95新增: assert json.loads(remote(imports + "image=clipboard.wait_for_image(); print(json.dumps([image.get_width(),image.get_height()]))", ':77')) == [12, 9]
96新增:
97新增: paths = [directory + '/中文.bin', directory + '/folder']
98新增: remote("from pathlib import Path\np=Path('/tmp/cage-clipboard-ui-qa'); (p/'中文.bin').write_bytes(bytes([0,255,128])); (p/'folder').mkdir(exist_ok=True); (p/'folder'/'blank').write_bytes(b'')")
99新增: send({'files': paths}, 3)
100新增: print('files acknowledged', flush=True)
101新增: for display in (':77', ':78'):
102新增: actual = json.loads(remote(imports + 'print(json.dumps(clipboard.wait_for_uris()))', display))
103新增: assert len(actual) == 2 and actual[0].endswith('%E4%B8%AD%E6%96%87.bin') and actual[1].endswith('/folder')
104新增:
105新增: file_owner = """
106新增:gtk = C.CDLL('libgtk-3.so.0'); gdk = C.CDLL('libgdk-3.so.0')
107新增:gdk.gdk_atom_intern_static_string.restype=C.c_void_p
108新增:gdk.gdk_atom_intern_static_string.argtypes=[C.c_char_p]
109新增:class Target(C.Structure):
110新增: _fields_=[('target',C.c_char_p),('flags',C.c_uint),('info',C.c_uint)]
111新增:Provide=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p,C.c_uint,C.c_void_p)
112新增:Clear=C.CFUNCTYPE(None,C.c_void_p,C.c_void_p)
113新增:gtk.gtk_selection_data_set.argtypes=[C.c_void_p,C.c_void_p,C.c_int,C.c_void_p,C.c_int]
114新增:gtk.gtk_clipboard_set_with_data.argtypes=[C.c_void_p,C.POINTER(Target),C.c_uint,Provide,Clear,C.c_void_p]
115新增:encoded=(uri+'\\r\\n').encode(); buffer=C.create_string_buffer(encoded)
116新增:@Provide
117新增:def provide(_clipboard,selection,_info,_data):
118新增: gtk.gtk_selection_data_set(selection,gdk.gdk_atom_intern_static_string(b'text/uri-list'),8,buffer,len(encoded))
119新增:@Clear
120新增:def clear(_clipboard,_data): pass
121新增:targets=(Target*1)(Target(b'text/uri-list',0,0))
122新增:assert gtk.gtk_clipboard_set_with_data(hash(clipboard),targets,1,provide,clear,None)
123新增:"""
124新增: owner("from pathlib import Path\np=Path.home()/'.cache/clipboard-private-qa'; p.mkdir(parents=True,exist_ok=True,mode=0o700); p.chmod(0o700); file=p/'private.bin'; file.write_bytes(bytes([0,255,128])); uri=file.as_uri()\n" + file_owner, ':77', 'cage-browser')
125新增: copied = expect(lambda event: 'files' in event)
126新增: assert copied['source'] == 'cage' and copied['files'][0].startswith('/tmp/cage-clipboard-')
127新增: actual = json.loads(remote(imports + 'from pathlib import Path\nfrom urllib.parse import urlsplit,unquote\nuris=clipboard.wait_for_uris(); print(json.dumps(list(Path(unquote(urlsplit(uris[0]).path)).read_bytes())))'))
128新增: assert actual == [0,255,128], 'private files must be materialized for the other application UID'
129新增: owner("uri='file:///etc/shadow'\n" + file_owner, ':77', 'cage-browser')
130新增: expect(lambda event: 'error' in event)
131新增:
132新增: # Ordinary drag-selection PRIMARY changes must not replace the clipboard.
133新增: owner("Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY).set_text('drag selection',-1)")
134新增: time.sleep(.3)
135新增: while not events.empty():
136新增: assert events.get().get('text') != 'drag selection'
137新增: print(json.dumps({'text_both_displays': True, 'native_copy_button': True, 'images_both_displays': True, 'files_and_folders_both_displays': True, 'private_file_cross_uid_copy': True, 'root_only_file_denied': True, 'primary_selection_ignored': True}))
138新增:finally:
139新增: bridge.stdin.close()
140新增: try:
141新增: bridge.wait(timeout=5)
142新增: except subprocess.TimeoutExpired:
143新增: bridge.terminate()
144新增: for process in owners:
145新增: process.terminate()
新增scripts/test-macos-install.mjs+103 −0看文件
@@ -0,0 +1,103 @@
1新增:// Exercise the manual macOS installation path in a disposable user directory.
2新增:import assert from "node:assert/strict";
3新增:import { execFileSync } from "node:child_process";
4新增:import { createHash, randomUUID } from "node:crypto";
5新增:import fs from "node:fs/promises";
6新增:import { createRequire } from "node:module";
7新增:import os from "node:os";
8新增:import path from "node:path";
9新增:import { seed, verify } from "./personal-data-fixture.mjs";
10新增:
11新增:const source = process.argv[2];
12新增:if (process.platform !== "darwin" || !source || !path.isAbsolute(source) || !source.endsWith(".app")) {
13新增: throw new Error("Usage on macOS: node scripts/test-macos-install.mjs /absolute/path/to/Cage.app");
14新增:}
15新增:const require = createRequire(import.meta.url);
16新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
17新增:const root = await fs.mkdtemp(path.join(os.tmpdir(), "cage-macos-install-"));
18新增:const qaHome = path.join(root, "user");
19新增:const manifest = path.join(root, "personal-data.json");
20新增:// The 12 preservation fixtures contain marker bytes. Use a separate valid profile for login.
21新增:const profile = path.join(root, "runtime-profile");
22新增:const env = { ...process.env, HOME: qaHome, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") };
23新增:const installed = path.join(qaHome, "Applications", "Cage.app");
24新增:const mount = path.join(root, "mount");
25新增:const image = path.join(root, "manual-install.dmg");
26新增:const stage = path.join(root, "volume");
27新增:const run = (exe, args, options = {}) => execFileSync(exe, args, { encoding: "utf8", timeout: 180000, ...options });
28新增:const cli = (...args) => run(path.join(installed, "Contents/Resources/cage"), args, { env });
29新增:const hash = async file => createHash("sha256").update(await fs.readFile(file)).digest("hex");
30新增:const password = randomUUID() + "7z";
31新增:let browser, mounted = false, running = false;
32新增:
33新增:try {
34新增: await seed(qaHome, manifest);
35新增: await fs.mkdir(path.dirname(installed), { recursive: true });
36新增: await fs.mkdir(stage);
37新增: await fs.mkdir(mount);
38新增: run("ditto", [source, path.join(stage, "Cage.app")]);
39新增: run("hdiutil", ["create", "-quiet", "-volname", "Cage-Isolated-QA", "-srcfolder", stage, "-format", "UDZO", image]);
40新增: run("hdiutil", ["attach", "-nobrowse", "-readonly", "-mountpoint", mount, image]);
41新增: mounted = true;
42新增: const result = {
43新增: dmg_sha256: await hash(image),
44新增: backend_sha256: await hash(path.join(source, "Contents/Resources/cage")),
45新增: launcher_sha256: await hash(path.join(source, "Contents/MacOS/Cage")),
46新增: };
47新增:
48新增: browser = await chromium.launch({ headless: true });
49新增: for (const phase of ["install", "reinstall"]) {
50新增: if (phase === "reinstall") await fs.rm(installed, { recursive: true });
51新增: run("ditto", [path.join(mount, "Cage.app"), installed]);
52新增: run("codesign", ["--verify", "--deep", "--strict", installed]);
53新增: assert.equal(await hash(path.join(installed, "Contents/Resources/cage")), result.backend_sha256);
54新增: cli("verify-web-assets");
55新增: if (process.arch === "arm64") cli("verify-macos-guest");
56新增: running = true;
57新增: const entry = JSON.parse(cli("desktop", "--json"));
58新增: assert.equal(entry.status, "ready");
59新增: const page = await browser.newPage();
60新增: try {
61新增: await page.goto(entry.url);
62新增: if (phase === "install") {
63新增: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click();
64新增: await page.getByRole("checkbox", { name: /^记住我/ }).uncheck();
65新增: await page.getByLabel("用户名", { exact: true }).fill("整包验收");
66新增: await page.getByLabel("设置密码", { exact: true }).fill(password);
67新增: await page.getByLabel("确认密码", { exact: true }).fill(password);
68新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click();
69新增: } else {
70新增: await page.getByLabel("账户密码", { exact: true }).fill(password);
71新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click();
72新增: }
73新增: await page.getByRole("button", { name: "设置", exact: true }).waitFor();
74新增: const account = await page.evaluate(async () => {
75新增: const context = await (await fetch("/api/client/context")).json();
76新增: return (await fetch("/api/account", { headers: { "X-Cage-Connection": context.connection_id } })).json();
77新增: });
78新增: assert.equal(account.username, "整包验收");
79新增: assert.equal(account.unlocked, true);
80新增: result[phase] = { original_account: true, preserved: await verify(qaHome, manifest) };
81新增: } finally {
82新增: await page.close();
83新增: }
84新增: cli("prepare-update", "--json");
85新增: running = false;
86新增: }
87新增: const accountHash = await hash(path.join(profile, "account.json"));
88新增: await fs.rm(installed, { recursive: true });
89新增: assert.equal(await hash(path.join(profile, "account.json")), accountHash);
90新增: result.uninstall = { account_preserved: true, preserved: await verify(qaHome, manifest) };
91新增: console.log(JSON.stringify(result, null, 2));
92新增:} finally {
93新增: try {
94新增: if (running) cli("prepare-update", "--json");
95新增: } finally {
96新增: try {
97新增: if (browser) await browser.close();
98新增: } finally {
99新增: if (mounted) run("hdiutil", ["detach", mount]);
100新增: await fs.rm(root, { recursive: true });
101新增: }
102新增: }
103新增:}
新增scripts/test-ubuntu-guest.sh+77 −0看文件
@@ -0,0 +1,77 @@
1新增:#!/usr/bin/env bash
2新增:set -euo pipefail
3新增:cd "$(dirname "$0")/.."
4新增:[[ $(id -u) != 0 ]] || { echo 'Run as an ordinary user in a disposable Ubuntu container.' >&2; exit 2; }
5新增:source internal/cage/tool-versions.env
6新增:source internal/cage/guest-tools.sh
7新增:source internal/cage/ubuntu-browser.sh
8新增:cage_is_ubuntu || { echo 'This test requires Ubuntu.' >&2; exit 2; }
9新增:sudo apt-get update
10新增:cage_install_ubuntu_browser
11新增:cage_install_ubuntu_novnc
12新增:test -r /usr/local/share/cage-novnc/core/rfb.js
13新增:sudo python3 internal/cage/novnc-patch.py /usr/local/share/cage-novnc
14新增:chromium --version
15新增:# Exercise the same pipe transport, sandbox and actual extension as the guest.
16新增:stage=$(mktemp -d)
17新增:trap 'rm -rf "$stage"' EXIT
18新增:CAGE_BROWSER_TEST_PROFILE="$stage/profile" CAGE_BROWSER_TEST_EXTENSION="$PWD/internal/cage/split-extension" CAGE_BROWSER_TEST_VERSION="$CAGE_UBUNTU_BROWSER_VERSION" \
19新增: xvfb-run -a node --input-type=module <<'JS'
20新增:import assert from 'node:assert/strict';
21新增:import { spawn } from 'node:child_process';
22新增:import { createHash } from 'node:crypto';
23新增:const extension = process.env.CAGE_BROWSER_TEST_EXTENSION;
24新增:const id = createHash('sha256').update(extension).digest('hex').slice(0, 32)
25新增: .replace(/./g, c => String.fromCharCode(97 + parseInt(c, 16)));
26新增:const browser = spawn('/usr/bin/chromium', [
27新增: `--user-data-dir=${process.env.CAGE_BROWSER_TEST_PROFILE}`, `--load-extension=${extension}`,
28新增: '--remote-debugging-pipe', '--no-first-run', '--no-default-browser-check', 'about:blank',
29新增:], { stdio: ['ignore', 'ignore', 'inherit', 'pipe', 'pipe'] });
30新增:let sequence = 0, buffer = Buffer.alloc(0), pageLoad;
31新增:const pending = new Map();
32新增:browser.stdio[4].on('data', chunk => {
33新增: buffer = Buffer.concat([buffer, chunk]);
34新增: let end;
35新增: while ((end = buffer.indexOf(0)) >= 0) {
36新增: const message = JSON.parse(buffer.subarray(0, end).toString());
37新增: buffer = buffer.subarray(end + 1);
38新增: if (pageLoad && message.sessionId === pageLoad.sessionId) {
39新增: if (message.method === 'Page.frameNavigated' && message.params.frame.url === pageLoad.url) pageLoad.navigated = true;
40新增: if (message.method === 'Page.loadEventFired' && pageLoad.navigated) pageLoad.resolve();
41新增: }
42新增: const job = pending.get(message.id);
43新增: if (job) { pending.delete(message.id); message.error ? job.reject(message.error) : job.resolve(message.result); }
44新增: }
45新增:});
46新增:function cdp(method, params = {}, sessionId) {
47新增: const id = ++sequence;
48新增: return new Promise((resolve, reject) => {
49新增: pending.set(id, { resolve, reject });
50新增: browser.stdio[3].write(JSON.stringify({ id, method, params, sessionId }) + '\0');
51新增: });
52新增:}
53新增:const timeout = setTimeout(() => { browser.kill('SIGKILL'); console.error('Browser pipe test timed out'); process.exitCode = 1; }, 30000);
54新增:try {
55新增: const version = await cdp('Browser.getVersion');
56新增: assert.ok(version.product.endsWith('/' + process.env.CAGE_BROWSER_TEST_VERSION));
57新增: const { targetId } = await cdp('Target.createTarget', { url: 'about:blank' });
58新增: const { sessionId } = await cdp('Target.attachToTarget', { targetId, flatten: true });
59新增: await cdp('Page.enable', {}, sessionId);
60新增: const url = `chrome-extension://${id}/control.html`;
61新增: const loaded = new Promise(resolve => { pageLoad = { sessionId, url, resolve, navigated: false }; });
62新增: const navigation = await cdp('Page.navigate', { url }, sessionId);
63新增: assert.equal(navigation.errorText, undefined);
64新增: await loaded;
65新增: const result = await cdp('Runtime.evaluate', {
66新增: expression: `({ protocol: location.protocol, extension: globalThis.chrome?.runtime?.id, title: document.title })`,
67新增: returnByValue: true,
68新增: }, sessionId);
69新增: assert.equal(result.result.value.protocol, 'chrome-extension:');
70新增: assert.equal(result.result.value.extension, id);
71新增: console.log(JSON.stringify({ browser: version.product, extension: true, cdpPipe: true, sandboxEnabled: true, noVNC: '1.6.0' }));
72新增: await cdp('Browser.close');
73新增:} finally {
74新增: clearTimeout(timeout);
75新增: browser.kill();
76新增:}
77新增:JS
新增scripts/update-exit-country-list.mjs+39 −0看文件
@@ -0,0 +1,39 @@
1新增:#!/usr/bin/env node
2新增:import { createHash } from "node:crypto";
3新增:import { mkdir, writeFile } from "node:fs/promises";
4新增:import { isIPv4 } from "node:net";
5新增:import { resolve } from "node:path";
6新增:
7新增:// Maintainer-only update: pin the reviewed upstream commit; applications never
8新增:// download executable policy or replace this bundled snapshot at runtime.
9新增:const commit = process.argv[2];
10新增:if (!/^[a-f0-9]{40}$/.test(commit || "")) {
11新增: throw new Error("Usage: node scripts/update-exit-country-list.mjs <upstream-commit-sha>");
12新增:}
13新增:const upstream = "gaoyifan/china-operator-ip";
14新增:const source = `https://raw.githubusercontent.com/${upstream}/${commit}`;
15新增:async function download(name) {
16新增: const response = await fetch(`${source}/${name}`, { signal: AbortSignal.timeout(30000) });
17新增: if (!response.ok) throw new Error(`${name}: HTTP ${response.status}`);
18新增: return response.text();
19新增:}
20新增:const [data, license] = await Promise.all([download("china.txt"), download("LICENSE")]);
21新增:const prefixes = data.trim().split(/\r?\n/);
22新增:if (prefixes.length < 1000 || prefixes.length > 50000) throw new Error("Unexpected mainland prefix count");
23新增:for (const prefix of prefixes) {
24新增: const [address, bits, extra] = prefix.split("/");
25新增: if (!isIPv4(address) || !/^[0-9]+$/.test(bits || "") || +bits < 8 || +bits > 32 || extra !== undefined) {
26新增: throw new Error(`Invalid IPv4 prefix: ${prefix}`);
27新增: }
28新增:}
29新增:if (!license.includes("MIT License") || !license.includes("Yifan Gao")) throw new Error("Review upstream license before updating");
30新增:const target = resolve(import.meta.dirname, "../internal/exitpolicy/data");
31新增:await mkdir(target, { recursive: true });
32新增:await writeFile(`${target}/mainland-ipv4.txt`, data);
33新增:await writeFile(`${target}/LICENSE`, license);
34新增:await writeFile(`${target}/source.json`, JSON.stringify({
35新增: upstream: `https://github.com/${upstream}`, commit,
36新增: url: `${source}/china.txt`, sha256: createHash("sha256").update(data).digest("hex"),
37新增: ipv4_prefixes: prefixes.length, license: "MIT",
38新增:}, null, 2) + "\n");
39新增:console.log(`Updated ${prefixes.length} mainland IPv4 prefixes from ${commit}`);
新增scripts/verify-windows-installer-icon.mjs+56 −0看文件
@@ -0,0 +1,56 @@
1新增:import { createHash } from "node:crypto";
2新增:import { execFileSync } from "node:child_process";
3新增:import { readFileSync } from "node:fs";
4新增:
5新增:const [executable, icon, sevenZip] = process.argv.slice(2);
6新增:if (!executable || !icon || !sevenZip) {
7新增: throw new Error("Usage: verify-windows-installer-icon.mjs INSTALLER.exe ICON.ico SEVEN_ZIP");
8新增:}
9新增:
10新增:function frames(bytes) {
11新增: if (bytes.length < 6 || bytes.readUInt16LE(0) !== 0 || bytes.readUInt16LE(2) !== 1) {
12新增: throw new Error("Invalid Windows icon file.");
13新增: }
14新增: const count = bytes.readUInt16LE(4);
15新增: if (!count || bytes.length < 6 + count * 16) throw new Error("Missing Windows icon images.");
16新增: const result = new Map();
17新增: for (let index = 0; index < count; index++) {
18新增: const entry = 6 + index * 16;
19新增: const size = bytes.readUInt32LE(entry + 8);
20新增: const offset = bytes.readUInt32LE(entry + 12);
21新增: const key = `${bytes[entry] || 256}x${bytes[entry + 1] || 256}`;
22新增: if (offset + size > bytes.length) throw new Error("Truncated Windows icon image.");
23新增: result.set(key, createHash("sha256").update(bytes.subarray(offset, offset + size)).digest("hex"));
24新增: }
25新增: return result;
26新增:}
27新增:
28新增:function resource(...names) {
29新增: return execFileSync(sevenZip, ["e", "-tPE", "-so", executable, ...names], {
30新增: maxBuffer: 2 * 1024 * 1024,
31新增: stdio: ["ignore", "pipe", "pipe"],
32新增: });
33新增:}
34新增:
35新增:const expected = frames(readFileSync(icon));
36新增:// NSIS uses icon group 103 for the executable's primary shell icon.
37新增:const group = resource(".rsrc/GROUP_ICON/103");
38新增:if (group.length !== 6 + expected.size * 14 || group.readUInt32LE(0) !== 0x00010000 || group.readUInt16LE(4) !== expected.size) {
39新增: throw new Error("Installer icon sizes differ from the Cage icon.");
40新增:}
41新增:const seen = new Set();
42新增:for (let index = 0; index < expected.size; index++) {
43新增: const entry = 6 + index * 14;
44新增: const key = `${group[entry] || 256}x${group[entry + 1] || 256}`;
45新增: const id = group.readUInt16LE(entry + 12);
46新增: // 7-Zip returns PNG frames directly and wraps bitmap frames in an ICO header.
47新增: const bytes = resource(`.rsrc/ICON/${id}`, `.rsrc/ICON/${id}.ico`);
48新增: const actual = bytes.length >= 6 && bytes.readUInt32LE(0) === 0x00010000
49新增: ? frames(bytes).get(key)
50新增: : createHash("sha256").update(bytes).digest("hex");
51新增: if (seen.has(key) || !expected.has(key) || actual !== expected.get(key)) {
52新增: throw new Error(`Installer icon ${key} differs from the Cage logo.`);
53新增: }
54新增: seen.add(key);
55新增:}
56新增:console.log(`Verified ${expected.size} Cage installer icon sizes.`);
修改scripts/windows-common.ps1+29 −0看文件
@@ -9,6 +9,35 @@ function Invoke-BuildTool {
99 if ($LASTEXITCODE -ne 0) { throw "$Tool failed with exit code $LASTEXITCODE" }
1010}
1111
12新增:function Assert-WindowsWorkbench {
13新增: param([Parameter(Mandatory)][string]$AppDirectory)
14新增: if (-not $IsWindows) { throw 'Workbench acceptance requires Windows.' }
15新增: $testRoot = Join-Path ([IO.Path]::GetTempPath()) ('cage-build-ui-' + [guid]::NewGuid().ToString('N'))
16新增: New-Item -ItemType Directory -Path $testRoot -Force | Out-Null
17新增: $report = Join-Path $testRoot 'smoke.json'
18新增: $start = [Diagnostics.ProcessStartInfo]::new((Join-Path $AppDirectory 'Cage.exe'))
19新增: $start.UseShellExecute = $false
20新增: $start.WorkingDirectory = $AppDirectory
21新增: $start.Environment['CLAUDE_CAGE_CONFIG'] = Join-Path $testRoot 'profile/config.json'
22新增: $start.ArgumentList.Add('--smoke-test')
23新增: $start.ArgumentList.Add($report)
24新增: $window = [Diagnostics.Process]::Start($start)
25新增: $passed = $false
26新增: try {
27新增: if (-not $window.WaitForExit(180000)) { throw "Cage workbench acceptance timed out. Diagnostics retained at $testRoot" }
28新增: if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage workbench acceptance failed. Diagnostics retained at $testRoot" }
29新增: $result = Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
30新增: if ($result.success -ne $true -or $result.nativeBridgeReady -ne $true) { throw "Cage workbench/bridge acceptance failed. Diagnostics retained at $testRoot" }
31新增: $passed = $true
32新增: } finally {
33新增: if (-not $window.HasExited) { $window.Kill($true); $window.WaitForExit() }
34新增: $window.Dispose()
35新增: # A successful smoke report is written only after the isolated backend
36新增: # confirms shutdown. Failed profiles remain available for diagnosis.
37新增: if ($passed) { Remove-Item -LiteralPath $testRoot -Recurse -Force -ErrorAction SilentlyContinue }
38新增: }
39新增:}
40新增:
1241function Get-CageVersion {
1342 param([string]$Repository)
1443 $value = (Get-Content -LiteralPath (Join-Path $Repository 'VERSION') -Raw).Trim()
新增third_party/gvisor-tap-vsock/pkg/tap/ipv6_drop_test.go+22 −0看文件
@@ -0,0 +1,22 @@
1新增:package tap
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "testing"
7新增:)
8新增:
9新增:// The observer must run on data read from the guest, before forwarding the
10新增:// frame to any other peer or to the IPv4 stack.
11新增:func TestIPv6DropAtGuestIngress(t *testing.T) {
12新增: s := NewSwitch(false)
13新增: payload := []byte{0x60, 0, 0, 0, 0, 0, 17, 1}
14新增: ethernet := make([]byte, 14)
15新增: ethernet[12], ethernet[13] = 0x86, 0xdd
16新增: var seen []byte
17新增: s.SetDroppedIPv6(func(packet []byte) { seen = append(seen, packet...) })
18新增: s.rxBuf(context.Background(), 1, append(ethernet, payload...))
19新增: if !bytes.Equal(seen, payload) || s.Sent != 0 || s.Received != uint64(len(ethernet)+len(payload)) {
20新增: t.Fatal("IPv6 frame was not observed and dropped at ingress")
21新增: }
22新增:}
修改third_party/gvisor-tap-vsock/pkg/tap/switch.go+13 −0看文件
@@ -33,6 +33,8 @@ type NetworkSwitch interface {
3333}
3434
3535type Switch struct {
36新增: droppedIPv6 func([]byte)
37新增:
3638 Sent uint64
3739 Received uint64
3840
@@ -60,6 +62,9 @@ func NewSwitch(debug bool) *Switch {
6062 }
6163}
6264
65新增:// SetDroppedIPv6 is configured before Accept, only for an IPv4-only stack.
66新增:func (e *Switch) SetDroppedIPv6(observe func([]byte)) { e.droppedIPv6 = observe }
67新增:
6368func (e *Switch) CAM() map[string]int {
6469 e.camLock.RLock()
6570 defer e.camLock.RUnlock()
@@ -275,7 +280,15 @@ func (e *Switch) rxBuf(_ context.Context, id int, buf []byte) {
275280 log.Info(packet.String())
276281 }
277282
283新增: if len(buf) < header.EthernetMinimumSize {
284新增: return
285新增: }
278286 eth := header.Ethernet(buf)
287新增: if e.droppedIPv6 != nil && eth.Type() == header.IPv6ProtocolNumber {
288新增: e.droppedIPv6(buf[header.EthernetMinimumSize:])
289新增: atomic.AddUint64(&e.Received, uint64(len(buf)))
290新增: return
291新增: }
279292
280293 e.camLock.Lock()
281294 _, exists := e.cam[eth.SourceAddress()]
修改third_party/gvisor-tap-vsock/pkg/types/configuration.go+4 −0看文件
@@ -20,6 +20,10 @@ func (o Outbound) Allows(network string, dst netip.AddrPort) bool {
2020type DialContext func(context.Context, string, string) (net.Conn, error)
2121
2222type Configuration struct {
23新增: // DroppedIPv6 observes guest IPv6 payloads discarded at ingress by an
24新增: // IPv4-only stack. It does not receive frames when IPv6 is supported.
25新增: DroppedIPv6 func([]byte) `yaml:"-" json:"-"`
26新增:
2327 DialContext DialContext `yaml:"-"`
2428 DNSExchange func(context.Context, *dns.Msg) (*dns.Msg, error) `yaml:"-"`
2529 // Print packets on stderr
修改third_party/gvisor-tap-vsock/pkg/virtualnetwork/virtualnetwork.go+4 −0看文件
@@ -12,6 +12,7 @@ import (
1212 "github.com/containers/gvisor-tap-vsock/pkg/tap"
1313 "github.com/containers/gvisor-tap-vsock/pkg/types"
1414 "gvisor.dev/gvisor/pkg/tcpip"
15新增: "gvisor.dev/gvisor/pkg/tcpip/header"
1516 "gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
1617 "gvisor.dev/gvisor/pkg/tcpip/network/arp"
1718 "gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
@@ -78,6 +79,9 @@ func New(configuration *types.Configuration) (*VirtualNetwork, error) {
7879 return nil, fmt.Errorf("cannot create network stack: %w", err)
7980 }
8081
82新增: if configuration.DroppedIPv6 != nil && stack.NetworkProtocolInstance(header.IPv6ProtocolNumber) == nil {
83新增: networkSwitch.SetDroppedIPv6(configuration.DroppedIPv6)
84新增: }
8185 mux, err := addServices(configuration, stack, ipPool)
8286 if err != nil {
8387 return nil, fmt.Errorf("cannot add network services: %w", err)