提交记录修改.github/workflows/linux-build.yml+40 −3看文件
修改.github/workflows/windows-build.yml+34 −2看文件
修改.gitignore+2 −0看文件
修改Makefile+17 −2看文件
修改THIRD_PARTY_LICENSES+91 −0看文件
修改deploy/cloud/Dockerfile.guest+2 −0看文件
修改deploy/cloud/README.md+2 −0看文件
修改deploy/cloud/build-guest.sh+3 −1看文件
修改desktop/Cage.swift+174 −5看文件
新增desktop/MacGuestLogin.swift+51 −0看文件
新增desktop/MacKeyboard.swift+54 −0看文件
修改desktop/NativeInput.swift+5 −16看文件
修改desktop/NativeInputTests.swift+31 −2看文件
修改desktop/linux/cage-desktop.c+260 −11看文件
修改desktop/windows/MainWindow.cs+116 −28看文件
修改desktop/windows/NativeInput.cs+40 −3看文件
新增desktop/windows/SharedClipboard.cs+175 −0看文件
新增desktop/windows/TrayMenu.cs+35 −0看文件
修改desktop/windows/WindowChrome.cs+29 −3看文件
新增desktop/windows/WindowLayout.cs+35 −0看文件
修改packaging/windows/dependencies.json+7 −0看文件
新增patches/gvisor-tap-vsock/0005-ipv6-guest-link-drop.patch+95 −0看文件
新增patches/qemu/0001-windows-balloon-discard.patch+322 −0看文件
修改scripts/build-app.sh+43 −18看文件
修改scripts/build-client-windows.ps1+5 −0看文件
修改scripts/build-client.sh+4 −1看文件
修改scripts/build-linux.sh+2 −1看文件
新增scripts/build-qemu-windows.ps1+65 −0看文件
新增scripts/build-qemu-windows.sh+37 −0看文件
新增scripts/build-tailnet.sh+11 −0看文件
修改scripts/build-windows.ps1+42 −3看文件
修改scripts/bundle-cloud-kit.mjs+5 −0看文件
修改scripts/ci-windows-build.ps1+12 −1看文件
修改scripts/collect-app-licenses.mjs+23 −0看文件
修改scripts/licenses+6 −0看文件
新增scripts/mobile-cli-supervisor-smoke.py+61 −0看文件
修改scripts/package-linux.sh+2 −2看文件
修改scripts/package-windows.ps1+36 −21看文件
新增scripts/shared-clipboard-guest-smoke.py+145 −0看文件
新增scripts/test-macos-install.mjs+103 −0看文件
新增scripts/test-ubuntu-guest.sh+77 −0看文件
新增scripts/update-exit-country-list.mjs+39 −0看文件
新增scripts/verify-windows-installer-icon.mjs+56 −0看文件
修改scripts/windows-common.ps1+29 −0看文件
新增third_party/gvisor-tap-vsock/pkg/tap/ipv6_drop_test.go+22 −0看文件
修改third_party/gvisor-tap-vsock/pkg/tap/switch.go+13 −0看文件
修改third_party/gvisor-tap-vsock/pkg/types/configuration.go+4 −0看文件
修改third_party/gvisor-tap-vsock/pkg/virtualnetwork/virtualnetwork.go+4 −0看文件
| @@ -18,7 +18,7 @@ permissions: | ||
| 18 | 18 | contents: read |
| 19 | 19 | jobs: |
| 20 | 20 | 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. | |
| 22 | 22 | # Ubuntu 24.04's host policy restricts them even in an unconfined container. |
| 23 | 23 | runs-on: ubuntu-22.04 |
| 24 | 24 | timeout-minutes: 60 |
| @@ -26,7 +26,7 @@ jobs: | ||
| 26 | 26 | run: |
| 27 | 27 | shell: bash |
| 28 | 28 | container: |
| 29 | 删除: image: debian:12 | |
| 29 | 新增: image: ubuntu:22.04 | |
| 30 | 30 | # docker-default AppArmor denies bubblewrap's private mount namespace. |
| 31 | 31 | # Relax only this disposable outer container; WebKit keeps its sandbox. |
| 32 | 32 | options: --security-opt seccomp=unconfined --security-opt systempaths=unconfined --security-opt apparmor=unconfined |
| @@ -34,8 +34,9 @@ jobs: | ||
| 34 | 34 | - name: Install build and test dependencies |
| 35 | 35 | run: | |
| 36 | 36 | 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 | |
| 38 | 38 | useradd -m -s /bin/bash cage |
| 39 | 新增: echo "cage ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/cage | |
| 39 | 40 | - uses: actions/checkout@v4 |
| 40 | 41 | with: |
| 41 | 42 | ref: ${{ inputs.ref }} |
| @@ -77,6 +78,8 @@ jobs: | ||
| 77 | 78 | runuser -u cage -- go test ./internal/... ./cmd/... |
| 78 | 79 | runuser -u cage -- go vet ./internal/managedproxy ./internal/workbench ./cmd/cage |
| 79 | 80 | 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 | |
| 80 | 83 | - name: Install, render native workbench, reinstall and remove |
| 81 | 84 | run: | |
| 82 | 85 | runuser -u cage -- bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev -- true |
| @@ -114,3 +117,37 @@ jobs: | ||
| 114 | 117 | overwrite: true |
| 115 | 118 | retention-days: 14 |
| 116 | 119 | # 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" | |
| @@ -45,13 +45,29 @@ jobs: | ||
| 45 | 45 | with: |
| 46 | 46 | dotnet-version: 10.0.403 |
| 47 | 47 | - 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 | |
| 48 | 63 | - uses: actions/cache@v4 |
| 49 | 64 | with: |
| 50 | 65 | 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.*') }} | |
| 52 | 67 | - name: Build, test and install the unsigned development package |
| 53 | 68 | env: |
| 54 | 69 | CAGE_BUILD_REF: ${{ inputs.ref }} |
| 70 | 新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }} | |
| 55 | 71 | run: ./scripts/ci-windows-build.ps1 |
| 56 | 72 | - uses: actions/upload-artifact@v4 |
| 57 | 73 | with: |
| @@ -94,10 +110,25 @@ jobs: | ||
| 94 | 110 | with: |
| 95 | 111 | dotnet-version: 10.0.403 |
| 96 | 112 | - 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 | |
| 97 | 128 | - uses: actions/cache@v4 |
| 98 | 129 | with: |
| 99 | 130 | 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.*') }} | |
| 101 | 132 | - uses: actions/setup-java@v4 |
| 102 | 133 | with: |
| 103 | 134 | distribution: temurin |
| @@ -105,6 +136,7 @@ jobs: | ||
| 105 | 136 | - name: Build, sign, test and install the release candidate |
| 106 | 137 | env: |
| 107 | 138 | CAGE_BUILD_REF: ${{ inputs.ref }} |
| 139 | 新增: CAGE_MSYS2_ROOT: ${{ steps.msys2.outputs.msys2-location }} | |
| 108 | 140 | CAGE_WINDOWS_SIGNING_PROVIDER: ${{ vars.CAGE_WINDOWS_SIGNING_PROVIDER }} |
| 109 | 141 | CAGE_ESIGNER_USERNAME: ${{ secrets.CAGE_ESIGNER_USERNAME }} |
| 110 | 142 | CAGE_ESIGNER_PASSWORD: ${{ secrets.CAGE_ESIGNER_PASSWORD }} |
| @@ -34,3 +34,5 @@ dist | ||
| 34 | 34 | # Rendered promo export; reproducible source and assets are in promo/. |
| 35 | 35 | /claude-cage-promo.mp4 |
| 36 | 36 | /.vite/ |
| 37 | 新增: | |
| 38 | 新增:/internal/tailnetassets/assets/*.gz | |
| @@ -49,7 +49,7 @@ GO_BUILD := CGO_ENABLED=$(CGO_ENABLED) $(GO) build -trimpath -tags $(TAGS) -ldfl | ||
| 49 | 49 | all: agent-vm |
| 50 | 50 | |
| 51 | 51 | # Claude Cage ships a separate entry point with a mandatory proxy profile. |
| 52 | 删除:cage: cage-ui assets | |
| 52 | 新增:cage: cage-ui assets tailnet-assets | |
| 53 | 53 | $(GO_BUILD) -o _output/bin/cage$(EXE) ./cmd/cage |
| 54 | 54 | ifeq ($(GOOS),darwin) |
| 55 | 55 | codesign -f --entitlements third_party/lima/vz.entitlements -s - _output/bin/cage |
| @@ -96,18 +96,26 @@ ifeq ($(GOOS),darwin) | ||
| 96 | 96 | codesign -f -v --entitlements third_party/lima/vz.entitlements -s - _output/bin/limactl |
| 97 | 97 | endif |
| 98 | 98 | |
| 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. | |
| 100 | 100 | assets: |
| 101 | 101 | CGO_ENABLED=0 GOOS=linux GOARCH=$(GOARCH) $(GO) build -trimpath \ |
| 102 | 102 | -ldflags "-s -w -X github.com/lima-vm/lima/v2/pkg/version.Version=$(LIMA_VERSION)" \ |
| 103 | 103 | -o $(ASSETS)/lima-guestagent.Linux-$(GUEST_ARCH) github.com/lima-vm/lima/v2/cmd/lima-guestagent |
| 104 | 104 | 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 | |
| 105 | 112 | rm -rf $(ASSETS)/templates && cp -R third_party/lima/templates $(ASSETS)/templates |
| 106 | 113 | |
| 107 | 114 | test: test-go |
| 108 | 115 | |
| 109 | 116 | test-go: |
| 110 | 117 | $(GO) test -tags $(TAGS) . ./cmd/... ./internal/... |
| 118 | 新增: cd tools/tailnet && GOFLAGS= $(GO) test ./... | |
| 111 | 119 | |
| 112 | 120 | # The Windows build and its tests compile and vet, from any OS. The Windows |
| 113 | 121 | # paths' logic is tested everywhere (paths.Windows); the tests themselves |
| @@ -144,3 +152,10 @@ fuzz: | ||
| 144 | 152 | clean: |
| 145 | 153 | rm -rf _output |
| 146 | 154 | 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 | |
| @@ -8,6 +8,32 @@ plus patches/ (see NOTICE). | ||
| 8 | 8 | |
| 9 | 9 | Generated by scripts/licenses. |
| 10 | 10 | |
| 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 | 新增: | |
| 11 | 37 | ================================================================================ |
| 12 | 38 | Go standard library (BSD-3-Clause) |
| 13 | 39 | ================================================================================ |
| @@ -3541,6 +3567,38 @@ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
| 3541 | 3567 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 3542 | 3568 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 3543 | 3569 | |
| 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 | 新增: | |
| 3544 | 3602 | ================================================================================ |
| 3545 | 3603 | github.com/google/yamlfmt v0.21.0: LICENSE |
| 3546 | 3604 | ================================================================================ |
| @@ -6081,6 +6139,30 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 6081 | 6139 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 6082 | 6140 | THE SOFTWARE. |
| 6083 | 6141 | |
| 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 | 新增: | |
| 6084 | 6166 | ================================================================================ |
| 6085 | 6167 | github.com/spakin/netpbm v1.3.2: LICENSE.md |
| 6086 | 6168 | ================================================================================ |
| @@ -8172,3 +8254,12 @@ Some files carry the following license, noted at the top of each file: | ||
| 8172 | 8254 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 8173 | 8255 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 8174 | 8256 | 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. | |
| @@ -4,11 +4,13 @@ ARG BASE_IMAGE=debian:13-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b | ||
| 4 | 4 | FROM ${BASE_IMAGE} |
| 5 | 5 | |
| 6 | 6 | ENV container=docker |
| 7 | 新增:COPY apt-bootstrap.sh /usr/local/lib/cage-apt-bootstrap | |
| 7 | 8 | COPY restore-apt-sources.sh /usr/local/lib/cage-image-restore-sources |
| 8 | 9 | ARG DEBIAN_MIRROR=http://deb.debian.org |
| 9 | 10 | RUN sed -i "s#http://deb.debian.org#${DEBIAN_MIRROR}#g" /etc/apt/sources.list.d/debian.sources \ |
| 10 | 11 | && printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d \ |
| 11 | 12 | && chmod 0755 /usr/sbin/policy-rc.d \ |
| 13 | 新增: && sh /usr/local/lib/cage-apt-bootstrap \ | |
| 12 | 14 | && apt-get update \ |
| 13 | 15 | && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ |
| 14 | 16 | systemd systemd-sysv dbus dbus-user-session libpam-systemd sudo \ |
| @@ -69,6 +69,8 @@ cage_engine="$HOME/.claude-cage/container-engine/tools/docker" | ||
| 69 | 69 | |
| 70 | 70 | 通过 `Dockerfile.guest` 构建基础层,再创建独立的镜像构建容器。构建容器不挂载项目、个人主目录、代理配置或账户;安装下载使用单独的构建网络。默认 Debian 镜像已经固定 digest,APT 继续验证发行版签名。若部署网络需要镜像站,只调整构建阶段的 Debian 软件源,保留签名验证;基础层和完整镜像提交前均恢复 `deb.debian.org` 官方源,以符合运行环境的维护下载来源限制。 |
| 71 | 71 | |
| 72 | 新增:基础层在批量安装前使用共同的 `internal/cage/apt-bootstrap.sh` 检查 APT;Debian 13 低于 3.0.4 时先通过官方安全源升级,升级下载禁用重试。`build-guest.sh` 将该脚本与 Dockerfile 复制到本次构建的临时上下文,部署工具包包含同一份脚本。升级失败会保留构建证据并停止后续安装。 | |
| 73 | 新增: | |
| 72 | 74 | 使用[完整镜像构建脚本](build-guest.sh)建立本次构建独占的父 slice、网络和容器。脚本检查实际 rootless 引擎和父层上限,再执行共同安装脚本;命名带唯一后缀,避免覆盖已有环境。 |
| 73 | 75 | |
| 74 | 76 | ```sh |
| @@ -82,8 +82,10 @@ read -r cage_cpu_quota cage_cpu_period < "/sys/fs/cgroup$cage_parent/cpu.max" | ||
| 82 | 82 | echo 'The build parent CPU limit was not applied.' >&2; exit 1; |
| 83 | 83 | } |
| 84 | 84 | cage_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/" | |
| 85 | 87 | DOCKER_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 | |
| 87 | 89 | cage_container_id=$(engine create --name "$cage_builder" --label "cn.cage.image-build=$cage_build_id" \ |
| 88 | 90 | --hostname cage --add-host cage:127.0.1.1 \ |
| 89 | 91 | --network "$cage_network" --cgroupns private --cgroup-parent "$cage_slice" --ipc private \ |
| @@ -23,6 +23,13 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 23 | 23 | private var allowQuit = false |
| 24 | 24 | private var nativeFilePanelOpen = false |
| 25 | 25 | 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? | |
| 26 | 33 | private var loading: NSTextField! |
| 27 | 34 | private var retry: NSButton! |
| 28 | 35 | private var backdrop: NSVisualEffectView! |
| @@ -40,6 +47,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 40 | 47 | |
| 41 | 48 | static func main() { |
| 42 | 49 | 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 | 新增: } | |
| 43 | 54 | NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") } |
| 44 | 55 | let app = NSApplication.shared |
| 45 | 56 | let delegate = CageApp() |
| @@ -53,7 +64,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 53 | 64 | NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua) |
| 54 | 65 | makeMenus() |
| 55 | 66 | 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" | |
| 57 | 68 | window.titlebarAppearsTransparent = false |
| 58 | 69 | window.backgroundColor = NSColor(srgbRed: 247.0/255, green: 247.0/255, blue: 247.0/255, alpha: 1) |
| 59 | 70 | window.minSize = NSSize(width: 820, height: 580) |
| @@ -129,6 +140,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 129 | 140 | completeUpdateMenu = appMenu.addItem(withTitle: "完成待安装更新…", action: #selector(completePendingUpdate), keyEquivalent: "") |
| 130 | 141 | completeUpdateMenu.isHidden = true |
| 131 | 142 | appMenu.addItem(.separator()) |
| 143 | 新增: if CageProfile.macGuestTrial { | |
| 144 | 新增: appMenu.addItem(withTitle: "复制试用客机登录密码", action: #selector(copyGuestLoginPassword), keyEquivalent: "") | |
| 145 | 新增: } | |
| 132 | 146 | appMenu.addItem(withTitle: "设置…", action: #selector(settings), keyEquivalent: ",") |
| 133 | 147 | appMenu.addItem(.separator()) |
| 134 | 148 | appMenu.addItem(withTitle: "隐藏 Cage", action: #selector(NSApplication.hide(_:)), keyEquivalent: "h") |
| @@ -182,6 +196,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 182 | 196 | let status = controllerNeedsUpdate ? "\n当前连接旧后台;更新尚未完成。" : "" |
| 183 | 197 | NSApp.orderFrontStandardAboutPanel(options: [.applicationName:"Cage", .applicationVersion:version, .credits:NSAttributedString(string:"本机隔离编码工作区\n基于 agent-vm、Lima、Chromium、noVNC 与 xterm.js" + status)]) |
| 184 | 198 | } |
| 199 | 新增: @objc private func copyGuestLoginPassword() { | |
| 200 | 新增: do { try MacGuestLoginCredential.copyForLogin() } | |
| 201 | 新增: catch { let alert = NSAlert(error: error); alert.beginSheetModal(for: window) } | |
| 202 | 新增: } | |
| 185 | 203 | @objc private func settings() { action("settings") } |
| 186 | 204 | @objc private func openProject() { action("openProject") } |
| 187 | 205 | @objc private func newTab() { action("newTab") } |
| @@ -204,6 +222,12 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 204 | 222 | } |
| 205 | 223 | private func action(_ name: String) { webView.evaluateJavaScript("window.cageNativeAction?.('\(name)')", completionHandler: nil) } |
| 206 | 224 | 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 | 新增: } | |
| 207 | 231 | guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { |
| 208 | 232 | completion(.failure(NSError(domain: "Cage", code: 1))); return |
| 209 | 233 | } |
| @@ -238,10 +262,15 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 238 | 262 | case .success(let entry): |
| 239 | 263 | self.controllerNeedsUpdate = entry.status != "ready" |
| 240 | 264 | 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 | |
| 242 | 267 | if let url = entry.url { self.expectedPort = url.port!; self.webView.load(URLRequest(url: url)) } |
| 243 | 268 | 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))。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。") } | |
| 245 | 274 | } |
| 246 | 275 | } |
| 247 | 276 | } |
| @@ -249,6 +278,47 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 249 | 278 | guard UUID(uuidString: id) != nil else { reply(nil,"下载标识无效"); return } |
| 250 | 279 | fileCommand(["browser-file", "--json", "--connection", connection, operation, id] + (path.map { [$0] } ?? []), reply: reply) |
| 251 | 280 | } |
| 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 | 新增: } | |
| 252 | 322 | private func fileCommand(_ arguments: [String], reply: @escaping (Any?, String?) -> Void) { |
| 253 | 323 | guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return } |
| 254 | 324 | DispatchQueue.global(qos: .userInitiated).async { |
| @@ -294,8 +364,21 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 294 | 364 | loading.textColor = .labelColor |
| 295 | 365 | } |
| 296 | 366 | 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 | 新增: } | |
| 299 | 382 | func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| 300 | 383 | guard let url = navigationAction.request.url, url.scheme == "http", url.host == "localhost", url.port == expectedPort else { decisionHandler(.cancel); return } |
| 301 | 384 | decisionHandler(.allow) |
| @@ -349,6 +432,67 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 349 | 432 | applyAppearance(value) |
| 350 | 433 | replyHandler(true,nil) |
| 351 | 434 | 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, "") } | |
| 352 | 496 | case "clipboardReadContent": |
| 353 | 497 | let board = NSPasteboard.general |
| 354 | 498 | 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 | ||
| 363 | 507 | } |
| 364 | 508 | replyHandler(["png":png.base64EncodedString()],nil) |
| 365 | 509 | } 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 | 新增: } | |
| 366 | 520 | case "chooseUploadFiles": |
| 367 | 521 | guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return } |
| 368 | 522 | let panel = NSOpenPanel() |
| @@ -429,6 +583,21 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 429 | 583 | do { try data.write(to: url, options: .atomic); replyHandler(true, nil) } |
| 430 | 584 | catch { replyHandler(nil, "主题未能导出,请检查保存位置的权限") } |
| 431 | 585 | } |
| 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 | 新增: } | |
| 432 | 601 | case "chooseFolder": |
| 433 | 602 | let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false |
| 434 | 603 | let storage = (body["purpose"] as? String) == "environmentStorage" |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -85,7 +85,8 @@ final class CageNativeInput: NSView, NSTextInputClient { | ||
| 85 | 85 | } |
| 86 | 86 | |
| 87 | 87 | 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")) { | |
| 89 | 90 | sendKey(event, down: true) |
| 90 | 91 | return |
| 91 | 92 | } |
| @@ -96,25 +97,13 @@ final class CageNativeInput: NSView, NSTextInputClient { | ||
| 96 | 97 | override func keyUp(with event: NSEvent) { sendKey(event, down: false) } |
| 97 | 98 | override func flagsChanged(with event: NSEvent) { |
| 98 | 99 | 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] | |
| 100 | 101 | if let flag = flags[event.keyCode] { sendKey(event, down: event.modifierFlags.contains(flag)) } |
| 101 | 102 | } |
| 102 | 103 | |
| 103 | 104 | 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, | |
| 118 | 107 | "metaKey":event.modifierFlags.contains(.command),"ctrlKey":event.modifierFlags.contains(.control), |
| 119 | 108 | "altKey":event.modifierFlags.contains(.option),"shiftKey":event.modifierFlags.contains(.shift),"repeat":event.isARepeat, |
| 120 | 109 | "modifierCapsLock":event.modifierFlags.contains(.capsLock),"textKey":text != nil]) |
| @@ -1,14 +1,31 @@ | ||
| 1 | 1 | import AppKit |
| 2 | 2 | import WebKit |
| 3 | 3 | |
| 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 | 新增: | |
| 4 | 12 | @main |
| 5 | 13 | enum NativeInputTests { |
| 6 | 14 | 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") | |
| 7 | 24 | let app = NSApplication.shared |
| 8 | 25 | app.setActivationPolicy(.prohibited) |
| 9 | 26 | let window = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 900, height: 700), |
| 10 | 27 | styleMask: [.titled, .resizable], backing: .buffered, defer: false) |
| 11 | 删除: let web = WKWebView(frame: window.contentView!.bounds) | |
| 28 | 新增: let web = RecordingWebView(frame: window.contentView!.bounds) | |
| 12 | 29 | window.contentView!.addSubview(web) |
| 13 | 30 | let input = CageNativeInput(frame: .zero) |
| 14 | 31 | input.configure(web: web) |
| @@ -35,8 +52,20 @@ enum NativeInputTests { | ||
| 35 | 52 | precondition(abs(moved.minY - lower.minY - 100) < 0.5) |
| 36 | 53 | web.setFrameSize(NSSize(width: 1000, height: 800)) |
| 37 | 54 | _ = 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 | 新增: } | |
| 38 | 67 | precondition(!input.handle(["operation":"deactivate", "owner":UUID().uuidString])) |
| 39 | 68 | 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") | |
| 41 | 70 | } |
| 42 | 71 | } |
| @@ -34,6 +34,26 @@ typedef struct { | ||
| 34 | 34 | static Cage app; |
| 35 | 35 | typedef struct { GPtrArray *paths; gint64 expires; } FileSelection; |
| 36 | 36 | static 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 | 新增:} | |
| 37 | 57 | static void bootstrap(const char *option); |
| 38 | 58 | static void show_error(const char *message); |
| 39 | 59 | |
| @@ -263,7 +283,7 @@ static char *choose_file(GtkFileChooserAction kind, const char *title, const cha | ||
| 263 | 283 | app.picker_open = FALSE; |
| 264 | 284 | return path; |
| 265 | 285 | } |
| 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; | |
| 267 | 287 | static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext *context) { |
| 268 | 288 | PendingReply *pending = g_new0(PendingReply, 1); |
| 269 | 289 | pending->reply = webkit_script_message_reply_ref(reply); |
| @@ -271,14 +291,27 @@ static PendingReply *pending_reply(WebKitScriptMessageReply *reply, JSCContext * | ||
| 271 | 291 | return pending; |
| 272 | 292 | } |
| 273 | 293 | static 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 | 新增: } | |
| 274 | 298 | webkit_script_message_reply_unref(pending->reply); |
| 275 | 299 | g_object_unref(pending->context); |
| 300 | 新增: g_free(pending->connection); | |
| 276 | 301 | g_free(pending); |
| 277 | 302 | } |
| 278 | 303 | static void browser_file_finished(JsonObject *object, const GError *error, gpointer data) { |
| 279 | 304 | PendingReply *pending = data; |
| 280 | 305 | if (error) reply_error(pending->reply, error->message); |
| 281 | 306 | 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 | 新增: } | |
| 282 | 315 | JsonNode *node = json_node_new(JSON_NODE_OBJECT); |
| 283 | 316 | json_node_set_object(node, object); |
| 284 | 317 | char *json = json_to_string(node, FALSE); |
| @@ -300,7 +333,7 @@ static void clipboard_content_text(GtkClipboard *clipboard, const gchar *text, g | ||
| 300 | 333 | if (text && strlen(text) > MAX_MESSAGE) reply_error(pending->reply, "剪贴板内容超过 2 MB。"); |
| 301 | 334 | else { |
| 302 | 335 | 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); | |
| 304 | 337 | reply_json(pending->reply, pending->context, json); |
| 305 | 338 | g_free(json); g_free(quoted); |
| 306 | 339 | } |
| @@ -319,7 +352,7 @@ static void clipboard_content_image(GtkClipboard *clipboard, GdkPixbuf *image, g | ||
| 319 | 352 | reply_error(pending->reply, "图片不能超过 20 MB 或 4000 万像素。"); |
| 320 | 353 | } else { |
| 321 | 354 | 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); | |
| 323 | 356 | reply_json(pending->reply, pending->context, json); |
| 324 | 357 | g_free(json); g_free(encoded); |
| 325 | 358 | } |
| @@ -381,6 +414,16 @@ static void reply_selected_uris(char **uris, PendingReply *pending) { | ||
| 381 | 414 | } |
| 382 | 415 | g_free(hostname); g_ptr_array_add(paths, path); |
| 383 | 416 | } |
| 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 | 新增: } | |
| 384 | 427 | char *json = error ? NULL : remember_files(paths, &error); |
| 385 | 428 | if (error) reply_error(pending->reply, error->message); |
| 386 | 429 | else reply_json(pending->reply, pending->context, json); |
| @@ -403,6 +446,150 @@ static void clipboard_file_uris(GtkClipboard *clipboard, gchar **uris, gpointer | ||
| 403 | 446 | if (uris && uris[0]) reply_selected_uris(uris, data); |
| 404 | 447 | else gtk_clipboard_request_contents(clipboard, gdk_atom_intern_static_string("x-special/gnome-copied-files"), clipboard_gnome_files, data); |
| 405 | 448 | } |
| 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 | 新增:} | |
| 406 | 593 | static void session_refreshed(JsonObject *object, const GError *error, gpointer data) { |
| 407 | 594 | PendingReply *pending = data; |
| 408 | 595 | const char *url = text_member(object, "url"); |
| @@ -491,7 +678,7 @@ static gboolean start_smoke(gpointer data) { | ||
| 491 | 678 | "if(phase==='seed')localStorage.setItem(storageKey,marker);" |
| 492 | 679 | "const storageMarkerMatched=!phase||localStorage.getItem(storageKey)===marker;" |
| 493 | 680 | "if(phase==='verify'&&storageMarkerMatched)localStorage.removeItem(storageKey);" |
| 494 | 删除: "stage='bridge';const bridge=window.webkit.messageHandlers.cage;" | |
| 681 | 新增: "stage='bridge';const bridge=window.cageNativeBridge;" | |
| 495 | 682 | "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}" |
| 496 | 683 | "stage='account-device';const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" |
| 497 | 684 | "stage='app-update';const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" |
| @@ -516,7 +703,7 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 516 | 703 | (void)manager; (void)data; |
| 517 | 704 | char *json = jsc_value_to_json(value, 0); |
| 518 | 705 | 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) || | |
| 520 | 707 | !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { |
| 521 | 708 | reply_error(reply, "原生请求格式无效。"); |
| 522 | 709 | goto done; |
| @@ -603,6 +790,19 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 603 | 790 | } |
| 604 | 791 | g_free(path); |
| 605 | 792 | } |
| 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 | 新增: } | |
| 606 | 806 | } else if (!strcmp(name, "chooseFolder")) { |
| 607 | 807 | if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); |
| 608 | 808 | else { |
| @@ -614,6 +814,39 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 614 | 814 | } |
| 615 | 815 | } else if (!strcmp(name, "clipboardRead")) { |
| 616 | 816 | 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); } | |
| 617 | 850 | } else if (!strcmp(name, "clipboardReadContent")) { |
| 618 | 851 | gtk_clipboard_request_uris(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), clipboard_file_uris, pending_reply(reply, context)); |
| 619 | 852 | } else if (!strcmp(name, "chooseUploadFiles")) { |
| @@ -739,7 +972,7 @@ static void install_bridge(void) { | ||
| 739 | 972 | "window.cageLinuxBridgeInit='origin-valid';window.cageNativeIMEAvailable=true;try{" |
| 740 | 973 | "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;" |
| 741 | 974 | "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});" | |
| 743 | 976 | "window.cageLinuxBridgeInit='ready';}catch(error){window.cageLinuxBridgeInit=error.name;}" |
| 744 | 977 | "})();", app.port, token); |
| 745 | 978 | /* The host allowlist narrows injection; the script and native receiver |
| @@ -757,7 +990,20 @@ static void bootstrapped(JsonObject *object, const GError *error, gpointer data) | ||
| 757 | 990 | (void)data; |
| 758 | 991 | app.bootstrapping = FALSE; |
| 759 | 992 | 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 | 新增: } | |
| 761 | 1007 | const char *status = text_member(object, "status"); |
| 762 | 1008 | app.needs_update = strcmp(status, "ready") != 0; |
| 763 | 1009 | if (!strcmp(status, "upgrade_pending")) { |
| @@ -831,9 +1077,12 @@ static void load_changed(WebKitWebView *web, WebKitLoadEvent event, gpointer dat | ||
| 831 | 1077 | } |
| 832 | 1078 | } |
| 833 | 1079 | static 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; | |
| 835 | 1081 | 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); | |
| 837 | 1086 | return TRUE; |
| 838 | 1087 | } |
| 839 | 1088 | static void process_terminated(WebKitWebView *web, WebKitWebProcessTerminationReason reason, gpointer data) { |
| @@ -978,7 +1227,7 @@ static gboolean smoke_diagnostics(gpointer data) { | ||
| 978 | 1227 | "const account=await fetch('/api/account');const state=await fetch('/api/status');const settings=await fetch('/api/settings');" |
| 979 | 1228 | "let unlocked=false;try{unlocked=(await account.json()).unlocked===true;}catch{}" |
| 980 | 1229 | "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," | |
| 982 | 1231 | "renderedButtons:document.querySelectorAll('button').length,accountStatus:account.status,accountUnlocked:unlocked,statusStatus:state.status,settingsStatus:settings.status};"; |
| 983 | 1232 | webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, "cage-smoke-diagnostics", NULL, smoke_diagnostics_ready, NULL); |
| 984 | 1233 | return G_SOURCE_REMOVE; |
| @@ -1030,7 +1279,7 @@ int main(int argc, char **argv) { | ||
| 1030 | 1279 | } |
| 1031 | 1280 | char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA256, app.profile, -1); |
| 1032 | 1281 | 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); | |
| 1034 | 1283 | g_free(hash); g_free(id); |
| 1035 | 1284 | g_signal_connect(app.application, "activate", G_CALLBACK(activate), NULL); |
| 1036 | 1285 | if (app.smoke_output) { |
| @@ -23,25 +23,12 @@ internal sealed class MainWindow : Form | ||
| 23 | 23 | public MainWindow() |
| 24 | 24 | { |
| 25 | 25 | 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"; | |
| 27 | 28 | StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247); |
| 28 | 29 | 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; | |
| 43 | 30 | status.Controls.AddRange([message, retry, existing, complete]); |
| 44 | 删除: Controls.Add(web); Controls.Add(status); Controls.Add(menus); | |
| 31 | 新增: Controls.Add(web); Controls.Add(status); | |
| 45 | 32 | Controls.Add(nativeInput); |
| 46 | 33 | retry.Click += async (_, _) => { |
| 47 | 34 | if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap(); |
| @@ -50,9 +37,13 @@ internal sealed class MainWindow : Form | ||
| 50 | 37 | complete.Click += async (_, _) => { |
| 51 | 38 | if (ConfirmStop()) await Bootstrap("--complete-update"); |
| 52 | 39 | }; |
| 53 | 删除: var trayMenu = new ContextMenuStrip(); | |
| 40 | 新增: var trayMenu = new TrayMenu(); | |
| 54 | 41 | 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()); | |
| 55 | 45 | trayMenu.Items.Add("退出 Cage…", null, (_, _) => RequestQuit()); |
| 46 | 新增: trayMenu.Opening += (_, _) => (chrome ?? new WindowChrome(BackColor, ForeColor, false)).ApplyMenu(trayMenu); | |
| 56 | 47 | tray = new NotifyIcon { Icon = Icon, Text = "Cage", Visible = true, ContextMenuStrip = trayMenu }; |
| 57 | 48 | tray.DoubleClick += (_, _) => RestoreWindow(); |
| 58 | 49 | updater = new AppUpdater(PublishUpdate, () => { allowQuit = true; Close(); }, () => _ = Bootstrap()); |
| @@ -62,17 +53,61 @@ internal sealed class MainWindow : Form | ||
| 62 | 53 | }; |
| 63 | 54 | Resize += (_, _) => PublishVisibility(); VisibleChanged += (_, _) => PublishVisibility(); |
| 64 | 55 | FormClosing += (_, e) => { |
| 56 | 新增: SaveWindowPlacement(); | |
| 65 | 57 | if (!allowQuit && e.CloseReason is not (CloseReason.WindowsShutDown or CloseReason.TaskManagerClosing)) { e.Cancel = true; Hide(); } |
| 66 | 58 | }; |
| 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; | |
| 68 | 101 | } |
| 69 | 102 | |
| 70 | 103 | private WindowChrome? chrome; |
| 71 | 104 | |
| 72 | 105 | private void ApplyWindowChrome() |
| 73 | 106 | { |
| 74 | 删除: if (IsHandleCreated && MainMenuStrip != null) | |
| 107 | 新增: if (IsHandleCreated) | |
| 75 | 108 | chrome?.Apply(Handle, MainMenuStrip); |
| 109 | 新增: if (tray?.ContextMenuStrip != null) | |
| 110 | 新增: chrome?.ApplyMenu(tray.ContextMenuStrip); | |
| 76 | 111 | } |
| 77 | 112 | |
| 78 | 113 | protected override void OnHandleCreated(EventArgs e) |
| @@ -87,13 +122,11 @@ internal sealed class MainWindow : Form | ||
| 87 | 122 | ApplyWindowChrome(); |
| 88 | 123 | } |
| 89 | 124 | |
| 90 | 删除: private void AddAction(ToolStripMenuItem menu, string label, string action, Keys shortcut) => | |
| 91 | 删除: menu.DropDownItems.Add(new ToolStripMenuItem(label, null, (_, _) => Action(action)) { ShortcutKeys = shortcut }); | |
| 92 | 125 | private bool ConfirmStop() => MessageBox.Show(this, |
| 93 | 126 | "请先保存编辑器中的文件并结束正在运行的工作。继续后 Cage 会停止环境、安装已验证的更新并重新启动。", |
| 94 | 127 | "保存并停止环境后安装重启", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK; |
| 95 | 128 | |
| 96 | 删除: public void RestoreWindow() { Show(); WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); } | |
| 129 | 新增: public void RestoreWindow() { Show(); if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); } | |
| 97 | 130 | private void RequestQuit() |
| 98 | 131 | { |
| 99 | 132 | RestoreWindow(); |
| @@ -144,7 +177,15 @@ internal sealed class MainWindow : Form | ||
| 144 | 177 | core.WebMessageReceived += Receive; |
| 145 | 178 | core.ProcessFailed += (_, _) => { webFailed = true; Error("工作台显示进程已退出。后台任务保留,可重试连接。"); }; |
| 146 | 179 | 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 | 新增: } | |
| 148 | 189 | status.Hide(); web.Show(); web.Focus(); PublishVisibility(); |
| 149 | 190 | }; |
| 150 | 191 | await core.AddScriptToExecuteOnDocumentCreatedAsync(BridgeScript); |
| @@ -176,6 +217,8 @@ internal sealed class MainWindow : Form | ||
| 176 | 217 | File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new { |
| 177 | 218 | success = true, nativeBridgeReady = true, version = AppUpdater.Version, |
| 178 | 219 | webviewVersion = web.CoreWebView2.Environment.BrowserVersionString, |
| 220 | 新增: windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi, | |
| 221 | 新增: nativeMenuBar = MainMenuStrip != null, | |
| 179 | 222 | })); |
| 180 | 223 | } |
| 181 | 224 | catch (Exception error) { Error(error.Message); } |
| @@ -201,8 +244,11 @@ internal sealed class MainWindow : Form | ||
| 201 | 244 | Text = controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage"; |
| 202 | 245 | web.CoreWebView2.Navigate(entry.AbsoluteUri); |
| 203 | 246 | } |
| 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 | 新增: } | |
| 206 | 252 | finally { bootstrapping = false; } |
| 207 | 253 | } |
| 208 | 254 | |
| @@ -233,10 +279,14 @@ internal sealed class MainWindow : Form | ||
| 233 | 279 | string id = ""; |
| 234 | 280 | try |
| 235 | 281 | { |
| 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; | |
| 238 | 285 | id = body.Text("id"); |
| 239 | 286 | 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("请求内容过大,请减少图片或文本内容后重试"); | |
| 240 | 290 | var request = body.GetProperty("request"); |
| 241 | 291 | object? result; |
| 242 | 292 | switch (request.Text("action")) |
| @@ -277,11 +327,30 @@ internal sealed class MainWindow : Form | ||
| 277 | 327 | File.WriteAllText(picker.FileName, themeText, new System.Text.UTF8Encoding(false)); result = true; |
| 278 | 328 | } |
| 279 | 329 | 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 | 新增: } | |
| 280 | 344 | case "chooseFolder": |
| 281 | 345 | using (var picker = new FolderBrowserDialog { Description = request.Text("purpose") == "environmentStorage" ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true }) |
| 282 | 346 | result = picker.ShowDialog(this) == DialogResult.OK ? picker.SelectedPath : ""; |
| 283 | 347 | break; |
| 284 | 348 | 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; | |
| 285 | 354 | case "saveBrowserDownload": |
| 286 | 355 | case "browserDownloadAction": |
| 287 | 356 | { |
| @@ -316,6 +385,18 @@ internal sealed class MainWindow : Form | ||
| 316 | 385 | } |
| 317 | 386 | else result = new { text = Clipboard.ContainsText() ? Clipboard.GetText() : "" }; |
| 318 | 387 | 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; | |
| 319 | 400 | case "chooseUploadFiles": |
| 320 | 401 | using (var picker = new OpenFileDialog { Title = "选择本机文件", Multiselect = request.TryGetProperty("multiple", out var multiple) && multiple.ValueKind == JsonValueKind.True, CheckFileExists = true }) |
| 321 | 402 | result = picker.ShowDialog(this) == DialogResult.OK ? RememberFiles(picker.FileNames) : new { canceled = true }; |
| @@ -375,6 +456,11 @@ internal sealed class MainWindow : Form | ||
| 375 | 456 | if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return; |
| 376 | 457 | window.cageNativeIMEAvailable = true; |
| 377 | 458 | 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 | 新增: ]); | |
| 378 | 464 | chrome.webview.addEventListener('message', ({data}) => { |
| 379 | 465 | const item = pending.get(data.id); if (!item) return; |
| 380 | 466 | pending.delete(data.id); clearTimeout(item.timer); |
| @@ -382,7 +468,9 @@ internal sealed class MainWindow : Form | ||
| 382 | 468 | }); |
| 383 | 469 | const cage = {postMessage(request) { return new Promise((resolve, reject) => { |
| 384 | 470 | 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); | |
| 386 | 474 | pending.set(id, {resolve, reject, timer}); chrome.webview.postMessage({id, request}); |
| 387 | 475 | }); }}; |
| 388 | 476 | Object.defineProperty(window, 'webkit', {value: {messageHandlers: {cage}}, writable: false}); |
| @@ -13,6 +13,8 @@ internal sealed class NativeInput : TextBox | ||
| 13 | 13 | private bool composing, resetting; |
| 14 | 14 | private Keys lastKey; |
| 15 | 15 | private bool repeating; |
| 16 | 新增: private int scanCode; | |
| 17 | 新增: private bool extendedKey; | |
| 16 | 18 | private char? highSurrogate; |
| 17 | 19 | |
| 18 | 20 | internal NativeInput(Action<Dictionary<string, object?>> publish) |
| @@ -79,6 +81,7 @@ internal sealed class NativeInput : TextBox | ||
| 79 | 81 | { |
| 80 | 82 | if (!composing && (keyData & (Keys.Control | Keys.Alt)) != 0) |
| 81 | 83 | { |
| 84 | 新增: ReadKeyMessage(msg); | |
| 82 | 85 | Key(keyData & Keys.KeyCode, true); |
| 83 | 86 | return true; |
| 84 | 87 | } |
| @@ -113,7 +116,8 @@ internal sealed class NativeInput : TextBox | ||
| 113 | 116 | } |
| 114 | 117 | private static bool IsCommand(Keys key) => key is Keys.Enter or Keys.Tab or Keys.Back or Keys.Delete or Keys.Escape or |
| 115 | 118 | 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; | |
| 117 | 121 | |
| 118 | 122 | private void Key(Keys key, bool down, string? text = null) |
| 119 | 123 | { |
| @@ -125,22 +129,55 @@ internal sealed class NativeInput : TextBox | ||
| 125 | 129 | Keys.ShiftKey => ("Shift", "ShiftLeft"), Keys.ControlKey => ("Control", "ControlLeft"), Keys.Menu => ("Alt", "AltLeft"), |
| 126 | 130 | Keys.LWin => ("Meta", "MetaLeft"), Keys.RWin => ("Meta", "MetaRight"), Keys.CapsLock => ("CapsLock", "CapsLock"), |
| 127 | 131 | 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"), | |
| 128 | 141 | _ when key >= Keys.A && key <= Keys.Z => (key.ToString().ToLowerInvariant(), "Key" + key), |
| 129 | 142 | _ 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)), | |
| 130 | 144 | _ when key >= Keys.F1 && key <= Keys.F24 => (key.ToString(), key.ToString()), |
| 131 | 145 | _ => (text ?? "Unidentified", "Unidentified") |
| 132 | 146 | }; |
| 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 | 新增: } | |
| 133 | 163 | 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, | |
| 135 | 165 | ["ctrlKey"] = (ModifierKeys & Keys.Control) != 0, ["altKey"] = (ModifierKeys & Keys.Alt) != 0, |
| 136 | 166 | ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false }); |
| 137 | 167 | } |
| 138 | 168 | |
| 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 | 新增: | |
| 139 | 176 | protected override void WndProc(ref Message message) |
| 140 | 177 | { |
| 141 | 178 | const int Start = 0x10d, End = 0x10e, Composition = 0x10f; |
| 142 | 179 | 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); | |
| 144 | 181 | if (!resetting && owner.Length > 0) |
| 145 | 182 | { |
| 146 | 183 | if (message.Msg == Start) { composing = true; Emit("compositionstart"); } |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -10,7 +10,7 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark | ||
| 10 | 10 | internal static Color ContrastingText(Color value) => |
| 11 | 11 | value.GetBrightness() < 0.5 ? Color.White : Color.Black; |
| 12 | 12 | |
| 13 | 删除: internal void Apply(IntPtr window, MenuStrip menus) | |
| 13 | 新增: internal void Apply(IntPtr window, MenuStrip? menus) | |
| 14 | 14 | { |
| 15 | 15 | bool accessible = SystemInformation.HighContrast; |
| 16 | 16 | int darkFrame = dark && !accessible ? 1 : 0; |
| @@ -23,9 +23,15 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark | ||
| 23 | 23 | DwmSetWindowAttribute(window, 36, ref text, sizeof(int)); // DWMWA_TEXT_COLOR |
| 24 | 24 | } |
| 25 | 25 | |
| 26 | 新增: if (menus != null) ApplyMenu(menus); | |
| 27 | 新增: } | |
| 28 | 新增: | |
| 29 | 新增: internal void ApplyMenu(ToolStrip menu) | |
| 30 | 新增: { | |
| 31 | 新增: bool accessible = SystemInformation.HighContrast; | |
| 26 | 32 | ToolStripRenderer renderer = accessible ? new ToolStripSystemRenderer() |
| 27 | 33 | : new MenuRenderer(background, foreground); |
| 28 | 删除: ApplyMenu(menus, renderer, accessible); | |
| 34 | 新增: ApplyMenu(menu, renderer, accessible); | |
| 29 | 35 | } |
| 30 | 36 | |
| 31 | 37 | private void ApplyMenu(ToolStrip menu, ToolStripRenderer renderer, bool accessible) |
| @@ -56,7 +62,27 @@ internal sealed class WindowChrome(Color background, Color foreground, bool dark | ||
| 56 | 62 | { |
| 57 | 63 | if (!e.Item.Selected && !e.Item.Pressed) return; |
| 58 | 64 | 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); | |
| 60 | 86 | } |
| 61 | 87 | |
| 62 | 88 | protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e) |
| @@ -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 | 新增:} | |
| @@ -48,5 +48,12 @@ | ||
| 48 | 48 | "prefix": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64/", |
| 49 | 49 | "file": "qemu-e470268ff446ec56728215a987ed166d5ed8fb64-source.tar", |
| 50 | 50 | "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" | |
| 51 | 58 | } |
| 52 | 59 | } |
| @@ -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 | 新增:+} | |
| @@ -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) | |
| @@ -2,15 +2,26 @@ | ||
| 2 | 2 | set -euo pipefail |
| 3 | 3 | cd "$(dirname "$0")/.." |
| 4 | 4 | if [[ "$(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}" | |
| 7 | 14 | if [[ "$app_destination" != /*.app ]]; then echo 'CAGE_BUILD_OUTPUT must be an absolute .app path.' >&2; exit 2; fi |
| 8 | 15 | check_destination() { |
| 9 | 16 | local target="$1" |
| 10 | 17 | [[ ! -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 | |
| 12 | 19 | echo 'Build destination is not a Cage application.' >&2; exit 1 |
| 13 | 20 | fi |
| 21 | 新增: if ! codesign --verify --deep --strict "$target"; then | |
| 22 | 新增: echo '现有 Cage 应用包含修改内容或无法验证完整性,已保留。请将个人文件移出应用包,或选择新的构建目录后重试。' >&2 | |
| 23 | 新增: exit 1 | |
| 24 | 新增: fi | |
| 14 | 25 | local running_pids |
| 15 | 26 | running_pids="$(/usr/sbin/lsof -t "$target/Contents/MacOS/Cage" "$target/Contents/Resources/cage" 2>/dev/null || true)" |
| 16 | 27 | if [[ -n "$running_pids" ]]; then |
| @@ -18,7 +29,7 @@ check_destination() { | ||
| 18 | 29 | fi |
| 19 | 30 | } |
| 20 | 31 | check_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 | |
| 22 | 33 | version="$(tr -d '\n\r' < VERSION)" |
| 23 | 34 | if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]]; then echo 'Invalid VERSION.' >&2; exit 1; fi |
| 24 | 35 | short_version="${version%%-*}" |
| @@ -31,15 +42,24 @@ export MACOSX_DEPLOYMENT_TARGET=14.0 | ||
| 31 | 42 | export CGO_CFLAGS="${CGO_CFLAGS:-} -mmacosx-version-min=14.0" |
| 32 | 43 | export CGO_LDFLAGS="${CGO_LDFLAGS:-} -mmacosx-version-min=14.0" |
| 33 | 44 | bash 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 | |
| 35 | 51 | build_stage="$(mktemp -d "$PWD/_output/app-build.XXXXXX")" |
| 36 | 52 | install_stage='' |
| 37 | 53 | trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT |
| 38 | 54 | bundle="$build_stage/Cage.app" |
| 39 | 55 | mkdir -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" | |
| 41 | 57 | swiftc -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" |
| 42 | 58 | cp _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 | |
| 43 | 63 | node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources" |
| 44 | 64 | cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo" |
| 45 | 65 | for 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 | ||
| 58 | 78 | <?xml version="1.0" encoding="UTF-8"?> |
| 59 | 79 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> |
| 60 | 80 | <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> | |
| 64 | 84 | <key>CFBundleVersion</key><string>$build_version</string> |
| 65 | 85 | <key>CFBundleShortVersionString</key><string>$short_version</string> |
| 66 | 86 | <key>CageVersion</key><string>$version</string> |
| @@ -98,26 +118,31 @@ if ! mv "$bundle" "$app_destination"; then | ||
| 98 | 118 | fi |
| 99 | 119 | bundle="$app_destination" |
| 100 | 120 | printf 'Built: %s\n' "$bundle" |
| 101 | 删除:if [[ "${1:-}" == "--install" ]]; then | |
| 121 | 新增:if [[ "${1:-}" == --install* ]]; then | |
| 102 | 122 | mkdir -p "$HOME/Applications" |
| 103 | 123 | install_stage="$(mktemp -d "$HOME/Applications/.Cage-install.XXXXXX")" |
| 104 | 124 | ditto "$bundle" "$install_stage/Cage.app" |
| 105 | 125 | 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 | |
| 110 | 130 | exit 1 |
| 111 | 131 | fi |
| 112 | 删除: printf 'Installed: %s/Applications/Cage.app\n' "$HOME" | |
| 132 | 新增: printf 'Installed: %s\n' "$installed_app" | |
| 113 | 133 | # An installed build has one launchable copy. Remove the staging build too, |
| 114 | 134 | # 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" \ | |
| 117 | 142 | --root "$bundle" --root "$PWD/_output" --root "$HOME/Applications" \ |
| 118 | 143 | --root /Applications --root "$HOME/.claude-cage-validation" |
| 119 | 144 | else |
| 120 | 删除: if [[ -z "${CAGE_BUILD_OUTPUT:-}" ]]; then | |
| 145 | 新增: if [[ -z "${CAGE_BUILD_OUTPUT:-}" && "${1:-}" != --macos-trial ]]; then | |
| 121 | 146 | node scripts/cleanup-apps.mjs --keep "$bundle" --root "$PWD/_output" |
| 122 | 147 | fi |
| 123 | 148 | fi |
| @@ -28,6 +28,7 @@ try { | ||
| 28 | 28 | Invoke-BuildTool $npm @('--prefix', 'ui', 'run', 'build') |
| 29 | 29 | } |
| 30 | 30 | 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') } | |
| 31 | 32 | $env:GOOS = 'windows'; $env:GOARCH = 'amd64'; $env:CGO_ENABLED = '0' |
| 32 | 33 | $goDependencies = & $go 'list' '-deps' './cmd/cage-client' |
| 33 | 34 | 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 轻量远程客户端(未签名开发构建) | ||
| 74 | 75 | 此目录为独立构建产物,不会安装、替换完整 Cage 或自动下载完整 Cage 更新。 |
| 75 | 76 | 本构建未签名或发布。Windows 原生运行验收范围以项目测试报告为准。 |
| 76 | 77 | '@) |
| 78 | 新增: if ($IsWindows) { | |
| 79 | 新增: Invoke-BuildTool (Join-Path $resources 'cage.exe') @('verify-web-assets') | |
| 80 | 新增: Assert-WindowsWorkbench $app | |
| 81 | 新增: } | |
| 77 | 82 | Compress-Archive -Path $app -DestinationPath (Join-Path $result 'Cage-Client-windows-amd64.zip') -CompressionLevel Optimal |
| 78 | 83 | if (Test-Path -LiteralPath $destination) { throw 'Client output already exists; no files were replaced.' } |
| 79 | 84 | Move-Item -LiteralPath $result -Destination $destination |
| @@ -24,6 +24,8 @@ destination="$output_root/build-$(date +%Y%m%d-%H%M%S)-$suffix" | ||
| 24 | 24 | if [[ "$skip_ui" == false ]]; then |
| 25 | 25 | [[ -d ui/node_modules ]] || npm --prefix ui ci --no-audit --no-fund |
| 26 | 26 | npm --prefix ui run build |
| 27 | 新增:else | |
| 28 | 新增: node ui/scripts/verify-build.mjs | |
| 27 | 29 | fi |
| 28 | 30 | [[ -f internal/workbench/web/index.html ]] || { echo 'Build the UI before using --skip-ui.' >&2; exit 1; } |
| 29 | 31 | go 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 | ||
| 31 | 33 | echo 'The client unexpectedly depends on a virtual machine runtime; build stopped.' >&2; exit 1 |
| 32 | 34 | fi |
| 33 | 35 | CGO_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 | |
| 34 | 37 | mkdir -p "$stage/result" |
| 35 | 38 | |
| 36 | 39 | if [[ "$platform" == macos ]]; then |
| @@ -38,7 +41,7 @@ if [[ "$platform" == macos ]]; then | ||
| 38 | 41 | mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" |
| 39 | 42 | swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library \ |
| 40 | 43 | -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 \ | |
| 42 | 45 | -o "$bundle/Contents/MacOS/Cage" |
| 43 | 46 | node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources" |
| 44 | 47 | cp "$stage/cage" "$bundle/Contents/Resources/cage" |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | #!/usr/bin/env bash |
| 2 | 2 | set -euo pipefail |
| 3 | 3 | cd "$(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; } | |
| 5 | 5 | case "${1:-}" in ''|--prebuilt-backend) ;; *) echo 'Usage: scripts/build-linux.sh [--prebuilt-backend]' >&2; exit 2 ;; esac |
| 6 | 6 | version=$(tr -d '\r\n' < VERSION) |
| 7 | 7 | [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { echo 'Invalid VERSION.' >&2; exit 1; } |
| @@ -16,6 +16,7 @@ else | ||
| 16 | 16 | [[ -x _output/bin/cage ]] || { echo 'Missing prebuilt Linux backend.' >&2; exit 1; } |
| 17 | 17 | _output/bin/cage help >/dev/null |
| 18 | 18 | fi |
| 19 | 新增:_output/bin/cage verify-web-assets | |
| 19 | 20 | mkdir -p _output/linux-amd64 |
| 20 | 21 | stage=$(mktemp -d "$PWD/_output/linux-amd64/build.XXXXXX") |
| 21 | 22 | trap 'rm -rf "$stage"' EXIT |
| @@ -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" | |
| @@ -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" | |
| @@ -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 | |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | [CmdletBinding()] |
| 3 | 3 | param( |
| 4 | 4 | [switch]$Release, |
| 5 | 新增: [switch]$Sign, | |
| 5 | 6 | [switch]$SkipUI, |
| 6 | 7 | [string]$OutputDirectory, |
| 7 | 8 | [string]$DependencyCache |
| @@ -13,7 +14,8 @@ if (-not $DependencyCache) { $DependencyCache = Join-Path $repository '_output/w | ||
| 13 | 14 | $OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory) |
| 14 | 15 | if (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.' } |
| 15 | 16 | $version = Get-CageVersion $repository |
| 16 | 删除:if ($Release) { Assert-WindowsSigningConfiguration } | |
| 17 | 新增:$signed = $Release -or $Sign | |
| 18 | 新增:if ($signed) { Assert-WindowsSigningConfiguration } | |
| 17 | 19 | $go = Get-BuildCommand @('go') |
| 18 | 20 | $dotnet = Get-BuildCommand @('dotnet') |
| 19 | 21 | $node = Get-BuildCommand @('node') |
| @@ -28,6 +30,8 @@ try { | ||
| 28 | 30 | if (-not $SkipUI) { |
| 29 | 31 | Invoke-BuildTool $npm @('--prefix', 'ui', 'ci', '--no-audit', '--no-fund') |
| 30 | 32 | Invoke-BuildTool $npm @('run', '--prefix', 'ui', 'build') |
| 33 | 新增: } else { | |
| 34 | 新增: Invoke-BuildTool $node @('ui/scripts/verify-build.mjs') | |
| 31 | 35 | } |
| 32 | 36 | $limaVersion = (Get-Content 'internal/limaembed/lima-version' -Raw).Trim() |
| 33 | 37 | $assets = Join-Path $repository 'internal/limaembed/assets' |
| @@ -47,10 +51,35 @@ try { | ||
| 47 | 51 | $resources = Join-Path $app 'resources' |
| 48 | 52 | New-Item -ItemType Directory -Path $resources -Force | Out-Null |
| 49 | 53 | 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' | |
| 50 | 77 | $env:GOOS = 'windows' |
| 51 | 78 | $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' |
| 52 | 79 | $ldflags = "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=$version -X github.com/lima-vm/lima/v2/pkg/version.Version=$limaVersion" |
| 53 | 80 | 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') | |
| 54 | 83 | Invoke-BuildTool $dotnet @('publish', 'desktop/windows/Cage.Windows.csproj', '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true', |
| 55 | 84 | '-p:EnableWindowsTargeting=true', '-p:PublishSingleFile=true', '-p:RestoreLockedMode=true', "-p:Version=$version", "-p:InformationalVersion=$version", '-o', $app) |
| 56 | 85 | Get-ChildItem -LiteralPath $app -File | Where-Object { $_.Extension -in @('.pdb', '.xml') } | Remove-Item -Force |
| @@ -74,13 +103,22 @@ try { | ||
| 74 | 103 | $qemuArchive = Get-VerifiedDependency $dependencies.qemu $DependencyCache |
| 75 | 104 | $qemuTarget = Join-Path $resources 'runtime/qemu' |
| 76 | 105 | 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 | |
| 77 | 109 | # Ship the x64 VM only, with its original firmware, DLLs and notices. |
| 78 | 110 | Get-ChildItem -LiteralPath $qemuTarget -Filter 'qemu-system-*.exe' | Where-Object { $_.Name -ne 'qemu-system-x86_64.exe' } | Remove-Item -Force |
| 79 | 111 | Get-ChildItem -LiteralPath (Join-Path $qemuTarget 'share') -File | |
| 80 | 112 | 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')) { | |
| 82 | 114 | if (-not (Test-Path -LiteralPath (Join-Path $qemuTarget $file))) { throw "QEMU archive lacks $file" } |
| 83 | 115 | } |
| 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 | 新增: } | |
| 84 | 122 | Remove-Item -LiteralPath (Join-Path $qemuTarget '$PLUGINSDIR') -Recurse -Force -ErrorAction SilentlyContinue |
| 85 | 123 | Remove-Item -LiteralPath (Join-Path $qemuTarget 'qemu-uninstall.exe') -Force -ErrorAction SilentlyContinue |
| 86 | 124 | $webviewArchive = Get-VerifiedDependency $dependencies.webview2 $DependencyCache |
| @@ -122,12 +160,13 @@ try { | ||
| 122 | 160 | Copy-Item -LiteralPath 'LICENSE' -Destination (Join-Path $app 'LICENSE.txt') |
| 123 | 161 | [IO.File]::WriteAllText((Join-Path $app 'Cage.install-id'), 'io.github.lee-xeo.claude-cage') |
| 124 | 162 | [IO.File]::WriteAllText((Join-Path $app 'version.txt'), $version) |
| 125 | 删除: if ($Release) { | |
| 163 | 新增: if ($signed) { | |
| 126 | 164 | $signTool = Get-SigningTool |
| 127 | 165 | foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) { Sign-CageFile (Join-Path $app $file) $signTool } |
| 128 | 166 | } else { |
| 129 | 167 | [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") |
| 130 | 168 | } |
| 169 | 新增: Assert-WindowsWorkbench $app | |
| 131 | 170 | $previousOutput = $null |
| 132 | 171 | if (Test-Path -LiteralPath $OutputDirectory) { |
| 133 | 172 | $marker = Join-Path $OutputDirectory 'Cage.install-id' |
| @@ -24,6 +24,9 @@ if (offline) { | ||
| 24 | 24 | try { |
| 25 | 25 | const version = fs.readFileSync("VERSION", "utf8").trim(); |
| 26 | 26 | 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 | 新增: } | |
| 27 | 30 | execFileSync("go", ["build", "-trimpath", "-ldflags", "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=" + version, "-o", binary, "./cmd/cage"], { |
| 28 | 31 | env: {...process.env, CGO_ENABLED:"0", GOOS:"linux", GOARCH:"amd64"}, stdio:"inherit" |
| 29 | 32 | }); |
| @@ -39,6 +42,8 @@ if (offline) { | ||
| 39 | 42 | fs.mkdirSync(recipe, {recursive:true}); |
| 40 | 43 | for (const name of ["Dockerfile.guest","restore-apt-sources.sh","build-guest.sh"]) |
| 41 | 44 | 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")); | |
| 42 | 47 | for (const name of ["cage-server.service","cage-container-engine.service"]) |
| 43 | 48 | fs.copyFileSync(path.join("deploy/cloud",name),path.join(stage,name)); |
| 44 | 49 | const runtime = JSON.parse(fs.readFileSync("deploy/cloud/runtime-artifacts.json")); |
| @@ -63,8 +63,18 @@ try { | ||
| 63 | 63 | & (Join-Path $PSScriptRoot 'install-nsis.ps1') -Destination $env:RUNNER_TEMP |
| 64 | 64 | $env:PATH = (Join-Path $env:RUNNER_TEMP 'nsis-3.13') + [IO.Path]::PathSeparator + $env:PATH |
| 65 | 65 | 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 | |
| 67 | 69 | & (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 | 新增: } | |
| 68 | 78 | Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj') |
| 69 | 79 | Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts') |
| 70 | 80 | # Exercise a second volume when the runner keeps its workspace and temp on different drives. |
| @@ -75,6 +85,7 @@ try { | ||
| 75 | 85 | Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Storage|Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)') |
| 76 | 86 | Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)') |
| 77 | 87 | 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$') | |
| 78 | 89 | Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths') |
| 79 | 90 | Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host') |
| 80 | 91 | $packageArguments = @{ Release = $Release; SkipBuild = $true } |
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | #!/usr/bin/env node |
| 2 | 2 | import { cpSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; |
| 3 | 新增:import { execFileSync } from "node:child_process"; | |
| 3 | 4 | import { resolve, join } from "node:path"; |
| 4 | 5 | |
| 5 | 6 | // Collect the licenses of the packages actually shipped in the workbench. |
| @@ -10,6 +11,7 @@ mkdirSync(target, { recursive: true }); | ||
| 10 | 11 | for (const file of ["LICENSE", "NOTICE", "THIRD_PARTY_LICENSES"]) { |
| 11 | 12 | cpSync(join(root, file), join(target, file)); |
| 12 | 13 | } |
| 14 | 新增:cpSync(join(root, "internal/exitpolicy/data"), join(target, "exit-country-data"), { recursive: true }); | |
| 13 | 15 | const lock = JSON.parse(readFileSync(join(root, "ui/package-lock.json"), "utf8")); |
| 14 | 16 | const notices = []; |
| 15 | 17 | for (const [path, entry] of Object.entries(lock.packages)) { |
| @@ -31,3 +33,24 @@ for (const file of ["LICENSE.txt", "AUTHORS", "NOTICE.cage", "docs", "vendor/pak | ||
| 31 | 33 | } |
| 32 | 34 | // MPL-covered source and local modifications travel with the executable. |
| 33 | 35 | cpSync(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"); | |
| @@ -52,6 +52,7 @@ trap 'rm -f "$list"' EXIT | ||
| 52 | 52 | modules windows arm64 0 ./cmd/agent-vm |
| 53 | 53 | modules linux arm64 0 github.com/lima-vm/lima/v2/cmd/lima-guestagent |
| 54 | 54 | 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 | |
| 55 | 56 | } | awk -F '\t' 'NF == 3 && !seen[$1]++' | LC_ALL=C sort > "$list" |
| 56 | 57 | |
| 57 | 58 | [ -s "$list" ] || { echo "licenses: go list found no module" >&2; exit 1; } |
| @@ -69,6 +70,11 @@ plus patches/ (see NOTICE). | ||
| 69 | 70 | Generated by scripts/licenses. |
| 70 | 71 | |
| 71 | 72 | EOF |
| 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' | |
| 72 | 78 | printf '================================================================================\n' |
| 73 | 79 | printf 'Go standard library (BSD-3-Clause)\n' |
| 74 | 80 | printf '================================================================================\n\n' |
| @@ -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") | |
| @@ -23,7 +23,7 @@ install -m 644 docs/linux.md "$stage/usr/share/doc/claude-cage/README.md" | ||
| 23 | 23 | install -m 755 packaging/linux/preinst "$stage/DEBIAN/preinst" |
| 24 | 24 | install -m 755 packaging/linux/preinst "$stage/DEBIAN/prerm" |
| 25 | 25 | # 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. | |
| 27 | 27 | mkdir -p "$stage/debian" |
| 28 | 28 | printf '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" |
| 29 | 29 | dependencies=$(cd "$stage" && dpkg-shlibdeps -O usr/lib/claude-cage/cage-desktop | sed -n 's/^shlibs:Depends=//p') |
| @@ -36,7 +36,7 @@ Section: devel | ||
| 36 | 36 | Priority: optional |
| 37 | 37 | Architecture: amd64 |
| 38 | 38 | Maintainer: 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 | |
| 40 | 40 | Suggests: qemu-system-x86, qemu-utils, ovmf, openssh-client, iproute2, git |
| 41 | 41 | Recommends: dbus-user-session, fonts-noto-cjk, libnotify-bin, zenity | kdialog |
| 42 | 42 | Homepage: https://github.com/Lee-xeo/Claude-Cage |
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | [CmdletBinding()] |
| 3 | 3 | param( |
| 4 | 4 | [switch]$Release, |
| 5 | 新增: [switch]$Sign, | |
| 5 | 6 | [switch]$SkipBuild, |
| 6 | 7 | [string]$AppDirectory, |
| 7 | 8 | [string]$OutputDirectory, |
| @@ -10,30 +11,34 @@ param( | ||
| 10 | 11 | . (Join-Path $PSScriptRoot 'windows-common.ps1') |
| 11 | 12 | $repository = Split-Path $PSScriptRoot -Parent |
| 12 | 13 | $version = Get-CageVersion $repository |
| 14 | 新增:$signed = $Release -or $Sign | |
| 13 | 15 | if (-not $AppDirectory) { $AppDirectory = Join-Path $repository '_output/windows-amd64/app' } |
| 14 | 16 | if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository "_output/releases/$version/windows" } |
| 15 | 17 | $AppDirectory = [IO.Path]::GetFullPath($AppDirectory) |
| 16 | 18 | $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 } | |
| 18 | 20 | if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'Cage.install-id') -Raw) -ne 'io.github.lee-xeo.claude-cage') { throw 'Invalid Cage app directory.' } |
| 19 | 21 | if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'version.txt') -Raw).Trim() -ne $version) { throw 'App version differs from VERSION; rebuild before packaging.' } |
| 20 | 22 | $makeNSIS = Get-BuildCommand @('makensis.exe', 'makensis') |
| 21 | 23 | $sevenZip = Get-BuildCommand @('7z.exe', '7zz', '7z') |
| 22 | 24 | if ($IsWindows) { |
| 23 | 25 | 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 } | |
| 24 | 29 | } else { |
| 25 | 30 | $metadata = & $sevenZip 'l' '-tPE' (Join-Path $AppDirectory 'Cage.exe') |
| 26 | 31 | if ($LASTEXITCODE -ne 0 -or -not ($metadata -match ('^ProductVersion: ' + [regex]::Escape($version) + '$'))) { throw 'Cage.exe version differs from VERSION; rebuild before packaging.' } |
| 27 | 32 | } |
| 28 | 33 | $signTool = $null |
| 29 | 删除:if ($Release) { | |
| 34 | 新增:if ($signed) { | |
| 30 | 35 | Assert-WindowsSigningConfiguration |
| 31 | 36 | 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))) { | |
| 34 | 39 | 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.' |
| 35 | 40 | } |
| 36 | 删除: Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $QemuSourceArchive) | |
| 41 | 新增: if ($Release) { Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $QemuSourceArchive) } | |
| 37 | 42 | $signTool = Get-SigningTool |
| 38 | 43 | foreach ($file in @('Cage.exe', 'resources/cage.exe', 'resources/mihomo.exe')) { |
| 39 | 44 | $signature = Get-AuthenticodeSignature -LiteralPath (Join-Path $AppDirectory $file) |
| @@ -46,29 +51,30 @@ New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null | ||
| 46 | 51 | # Verify source material before the expensive installer compression. |
| 47 | 52 | $dependencies = Get-Content -LiteralPath (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json |
| 48 | 53 | $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' } | |
| 50 | 55 | $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() | |
| 54 | 59 | foreach ($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() }) | |
| 61 | 62 | } |
| 62 | 删除:[IO.File]::WriteAllLines($manifest, $lines) | |
| 63 | 新增:@{ version = 1; files = @($ownership | Sort-Object path) } | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $manifest -Encoding utf8 | |
| 63 | 64 | $numericVersion = ($version -split '-')[0] + '.0' |
| 64 | 65 | $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) { | |
| 67 | 69 | $arguments += @("${prefix}DSIGN_PWSH=$((Get-Process -Id $PID).Path)", "${prefix}DSIGN_SCRIPT=$(Join-Path $PSScriptRoot 'sign-windows-file.ps1')") |
| 68 | 70 | } |
| 69 | 71 | $arguments += (Join-Path $repository 'packaging/windows/Cage.nsi') |
| 70 | 72 | Invoke-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 } | |
| 72 | 78 | if ((Get-Item -LiteralPath $artifact).Length -gt 512MB) { throw 'Installer exceeds the application updater 512 MiB limit.' } |
| 73 | 79 | |
| 74 | 80 | # Source materials travel beside the binary, not inside the application directory. |
| @@ -82,6 +88,16 @@ if (Test-Path -LiteralPath $qemuSource) { Remove-Item -LiteralPath $qemuSource } | ||
| 82 | 88 | Invoke-BuildTool $sevenZip @('a', '-tgzip', '-mx=9', '-bso0', '-bsp0', $qemuSource, $qemuTar) |
| 83 | 89 | Invoke-BuildTool $sevenZip @('t', '-bso0', '-bsp0', $qemuSource) |
| 84 | 90 | $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 | 新增:} | |
| 85 | 101 | if ($Release) { |
| 86 | 102 | $qemuSourceTarget = Join-Path $OutputDirectory ('qemu-' + $dependencies.qemu.version + '-windows-full-source' + [IO.Path]::GetExtension($QemuSourceArchive)) |
| 87 | 103 | Copy-Item -LiteralPath $QemuSourceArchive -Destination $qemuSourceTarget -Force |
| @@ -89,6 +105,5 @@ if ($Release) { | ||
| 89 | 105 | } |
| 90 | 106 | $sums = foreach ($file in $releaseFiles) { (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() + ' ' + [IO.Path]::GetFileName($file) } |
| 91 | 107 | [IO.File]::WriteAllLines((Join-Path $OutputDirectory 'SHA256SUMS'), $sums) |
| 92 | 删除:Remove-Item -LiteralPath $manifest | |
| 93 | 108 | Write-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.' } | |
| @@ -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() | |
| @@ -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 | 新增:} | |
| @@ -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 | |
| @@ -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}`); | |
| @@ -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.`); | |
| @@ -9,6 +9,35 @@ function Invoke-BuildTool { | ||
| 9 | 9 | if ($LASTEXITCODE -ne 0) { throw "$Tool failed with exit code $LASTEXITCODE" } |
| 10 | 10 | } |
| 11 | 11 | |
| 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 | 新增: | |
| 12 | 41 | function Get-CageVersion { |
| 13 | 42 | param([string]$Repository) |
| 14 | 43 | $value = (Get-Content -LiteralPath (Join-Path $Repository 'VERSION') -Raw).Trim() |
| @@ -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 | 新增:} | |
| @@ -33,6 +33,8 @@ type NetworkSwitch interface { | ||
| 33 | 33 | } |
| 34 | 34 | |
| 35 | 35 | type Switch struct { |
| 36 | 新增: droppedIPv6 func([]byte) | |
| 37 | 新增: | |
| 36 | 38 | Sent uint64 |
| 37 | 39 | Received uint64 |
| 38 | 40 | |
| @@ -60,6 +62,9 @@ func NewSwitch(debug bool) *Switch { | ||
| 60 | 62 | } |
| 61 | 63 | } |
| 62 | 64 | |
| 65 | 新增:// SetDroppedIPv6 is configured before Accept, only for an IPv4-only stack. | |
| 66 | 新增:func (e *Switch) SetDroppedIPv6(observe func([]byte)) { e.droppedIPv6 = observe } | |
| 67 | 新增: | |
| 63 | 68 | func (e *Switch) CAM() map[string]int { |
| 64 | 69 | e.camLock.RLock() |
| 65 | 70 | defer e.camLock.RUnlock() |
| @@ -275,7 +280,15 @@ func (e *Switch) rxBuf(_ context.Context, id int, buf []byte) { | ||
| 275 | 280 | log.Info(packet.String()) |
| 276 | 281 | } |
| 277 | 282 | |
| 283 | 新增: if len(buf) < header.EthernetMinimumSize { | |
| 284 | 新增: return | |
| 285 | 新增: } | |
| 278 | 286 | 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 | 新增: } | |
| 279 | 292 | |
| 280 | 293 | e.camLock.Lock() |
| 281 | 294 | _, exists := e.cam[eth.SourceAddress()] |
| @@ -20,6 +20,10 @@ func (o Outbound) Allows(network string, dst netip.AddrPort) bool { | ||
| 20 | 20 | type DialContext func(context.Context, string, string) (net.Conn, error) |
| 21 | 21 | |
| 22 | 22 | type 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 | 新增: | |
| 23 | 27 | DialContext DialContext `yaml:"-"` |
| 24 | 28 | DNSExchange func(context.Context, *dns.Msg) (*dns.Msg, error) `yaml:"-"` |
| 25 | 29 | // Print packets on stderr |
| @@ -12,6 +12,7 @@ import ( | ||
| 12 | 12 | "github.com/containers/gvisor-tap-vsock/pkg/tap" |
| 13 | 13 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 14 | 14 | "gvisor.dev/gvisor/pkg/tcpip" |
| 15 | 新增: "gvisor.dev/gvisor/pkg/tcpip/header" | |
| 15 | 16 | "gvisor.dev/gvisor/pkg/tcpip/link/sniffer" |
| 16 | 17 | "gvisor.dev/gvisor/pkg/tcpip/network/arp" |
| 17 | 18 | "gvisor.dev/gvisor/pkg/tcpip/network/ipv4" |
| @@ -78,6 +79,9 @@ func New(configuration *types.Configuration) (*VirtualNetwork, error) { | ||
| 78 | 79 | return nil, fmt.Errorf("cannot create network stack: %w", err) |
| 79 | 80 | } |
| 80 | 81 | |
| 82 | 新增: if configuration.DroppedIPv6 != nil && stack.NetworkProtocolInstance(header.IPv6ProtocolNumber) == nil { | |
| 83 | 新增: networkSwitch.SetDroppedIPv6(configuration.DroppedIPv6) | |
| 84 | 新增: } | |
| 81 | 85 | mux, err := addServices(configuration, stack, ipPool) |
| 82 | 86 | if err != nil { |
| 83 | 87 | return nil, fmt.Errorf("cannot add network services: %w", err) |

